You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dialogflow中实现预约参数的时间合法性验证

Solution: Add Pre-Booking Validation Checks

Got it, let's integrate those two validation rules directly into your makeAppointment function—we want to catch invalid requests early before even hitting the calendar API. Here's the modified code with clear, commented checks:

Modified Code with Validation

function makeAppointment (agent) {
  const appointmentDuration = 1; // 1 hour appointment
  const timeZoneOffset = /* your existing time zone offset value */;
  const openHourTime = '09:00';
  const closeHourTime = '16:00';

  // Convert user input to start/end date objects
  const dateTimeStart = convertParametersDate(agent.parameters.date, agent.parameters.time, timeZoneOffset);
  const dateTimeEnd = addHours(dateTimeStart, appointmentDuration);
  const appointmentTimeString = getLocaleTimeString(dateTimeStart);
  const appointmentDateString = getLocaleDateString(dateTimeStart);

  // --------------------------
  // Validation Rule 1: Reject past dates/times
  // --------------------------
  const currentTime = new Date();
  if (dateTimeStart < currentTime) {
    agent.add(`you can't book a date passed`);
    return Promise.resolve(); // Exit early to avoid further processing
  }

  // --------------------------
  // Validation Rule 2: Reject outside business hours
  // --------------------------
  // Helper function to convert time string (HH:MM) to total minutes in a day
  const timeToMinutes = (timeStr) => {
    const [hours, minutes] = timeStr.split(':').map(Number);
    return hours * 60 + minutes;
  };

  const openMinutes = timeToMinutes(openHourTime);
  const closeMinutes = timeToMinutes(closeHourTime);
  const startMinutes = dateTimeStart.getHours() * 60 + dateTimeStart.getMinutes();
  const endMinutes = dateTimeEnd.getHours() * 60 + dateTimeEnd.getMinutes();

  // Check if start is before opening OR end is after closing
  if (startMinutes < openMinutes || endMinutes > closeMinutes) {
    agent.add(`Sorry, we're only open between ${openHourTime} and ${closeHourTime}. Please choose a time within those hours.`);
    return Promise.resolve(); // Exit early
  }

  // Proceed with calendar availability check and booking if validations pass
  return createCalendarEvent(dateTimeStart, dateTimeEnd).then(() => {
    agent.add(`Done 😊`);
  }).catch((err) => {
    agent.add(` 😔Sorry check other date. Error: ${err.message || 'Unknown issue'}`);
  });
}

function createCalendarEvent (dateTimeStart, dateTimeEnd) {
  return new Promise((resolve, reject) => {
    calendar.events.list({
      auth: serviceAccountAuth,
      calendarId: calendarId,
      timeMin: dateTimeStart.toISOString(),
      timeMax: dateTimeEnd.toISOString()
    }, (err, calendarResponse) => {
      if (err || calendarResponse.data.items.length > 0) {
        reject(err || new Error('Die angeforderte Zeit kollidiert mit einem anderen Termin'));
      } else {
        calendar.events.insert({
          auth: serviceAccountAuth,
          calendarId: calendarId,
          resource: {
            summary: 'Appointment',
            start: {dateTime: dateTimeStart.toISOString()}, // Fixed: use ISO string for calendar API
            end: {dateTime: dateTimeEnd.toISOString()}
          }
        }, (err, event) => {
          err ? reject(err) : resolve(event);
        });
      }
    });
  });
}

Key Changes Explained

  • Validation Rule 1: We compare the requested start time directly to the current time. If it's in the past, we send the error message and exit early using Promise.resolve() to avoid unnecessary API calls.
  • Validation Rule 2: Created a small helper timeToMinutes function to convert time strings to total minutes (easier to compare than date objects). We check if the appointment starts before opening hours OR ends after closing hours, then send a clear error message.
  • Minor Fix: Updated the calendar event insert to use toISOString() for start/end times—this is required for Google Calendar API to parse dates correctly.

内容的提问来源于stack exchange,提问作者user7575848

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:47:37