AI Voice Agent Backend
Module 13 · ai · intermediate
book.js
// book_appointment({ name, phone, date: 'YYYY-MM-DD', time: 'HH:mm', service? }) → booking
const s = $('Business Settings').first().json;
const db = $getWorkflowStaticData('global');
db.bookings = db.bookings ?? {};
const speak = (t) => DateTime.fromFormat(t, 'HH:mm').toFormat('h:mm a').replace(':00', '');
return $input.all().map(({ json }) => {
const a = json.args;
const name = String(a.name ?? '').trim();
const phone = String(a.phone ?? '').replace(/[^\d+]/g, '');
const date = String(a.date ?? '').trim();
const time = String(a.time ?? '').trim().padStart(5, '0');
const service = String(a.service ?? s.default_service).trim();
const day = DateTime.fromISO(date);
const hour = Number(time.split(':')[0]);
let result;
const missing = [!name && 'name', phone.length < 7 && 'phone number', !day.isValid && 'date', !/^\d{2}:00$/.test(time) && 'time'].filter(Boolean);
if (missing.length) {
result = { ok: false, message: `To book, I still need your ${missing.join(' and ')}.` };
} else if (day.startOf('day') < DateTime.now().startOf('day') || !s.open_days.includes(day.weekday) || hour < s.open_hour || hour >= s.close_hour) {
result = { ok: false, message: `We can't book ${day.toFormat('cccc')} at ${speak(time)}. We're open Monday to Friday, ${speak(String(s.open_hour).padStart(2, '0') + ':00')} to ${speak(String(s.close_hour).padStart(2, '0') + ':00')}.` };
} else if (Object.values(db.bookings).some((b) => b.date === date && b.time === time)) {
result = { ok: false, message: `Sorry, ${speak(time)} on ${day.toFormat('cccc')} was just taken. Shall I check other times that day?` };
} else {
let id;
do { id = 'BK-' + Math.floor(1000 + Math.random() * 9000); } while (db.bookings[id]);
db.bookings[id] = { id, name, phone, date, time, service, created_at: DateTime.now().toISO() };
result = {
ok: true,
booking_id: id,
message: `You're booked for ${service} on ${day.toFormat('cccc, LLLL d')} at ${speak(time)}, ${name.split(' ')[0]}. Your booking number is ${id.replace('-', '').split('').join(' ')}.`,
};
}
return { json: { ...json, result } };
});