Skip to content
// Confirm the booking: Google mode needs an event id from Google Calendar; internal mode keeps its own calendar.
const x = $('Decide Next Step').first().json;
const res = $input.first().json;
const db = $getWorkflowStaticData('global');
const lead = db.leads[x.lead_id];
const google = x.calendar_mode !== 'internal';
const ok = google ? Boolean(res.id) && !res.lead_id : true; // without a credential the node passes our item through (it has lead_id)
if (ok) {
  db.bookings[x.booking.start] = lead.id;
  for (const [k, h] of Object.entries(db.holds)) if (h.lead_id === lead.id) delete db.holds[k];
  lead.status = 'booked'; lead.booking = { ...x.booking, event_id: google ? res.id : null, booked_at: x.event.start };
  lead.offered = [];
  return [{ json: { ...x, status: 'booked', booked: true, event_id: google ? res.id : null } }];
}
const error = String(res.error?.message ?? res.error ?? 'no event id returned (check the Google Calendar credential)').slice(0, 300);
lead.messages.push({ from: 'bot', text: '(booking failed, owner alerted)', at: x.event.start });
return [{ json: { ...x, booked: false, booking_error: error, action: 'manual_scheduling', alert_owner: true,
  reply: `Thanks! I couldn't confirm that time automatically, so ${$('Settings (edit me)').first().json.owner_name} will email you to lock it in.` } }];