From 82402498eb49946581fa96f2dee704f3328d1391 Mon Sep 17 00:00:00 2001 From: KesterJJ <95241742+KesterJJ@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:18:10 +0000 Subject: [PATCH] feat(place/vip_visitor_automation): implement VIP visitor workflow --- drivers/place/vip_visitor_automation.cr | 438 +++++++++++++++-- drivers/place/vip_visitor_automation_spec.cr | 255 +++++++++- drivers/place/vip_visitor_planner.cr | 122 ----- drivers/place/vip_visitor_readme.md | 480 +++++++++++-------- 4 files changed, 914 insertions(+), 381 deletions(-) delete mode 100644 drivers/place/vip_visitor_planner.cr diff --git a/drivers/place/vip_visitor_automation.cr b/drivers/place/vip_visitor_automation.cr index 814d5bdb58..0acdd53418 100644 --- a/drivers/place/vip_visitor_automation.cr +++ b/drivers/place/vip_visitor_automation.cr @@ -3,13 +3,12 @@ require "placeos-driver/interface/mailer" require "placeos-driver/interface/mailer_templates" require "placeos-models/placeos-models/base/jwt" require "jwt" +require "json" require "uuid" require "digest/sha256" -require "./vip_visitor_planner" # One instance per building. Planner is provided by Calendar_1. class Place::VIPVisitorAutomation < PlaceOS::Driver - include Place::VIPVisitorPlanner include PlaceOS::Driver::Interface::MailerTemplates descriptive_name "VIP Visitor Automation" @@ -24,17 +23,10 @@ class Place::VIPVisitorAutomation < PlaceOS::Driver building_id: "", planner_group_id: "", timezone: "Asia/Dubai", - confirmation_field: "vip_confirmed", confirmation_url: "", domain_uri: "", jwt_private_key: PlaceOS::Model::JWTBase.private_key, handler_emails: [] of String, - notification_emails: [] of String, - notify_arrival_departure: false, - location: "", - google_maps_url: "", - parking_details: "", - valet_details: "", planner_task_assignments: {} of String => Array(String), }) @@ -69,64 +61,246 @@ class Place::VIPVisitorAutomation < PlaceOS::Driver record_error(error) end - # Also provides an operator retry after a downstream failure. + # Runs the applicable stages, or resumes after a downstream failure. @[Security(Level::Administrator)] def process_booking(booking_id : Int64, action : String = "changed") @lock.synchronize do - booking = staff_api.get_booking(booking_id).get - return false unless booking["booking_type"]? == "vip-visitor" - building = setting(String, :building_id).strip - raise "building_id must be configured" if building.empty? - return false unless booking["zones"]?.try(&.as_a.includes?(JSON::Any.new(building))) - ext = booking["extension_data"]?.try(&.as_h) || {} of String => JSON::Any - return false if booking["parent_id"]?.try { |id| !id.raw.nil? && !id.to_s.empty? } - return false if ext["parent_id"]?.try { |id| !id.raw.nil? && !id.to_s.empty? } - return false if booking["deleted"]? == true || booking["cancelled"]? == true || booking["rejected"]? == true || action.in?("cancelled", "deleted", "rejected") - state = @workflows[booking_id.to_s] ||= {} of String => JSON::Any - confirmed = ext[setting?(String, :confirmation_field) || "vip_confirmed"]? == true - signature = Digest::SHA256.hexdigest({ - booking["booking_start"]?, booking["booking_end"]?, booking["title"]?, booking["asset_id"]?, - ext["vip_assistant_email"]?, ext["vip_assistant_name"]?, - }.to_json) - unless confirmed || state["invitation_signature"]? == signature - send_invitation(booking, ext) - state["invited"] = JSON::Any.new(true) - state["invitation_signature"] = JSON::Any.new(signature) - checkpoint - end - if confirmed - unless state["confirmation_sent"]? == true - recipients = setting(Array(String), :handler_emails).reject(&.strip.empty?) - raise "handler_emails must be configured" if recipients.empty? - send_notice(recipients, "confirmed", booking, ext) - state["confirmation_sent"] = JSON::Any.new(true) - checkpoint - end - provision_plan(booking, state) { checkpoint } - end - if setting?(Bool, :notify_arrival_departure) && action.in?("arrived", "departed") && state[action]? != true - recipients = setting(Array(String), :notification_emails).reject(&.strip.empty?) - unless recipients.empty? - send_notice(recipients, action, booking, ext) - state[action] = JSON::Any.new(true) - checkpoint - end + booking = fetch_vip_booking(booking_id) + return false unless booking + return false if action.in?("cancelled", "deleted", "rejected") + state = workflow(booking_id) + if confirmed?(booking) + send_confirmation_for(booking, state) + provision_plan_for(booking, state) { checkpoint } + else + send_invitation_for(booking, state) end + send_notification_for(booking, state, action) if action.in?("arrived", "departed") self[:last_booking_id] = booking_id self[:last_error] = nil true end + rescue error + record_error(error) + raise error end - def template_fields : Array(TemplateFields) - fields = %w(booking_id booking_title booking_user_name booking_user_email booking_booking_start booking_booking_end event_date event_time event_end_time location google_maps_url parking_details valet_details submitted_details confirmation_url visitor_email qr_code vip_title vip_full_name vip_mobile_number vip_assistant_name vip_assistant_email vip_assistant_mobile_number protocol_officer_name protocol_officer_mobile_number vehicle_plate_number vehicle_plate_type welcome_beverage welcome_beverage_notes).map do |name| - {name: name, description: name.gsub('_', ' ')} + # Look up numeric IDs for Backoffice testing, using an explicit time window. + @[Security(Level::Administrator)] + def list_bookings(period_start : Int64, period_end : Int64) + raise "period_end must be after period_start" unless period_end > period_start + bookings = staff_api.query_bookings(type: "vip-visitor", period_start: period_start, + period_end: period_end, zones: [building_id]).get + bookings.as_a.select { |booking| eligible_booking?(booking) } + end + + @[Security(Level::Administrator)] + def get_booking(booking_id : Int64) + require_booking(booking_id) + end + + @[Security(Level::Administrator)] + def workflow_status(booking_id : Int64) + @lock.synchronize { workflow_snapshot(booking_id) } + end + + # Read-only: no JWT, email, booking update or Planner resource is created. + @[Security(Level::Administrator)] + def preview_booking(booking_id : Int64) + @lock.synchronize do + booking = require_booking(booking_id) + state = @workflows[booking_id.to_s]? || {} of String => JSON::Any + { + booking_id: booking_id, confirmed: confirmed?(booking), + planner_group_id: planner_group_id(booking, state), + tasks: vip_planner_tasks(booking), template_args: template_args(booking, extension_data(booking)), + workflow_state: workflow_snapshot(booking_id), + } + end + end + + @[Security(Level::Administrator)] + def send_invitation(booking_id : Int64, force : Bool = false) + with_booking(booking_id) do |booking, state| + raise "booking is already confirmed" if confirmed?(booking) + send_invitation_for(booking, state, force) + end + end + + @[Security(Level::Administrator)] + def send_confirmation(booking_id : Int64) + with_booking(booking_id) do |booking, state| + require_confirmation(booking) + send_confirmation_for(booking, state) + end + end + + @[Security(Level::Administrator)] + def provision_plan(booking_id : Int64) + with_booking(booking_id) do |booking, state| + require_confirmation(booking) + provision_plan_for(booking, state) { checkpoint } + state["plan_id"] + end + end + + @[Security(Level::Administrator)] + def send_arrival_notification(booking_id : Int64) + with_booking(booking_id) { |booking, state| send_notification_for(booking, state, "arrived") } + end + + @[Security(Level::Administrator)] + def send_departure_notification(booking_id : Int64) + with_booking(booking_id) { |booking, state| send_notification_for(booking, state, "departed") } + end + + # Matches the AECB enrolment form's field names. This is an authenticated + # operator entry point, not an endpoint accessible with the guest JWT. + @[Security(Level::Administrator)] + def submit_confirmation( + booking_id : Int64, + vip_title : String, + vip_full_name : String, + vip_contact_number : String, + assistant_name : String, + assistant_contact_number : String, + protocol_officer_name : String, + protocol_officer_contact_number : String, + vehicle_plate_number : String, + vehicle_plate_type : String, + beverage_preference : String, + beverage_notes : String = "", + ) + raise "vip_full_name is required" if vip_full_name.strip.empty? + beverage = beverage_preference.strip.downcase + raise "beverage_preference must be none, standard or custom" unless beverage.in?("none", "standard", "custom") + @lock.synchronize do + require_booking(booking_id) + # Merge just the form fields, preserving internal options and destination. + fields = JSON.parse({ + vip_title: vip_title, vip_full_name: vip_full_name, vip_contact_number: vip_contact_number, + assistant_name: assistant_name, assistant_contact_number: assistant_contact_number, + protocol_officer_name: protocol_officer_name, protocol_officer_contact_number: protocol_officer_contact_number, + vehicle_plate_number: vehicle_plate_number, vehicle_plate_type: vehicle_plate_type, + beverage_preference: beverage, beverage_notes: beverage == "custom" ? beverage_notes : "", vip_confirmed: true, + }.to_json).as_h + # Invoke the workflow directly after saving; do not also publish an event. + staff_api.booking_extension_data(booking_id, fields, signal_changes: false).get end + process_booking(booking_id) + rescue error + record_error(error) + raise error + end + + TEMPLATE_FIELD_NAMES = %w(booking_id booking_title booking_user_name booking_user_email booking_booking_start booking_booking_end event_date event_time event_end_time building_name level_name submitted_details confirmation_url visitor_email qr_code vip_title vip_full_name vip_contact_number assistant_name assistant_contact_number protocol_officer_name protocol_officer_contact_number vehicle_plate_number vehicle_plate_type beverage_preference beverage_notes vip_mobile_number vip_assistant_name vip_assistant_email vip_assistant_mobile_number protocol_officer_mobile_number welcome_beverage welcome_beverage_notes) + + def template_fields : Array(TemplateFields) + fields = TEMPLATE_FIELD_NAMES.map { |name| {name: name, description: name.gsub('_', ' ')} } %w(invitation confirmed arrived departed).map do |name| TemplateFields.new(trigger: {"vip_visitor", name}, name: "VIP visitor #{name}", description: "VIP visitor #{name}", fields: fields) end end + private def building_id : String + id = setting(String, :building_id).strip + raise "building_id must be configured" if id.empty? + id + end + + private def extension_data(booking : JSON::Any) : Hash(String, JSON::Any) + booking["extension_data"]?.try(&.as_h) || {} of String => JSON::Any + end + + private def confirmed?(booking : JSON::Any) : Bool + extension_data(booking)["vip_confirmed"]? == true + end + + private def require_confirmation(booking : JSON::Any) + raise "booking must be confirmed before this stage" unless confirmed?(booking) + end + + private def eligible_booking?(booking : JSON::Any) : Bool + return false unless booking["booking_type"]? == "vip-visitor" + return false unless booking["zones"]?.try(&.as_a.includes?(JSON::Any.new(building_id))) + return false if booking["parent_id"]?.try { |id| !id.raw.nil? && !id.to_s.empty? } + return false if extension_data(booking)["parent_id"]?.try { |id| !id.raw.nil? && !id.to_s.empty? } + !%w(deleted cancelled rejected).any? { |key| booking[key]? == true } + end + + private def fetch_vip_booking(booking_id : Int64) : JSON::Any? + booking = staff_api.get_booking(booking_id).get + eligible_booking?(booking) ? booking : nil + end + + private def require_booking(booking_id : Int64) : JSON::Any + fetch_vip_booking(booking_id) || raise "booking must be an active standalone VIP booking in the configured building" + end + + private def workflow(booking_id : Int64) : Hash(String, JSON::Any) + @workflows[booking_id.to_s] ||= {} of String => JSON::Any + end + + private def workflow_snapshot(booking_id : Int64) : JSON::Any + JSON.parse((@workflows[booking_id.to_s]? || {} of String => JSON::Any).to_json) + end + + private def with_booking(booking_id : Int64, &) + @lock.synchronize do + booking = require_booking(booking_id) + result = yield booking, workflow(booking_id) + self[:last_booking_id] = booking_id + self[:last_error] = nil + result + end + rescue error + record_error(error) + raise error + end + + private def send_invitation_for(booking : JSON::Any, state : Hash(String, JSON::Any), force : Bool = false) : Bool + ext = extension_data(booking) + signature = Digest::SHA256.hexdigest({ + booking["booking_start"]?, booking["booking_end"]?, booking["title"]?, booking["asset_id"]?, + ext["vip_assistant_email"]?, ext["vip_assistant_name"]?, + }.to_json) + return false if !force && state["invitation_signature"]? == signature + send_invitation_email(booking, ext) + state["invited"] = JSON::Any.new(true) + state["invitation_signature"] = JSON::Any.new(signature) + checkpoint + true + end + + private def send_confirmation_for(booking : JSON::Any, state : Hash(String, JSON::Any)) : Bool + return false if state["confirmation_sent"]? == true + recipients = setting(Array(String), :handler_emails).reject(&.strip.empty?) + raise "handler_emails must be configured" if recipients.empty? + send_notice(recipients, "confirmed", booking, extension_data(booking)) + state["confirmation_sent"] = JSON::Any.new(true) + checkpoint + true + end + + private def template_zone_ids : Array(String) + # Match Template Mailer's default send_template lookup. TemplateItems in + # supported driver shards accepts scalar values, not zone-ID arrays. + [mailer.org_zone_id.get.as_s, mailer.building_zone_id.get.as_s] + end + + private def send_notification_for(booking : JSON::Any, state : Hash(String, JSON::Any), action : String) : Bool + return false if state[action]? == true + # Without a configured metadata template, do not fall through to Mailer_2. + template = mailer.find_template?("vip_visitor.#{action}", template_zone_ids).get + return false if template.raw.nil? + host = booking["user_email"]?.try(&.as_s?).presence + raise "booking user_email is required for notifications" unless host + send_notice([host], action, booking, extension_data(booking)) + state[action] = JSON::Any.new(true) + checkpoint + true + end + private def checkpoint define_setting(:workflow_state, @workflows) end @@ -139,6 +313,7 @@ class Place::VIPVisitorAutomation < PlaceOS::Driver private def template_args(booking, ext) args = Interface::Mailer::TemplateItems.new + TEMPLATE_FIELD_NAMES.each { |name| args[name] = nil } ext.each { |key, value| args[key] = value.raw.is_a?(String) ? value.as_s : value.to_json } %w(id title user_name user_email booking_start booking_end).each do |key| args["booking_#{key}"] = booking[key]?.try(&.to_s) @@ -149,16 +324,41 @@ class Place::VIPVisitorAutomation < PlaceOS::Driver args["event_time"] = start.to_s("%H:%M %Z") args["event_end_time"] = Time.unix(booking["booking_end"].as_i64).in(location).to_s("%H:%M %Z") args["submitted_details"] = ext.to_json - %w(location google_maps_url parking_details valet_details).each { |key| args[key] = setting?(String, key) || "" } + # Provide the form's current values under both UI and document field names. + { + "vip_mobile_number" => "vip_contact_number", + "vip_assistant_name" => "assistant_name", + "vip_assistant_mobile_number" => "assistant_contact_number", + "protocol_officer_mobile_number" => "protocol_officer_contact_number", + "welcome_beverage" => "beverage_preference", + "welcome_beverage_notes" => "beverage_notes", + }.each do |document_key, form_key| + args[document_key] = args[form_key] if ext.has_key?(form_key) + end + building = staff_api.zone(building_id).get + args["building_name"] = zone_display_name(building) + args["level_name"] = "" + booking["zones"].as_a.each do |id| + next if id.as_s == building_id + zone = staff_api.zone(id.as_s).get + if zone["tags"]?.try(&.as_a.includes?(JSON::Any.new("level"))) + args["level_name"] = zone_display_name(zone) + break + end + end args end + private def zone_display_name(zone : JSON::Any) : String + zone["display_name"]?.try(&.as_s?).presence || zone["name"]?.try(&.as_s?) || "" + end + private def send_notice(to, template, booking, ext) result = mailer.send_template(to, {"vip_visitor", template}, template_args(booking, ext)).get raise "VIP #{template} email was not sent; check template configuration" if result.raw.nil? || result == false end - private def send_invitation(booking, ext) + private def send_invitation_email(booking, ext) assistant = ext["vip_assistant_email"]?.try(&.as_s).try(&.strip) raise "vip_assistant_email is required" unless assistant && !assistant.empty? url = URI.parse(setting(String, :confirmation_url)) @@ -194,4 +394,136 @@ class Place::VIPVisitorAutomation < PlaceOS::Driver result = mailer.send_template(assistant, {"vip_visitor", "invitation"}, args, resource_attachments: attachments).get raise "VIP invitation was not sent; check template configuration" if result.raw.nil? || result == false end + + # Planner orchestration uses the existing Calendar_1 module. + private def provision_plan_for(booking : JSON::Any, state : Hash(String, JSON::Any), &checkpoint : ->) + return if state["planner_complete"]?.try(&.as_bool?) == true + + group_id = planner_group_id(booking, state) + raise "planner_group_id must identify an existing Microsoft 365 group" if group_id.empty? + tasks = vip_planner_tasks(booking) + assignments = setting?(Hash(String, Array(String)), :planner_task_assignments) || {} of String => Array(String) + + unless state["plan_id"]? + name = booking["extension_data"]?.try(&.["vip_full_name"]?).try(&.as_s?).presence || + booking["title"]?.try(&.as_s?).presence || "VIP Visit" + title = "#{name} - VIP Visit (#{booking["id"]})" + raise "Planner plan title exceeds 255 characters" if title.size > 255 + result = calendar.create_plan(group_id, title).get + state["plan_id"] = JSON::Any.new(vip_planner_id(result)) + # Once the plan exists, retries keep its destination even after edits. + state["planner_group_id"] = JSON::Any.new(group_id) + yield + end + plan_id = state["plan_id"].as_s + + buckets = state["bucket_ids"]?.try(&.as_h) || {} of String => JSON::Any + state["bucket_ids"] = JSON::Any.new(buckets) + {"To Do", "In Progress", "Done"}.each do |name| + next if buckets[name]? + # Place each bucket after the preceding one, using the service's hint. + # https://learn.microsoft.com/en-us/graph/api/resources/planner-order-hint-format + order_hint = "#{state["bucket_order_hint"]?.try(&.as_s) || ""} !" + result = calendar.create_bucket(plan_id, name, order_hint).get + buckets[name] = JSON::Any.new(vip_planner_id(result)) + state["bucket_order_hint"] = result["orderHint"]? || JSON::Any.new(order_hint) + yield + end + + task_ids = state["task_ids"]?.try(&.as_h) || {} of String => JSON::Any + state["task_ids"] = JSON::Any.new(task_ids) + due_at = booking["booking_start"]?.try(&.as_i64?).try { |value| Time.unix(value).to_rfc3339 } + tasks.each do |key, title| + next if task_ids[key]? + result = calendar.create_task( + plan_id: plan_id, + title: title, + bucket_id: buckets["To Do"].as_s, + assigned_to_user_ids: assignments[key]?, + due_date_time: due_at, + percent_complete: 0, + ).get + task_ids[key] = JSON::Any.new(vip_planner_id(result)) + yield + end + state["planner_complete"] = JSON::Any.new(true) + yield + end + + private def planner_group_id(booking : JSON::Any, state : Hash(String, JSON::Any)) : String + state["planner_group_id"]?.try(&.as_s?).presence || + extension_data(booking)["planner_group_id"]?.try(&.as_s?).try(&.strip).presence || + setting?(String, :planner_group_id).try(&.strip) || "" + end + + private def vip_planner_id(result : JSON::Any) : String + id = result["id"]?.try(&.as_s?).presence + raise "Calendar returned no Planner resource ID" unless id + id + end + + private def vip_planner_tasks(booking : JSON::Any) : Hash(String, String) + data = booking["extension_data"]?.try(&.as_h?) || {} of String => JSON::Any + tasks = {} of String => String + if value = vip_planner_option(data, "meet_greet") + label = case value.downcase + when "internal" then "Internal" + when "airport", "external - airport", "external_airport" then "Airport" + else value + end + tasks["meet_greet"] = "Meet & Greet - #{label}" + end + { + "tour" => "Walkthrough/Guided Tour", + "gift" => "Giveaway Gift", + "photographer" => "Photographer", + "welcome_screen" => "Welcome screen", + "presentation" => "Presentation", + }.each do |key, title| + selected = key == "tour" ? (data[key]? || data["walkthrough"]?) : data[key]? + tasks[key] = title if selected.try(&.as_bool?) == true + end + beverage_key = data.has_key?("beverage_preference") ? "beverage_preference" : "welcome_beverage" + if value = vip_planner_option(data, beverage_key) + # A submitted choice replaces the booked preference, including cleared + # notes. Do not revive organiser notes after the assistant clears them. + notes = if data.has_key?("beverage_preference") + value.downcase == "custom" ? data["beverage_notes"]?.try(&.as_s?).presence : nil + else + data["beverage_notes"]?.try(&.as_s?).presence || + data["welcome_beverage_notes"]?.try(&.as_s?).presence || + data["welcome_beverage_custom"]?.try(&.as_s?).presence + end + tasks["welcome_beverage"] = "Welcome Beverage - #{value}#{notes ? ": #{notes}" : ""}" + end + if restaurant = data["restaurant_reservation"]?.try(&.as_h?) + name = restaurant["name"]?.try(&.as_s?).presence + timestamp = restaurant["time"]?.try(&.as_i64?) + raise "Restaurant reservation requires name and Unix time" unless name && timestamp + zone = Time::Location.load(setting?(String, :timezone) || "Asia/Dubai") + time = Time.unix(timestamp).in(zone).to_s("%Y-%m-%d %H:%M %z") + address = restaurant["address"]?.try(&.as_s?).presence + tasks["restaurant_reservation"] = "Restaurant Reservation - #{name}#{address ? ", #{address}" : ""} - #{time}" + end + if value = vip_planner_option(data, "driver") + label = case value.downcase + when "in_house", "in-house" then "In-house" + when "third_party", "third party" then "Third Party" + else value + end + tasks["driver"] = "Driver - #{label}" + end + tasks.each do |key, title| + # Calendar currently has no task-details API. Keep all requested details + # in the title and fail explicitly rather than silently dropping data. + raise "Planner task #{key} exceeds 255 characters" if title.size > 255 + end + tasks + end + + private def vip_planner_option(data : Hash(String, JSON::Any), key : String) : String? + value = data[key]?.try(&.as_s?).try(&.strip) + return nil if value.nil? || value.empty? || value.downcase == "none" + value + end end diff --git a/drivers/place/vip_visitor_automation_spec.cr b/drivers/place/vip_visitor_automation_spec.cr index 34a2c12db2..bdc4f0f22e 100644 --- a/drivers/place/vip_visitor_automation_spec.cr +++ b/drivers/place/vip_visitor_automation_spec.cr @@ -5,6 +5,57 @@ require "base64" class VIPStaffMock < DriverSpecs::MockDriver @start = (Time.utc + 1.day).to_unix @pending_offset = 0_i64 + @overrides = {} of Int64 => Hash(String, JSON::Any) + @level_display_name = "Level Display" + + def set_level_display_name(value : String) + @level_display_name = value + end + + def zone(zone_id : String) + case zone_id + when "zone-aecb" + {id: zone_id, name: "Building Internal", display_name: "Building Display", tags: ["building"]} + when "zone-level" + {id: zone_id, name: "Level Internal", display_name: @level_display_name, tags: ["level"], parent_id: "zone-aecb"} + else + raise "unexpected zone #{zone_id}" + end + end + + def query_bookings( + type : String? = nil, + period_start : Int64? = nil, + period_end : Int64? = nil, + zones : Array(String) = [] of String, + user : String? = nil, + email : String? = nil, + state : String? = nil, + event_id : String? = nil, + ical_uid : String? = nil, + created_before : Int64? = nil, + created_after : Int64? = nil, + approved : Bool? = nil, + rejected : Bool? = nil, + checked_in : Bool? = nil, + include_checked_out : Bool? = nil, + extension_data : JSON::Any? = nil, + deleted : Bool? = nil, + asset_id : String? = nil, + limit : Int32? = nil, + ) + raise "wrong booking filter" unless type == "vip-visitor" && zones == ["zone-aecb"] + raise "missing query window" unless period_start && period_end && period_start < period_end + [get_booking(1)] + end + + def booking_extension_data(booking_id : String | Int64, extension_data : Hash(String, JSON::Any), instance : Int64? = nil, signal_changes : Bool = false) + id = booking_id.to_i64 + (@overrides[id] ||= {} of String => JSON::Any).merge!(extension_data) + self[:last_extension_update] = extension_data + self[:signal_changes] = signal_changes + get_booking(id) + end def postpone_pending @pending_offset = 3600_i64 @@ -15,7 +66,7 @@ class VIPStaffMock < DriverSpecs::MockDriver start = @start + (id == 1 ? @pending_offset : 0_i64) booking = JSON.parse({ id: id, booking_type: "vip-visitor", booking_start: start, - booking_end: start + 3600, zones: ["zone-aecb"], title: "VIP Guest", + booking_end: start + 3600, zones: ["zone-aecb", "zone-level"], title: "VIP Guest", asset_id: "vip@example.net", user_email: "host@example.com", booked_by_email: "booker@example.com", booked_by_name: "Booker", extension_data: { @@ -61,6 +112,9 @@ class VIPStaffMock < DriverSpecs::MockDriver when 14 data.merge!(JSON.parse({welcome_beverage: "Custom", welcome_beverage_custom: "Juice"}.to_json).as_h) end + if overrides = @overrides[id]? + data.merge!(overrides) + end booking end end @@ -70,15 +124,27 @@ class VIPCalendarMock < DriverSpecs::MockDriver @buckets = [] of String @tasks = [] of String @failed_once = false + @fail_next_plan = false + @groups = [] of String + + def fail_next_plan + @fail_next_plan = true + end def on_load self[:plans] = @plans self[:buckets] = @buckets self[:tasks] = @tasks + self[:groups] = @groups end def create_plan(group_id : String, title : String) - raise "wrong group" unless group_id == "group-aecb" + @groups << group_id + self[:groups] = @groups + if @fail_next_plan + @fail_next_plan = false + raise "temporary plan creation failure" + end @plans << title self[:plans] = @plans {id: "plan-#{@plans.size}"} @@ -120,9 +186,34 @@ end class VIPMailerMock < DriverSpecs::MockDriver include PlaceOS::Driver::Interface::Mailer @recipients = [] of String + @sent_templates = [] of String + @missing_templates = [] of String + + def org_zone_id : String + "zone-org" + end + + def building_zone_id : String + "zone-aecb" + end + + def disable_template(template : String) + @missing_templates << template + end + + def enable_template(template : String) + @missing_templates.delete(template) + end + + def find_template?(template : String, zone_ids : Array(String)) : Hash(String, String | Int64)? + raise "template lookup must match the mailer default context" unless zone_ids == ["zone-org", "zone-aecb"] + return nil if @missing_templates.includes?(template) + {"trigger" => template} of String => String | Int64 + end def on_load self[:recipients] = @recipients + self[:templates] = @sent_templates end def generate_png_qrcode(text : String, size : Int32 = 128) : String @@ -140,6 +231,8 @@ class VIPMailerMock < DriverSpecs::MockDriver from : String | Array(String) | Nil = nil, reply_to : String | Array(String) | Nil = nil, ) + @sent_templates << template.join(".") + self[:templates] = @sent_templates @recipients.concat(to.is_a?(String) ? [to] : to) self[:recipients] = @recipients self[:last_args] = args @@ -217,7 +310,13 @@ DriverSpecs.mock_driver "Place::VIPVisitorAutomation" do expect_raises(Exception) { exec(:process_booking, 9).get } system(:Calendar)[:tasks].as_a.size.should eq 10 + # The plan already exists, so an edited booking cannot redirect a retry. + system(:StaffAPI).as(VIPStaffMock).booking_extension_data(9, JSON.parse({planner_group_id: "group-changed"}.to_json).as_h) + exec(:workflow_status, 9).get["planner_group_id"].should eq "group-aecb" + exec(:preview_booking, 9).get["planner_group_id"].should eq "group-aecb" + plan_attempts = system(:Calendar)[:groups].as_a.size exec(:process_booking, 9).get + system(:Calendar)[:groups].as_a.size.should eq plan_attempts system(:Calendar)[:plans].as_a.size.should eq 3 system(:Calendar)[:buckets].as_a.size.should eq 9 system(:Calendar)[:tasks].as_a.size.should eq 11 @@ -254,20 +353,19 @@ DriverSpecs.mock_driver "Place::VIPVisitorAutomation" do settings({ building_id: "zone-aecb", planner_group_id: "group-aecb", confirmation_url: "https://example.com/vip-confirmation", domain_uri: "https://example.com", - handler_emails: ["handler@example.com"], notify_arrival_departure: true, - notification_emails: ["manager@example.com"], + handler_emails: ["handler@example.com"], planner_task_assignments: {meet_greet: ["user-greeter"]}, }) publish("staff/booking/changed", {id: 15, action: "checked_in", checked_in: true}.to_json) sleep 0.5 publish("staff/guest/checkin", {booking_id: 15, action: "checkin", checkin: true}.to_json) sleep 0.5 - system(:Mailer)[:recipients].as_a.count { |email| email == "manager@example.com" }.should eq 1 + system(:Mailer)[:recipients].as_a.count { |email| email == "host@example.com" }.should eq 1 publish("staff/guest/checkin", {booking_id: 15, action: "checkin", checkin: false}.to_json) sleep 0.5 publish("staff/booking/changed", {id: 15, action: "checked_in", checked_in: false}.to_json) sleep 0.5 - system(:Mailer)[:recipients].as_a.count { |email| email == "manager@example.com" }.should eq 2 + system(:Mailer)[:recipients].as_a.count { |email| email == "host@example.com" }.should eq 2 # Editing a pending visit refreshes its invitation, without accepting it. system(:StaffAPI).as(VIPStaffMock).postpone_pending @@ -276,4 +374,149 @@ DriverSpecs.mock_driver "Place::VIPVisitorAutomation" do system(:Calendar)[:plans].as_a.size.should eq 7 exec(:process_booking, 1).get system(:Mailer)[:recipients].as_a.count { |email| email == "assistant@example.net" }.should eq 2 + + # Read-only Backoffice inspection exposes the real booking IDs, zone display + # names and planned tasks without sending email or provisioning resources. + plans_before = system(:Calendar)[:plans].as_a.size + messages_before = system(:Mailer)[:templates].as_a.size + exec(:get_booking, 1).get["id"].should eq 1 + [3, 4, 5, 6, 7, 12, 13].each do |id| + expect_raises(Exception) { exec(:get_booking, id).get } + end + start_time = Time.utc.to_unix + exec(:list_bookings, start_time, start_time + 86400).get.as_a.map(&.["id"].as_i64).should eq [1_i64] + expect_raises(Exception) { exec(:list_bookings, start_time + 86400, start_time).get } + preview = exec(:preview_booking, 2).get + preview["booking_id"].should eq 2 + preview["confirmed"].should eq true + preview["planner_group_id"].should eq "group-aecb" + preview["tasks"].as_h.size.should eq 9 + preview["template_args"]["building_name"].should eq "Building Display" + preview["template_args"]["level_name"].should eq "Level Display" + exec(:workflow_status, 2).get["planner_complete"].should eq true + exec(:workflow_status, 99).get.as_h.should be_empty + system(:StaffAPI).as(VIPStaffMock).set_level_display_name("") + exec(:preview_booking, 1).get["template_args"]["level_name"].should eq "Level Internal" + system(:StaffAPI).as(VIPStaffMock).set_level_display_name("Level Display") + system(:Calendar)[:plans].as_a.size.should eq plans_before + system(:Mailer)[:templates].as_a.size.should eq messages_before + + fields = exec(:template_fields).get.as_a.first["fields"].as_a.map(&.["name"].as_s) + %w(building_name level_name vip_contact_number assistant_name assistant_contact_number protocol_officer_contact_number beverage_preference beverage_notes).each do |key| + fields.includes?(key).should be_true + end + %w(location google_maps_url parking_details valet_details).each do |key| + fields.includes?(key).should be_false + end + + # Stage methods only perform their own stage, retain eligibility checks, and + # cannot provision or report acceptance of an unconfirmed booking. + exec(:send_invitation, 1).get + system(:Mailer)[:templates].as_a.size.should eq messages_before + exec(:send_invitation, 1, true).get + system(:Mailer)[:templates].as_a.size.should eq messages_before + 1 + expect_raises(Exception) { exec(:send_confirmation, 1).get } + expect_raises(Exception) { exec(:provision_plan, 1).get } + system(:Calendar)[:plans].as_a.size.should eq plans_before + exec(:send_confirmation, 16).get + system(:Mailer)[:templates].as_a.last.should eq "vip_visitor.confirmed" + system(:Calendar)[:plans].as_a.size.should eq plans_before + messages_before = system(:Mailer)[:templates].as_a.size + exec(:send_confirmation, 16).get + system(:Mailer)[:templates].as_a.size.should eq messages_before + exec(:provision_plan, 16).get + system(:Calendar)[:plans].as_a.size.should eq plans_before + 1 + system(:Mailer)[:templates].as_a.size.should eq messages_before + + # Notifications are enabled by the template's presence. An absent template + # neither sends nor marks the stage complete, so adding it allows a retry. + mailer = system(:Mailer).as(VIPMailerMock) + mailer.disable_template("vip_visitor.arrived") + exec(:send_arrival_notification, 17).get.should eq false + system(:Mailer)[:templates].as_a.size.should eq messages_before + exec(:workflow_status, 17).get["arrived"]?.should_not eq true + mailer.enable_template("vip_visitor.arrived") + exec(:send_arrival_notification, 17).get + system(:Mailer)[:templates].as_a.last.should eq "vip_visitor.arrived" + system(:Mailer)[:recipients].as_a.last.should eq "host@example.com" + exec(:send_arrival_notification, 17).get + system(:Mailer)[:templates].as_a.size.should eq messages_before + 1 + exec(:send_departure_notification, 17).get + system(:Mailer)[:templates].as_a.last.should eq "vip_visitor.departed" + system(:Calendar)[:plans].as_a.size.should eq plans_before + 1 + + # A booking destination overrides the module default. Failed creation leaves + # it editable; only a successfully created plan pins its destination. + staff = system(:StaffAPI).as(VIPStaffMock) + staff.booking_extension_data(18, JSON.parse({planner_group_id: "group-booking"}.to_json).as_h) + exec(:preview_booking, 18).get["planner_group_id"].should eq "group-booking" + system(:Calendar).as(VIPCalendarMock).fail_next_plan + expect_raises(Exception) { exec(:provision_plan, 18).get } + exec(:workflow_status, 18).get["planner_group_id"]?.should be_nil + exec(:workflow_status, 18).get["plan_id"]?.should be_nil + staff.booking_extension_data(18, JSON.parse({planner_group_id: "group-changed"}.to_json).as_h) + exec(:provision_plan, 18).get + system(:Calendar)[:groups].as_a.last(2).should eq ["group-booking", "group-changed"] + exec(:workflow_status, 18).get["planner_group_id"].should eq "group-changed" + exec(:preview_booking, 18).get["planner_group_id"].should eq "group-changed" + + # Blank booking overrides fall back to the module; no destination fails + # clearly before a plan request and does not mark the workflow complete. + staff.booking_extension_data(19, JSON.parse({planner_group_id: " "}.to_json).as_h) + exec(:preview_booking, 19).get["planner_group_id"].should eq "group-aecb" + settings({building_id: "zone-aecb", planner_group_id: "", handler_emails: ["handler@example.com"]}) + requests_before = system(:Calendar)[:groups].as_a.size + expect_raises(Exception) { exec(:provision_plan, 19).get } + system(:Calendar)[:groups].as_a.size.should eq requests_before + exec(:workflow_status, 19).get["planner_complete"]?.should_not eq true + + # The executable submission uses the frontend's field names and merges only + # those fields, retaining organiser choices and the requested Planner group. + staff.booking_extension_data(20, JSON.parse({vip_confirmed: false, planner_group_id: "group-booking", gift: true}.to_json).as_h) + expect_raises(Exception) do + exec(:submit_confirmation, 20, "Dr", " ", "123", "Assistant", "456", "Officer", "789", "ABC", "Private", "standard").get + end + expect_raises(Exception) do + exec(:submit_confirmation, 20, "Dr", "Guest", "123", "Assistant", "456", "Officer", "789", "ABC", "Private", "invalid").get + end + exec(:get_booking, 20).get["extension_data"]["vip_confirmed"].should eq false + messages_before = system(:Mailer)[:templates].as_a.size + exec(:submit_confirmation, 20, "Dr", "Confirmed Guest", "123", "Assistant", "456", "Officer", "789", "ABC", "Private", " Custom ", "Green tea").get + submission = exec(:get_booking, 20).get["extension_data"] + submission["vip_confirmed"].should eq true + submission["vip_full_name"].should eq "Confirmed Guest" + submission["vip_contact_number"].should eq "123" + submission["assistant_name"].should eq "Assistant" + submission["assistant_contact_number"].should eq "456" + submission["protocol_officer_contact_number"].should eq "789" + submission["beverage_preference"].should eq "custom" + submission["beverage_notes"].should eq "Green tea" + submission["gift"].should eq true + submission["planner_group_id"].should eq "group-booking" + system(:StaffAPI)[:signal_changes].should eq false + system(:Mailer)[:templates].as_a.size.should eq messages_before + 1 + system(:Mailer)[:last_args]["vip_contact_number"].should eq "123" + system(:Calendar)[:tasks].as_a.map(&.as_s).any?(&.ends_with?("Welcome Beverage - custom: Green tea")).should be_true + exec(:workflow_status, 20).get["planner_complete"].should eq true + plans_before = system(:Calendar)[:plans].as_a.size + exec(:submit_confirmation, 20, "Dr", "Confirmed Guest", "123", "Assistant", "456", "Officer", "789", "ABC", "Private", "custom", "Green tea").get + system(:Calendar)[:plans].as_a.size.should eq plans_before + system(:Mailer)[:templates].as_a.size.should eq messages_before + 1 + + # Form notes are authoritative, including empty strings. A previous custom + # request must not reappear after the assistant selects standard or clears it. + {21_i64 => "standard", 22_i64 => "custom"}.each do |id, preference| + staff.booking_extension_data(id, JSON.parse({ + vip_confirmed: false, planner_group_id: "group-booking", + welcome_beverage: "custom", welcome_beverage_notes: "Old tea", welcome_beverage_custom: "Old coffee", + }.to_json).as_h) + exec(:submit_confirmation, id, "Dr", "Confirmed Guest", "123", "Assistant", "456", "Officer", "789", "ABC", "Private", preference, "").get + booking = exec(:get_booking, id).get + booking["extension_data"]["beverage_notes"].should eq "" + booking["extension_data"]["welcome_beverage_custom"].should eq "Old coffee" + plan_id = exec(:workflow_status, id).get["plan_id"].as_s + tasks = system(:Calendar)[:tasks].as_a.map(&.as_s).select(&.starts_with?("#{plan_id}:")) + tasks.size.should eq 1 + tasks.first.ends_with?("Welcome Beverage - #{preference}").should be_true + end end diff --git a/drivers/place/vip_visitor_planner.cr b/drivers/place/vip_visitor_planner.cr deleted file mode 100644 index 971fe54826..0000000000 --- a/drivers/place/vip_visitor_planner.cr +++ /dev/null @@ -1,122 +0,0 @@ -require "json" - -# Uses the Planner methods on Calendar_1 (Microsoft Graph calendar driver). -# The caller owns persistence and serializes work for each booking. -module Place::VIPVisitorPlanner - private def provision_plan(booking : JSON::Any, state : Hash(String, JSON::Any), &checkpoint : ->) - return if state["planner_complete"]?.try(&.as_bool?) == true - - group_id = setting(String, :planner_group_id).strip - raise "planner_group_id must identify an existing Microsoft 365 group" if group_id.empty? - tasks = vip_planner_tasks(booking) - assignments = setting?(Hash(String, Array(String)), :planner_task_assignments) || {} of String => Array(String) - - unless state["plan_id"]? - name = booking["extension_data"]?.try(&.["vip_full_name"]?).try(&.as_s?).presence || - booking["title"]?.try(&.as_s?).presence || "VIP Visit" - title = "#{name} - VIP Visit (#{booking["id"]})" - raise "Planner plan title exceeds 255 characters" if title.size > 255 - result = calendar.create_plan(group_id, title).get - state["plan_id"] = JSON::Any.new(vip_planner_id(result)) - yield - end - plan_id = state["plan_id"].as_s - - buckets = state["bucket_ids"]?.try(&.as_h) || {} of String => JSON::Any - state["bucket_ids"] = JSON::Any.new(buckets) - {"To Do", "In Progress", "Done"}.each do |name| - next if buckets[name]? - # Place each bucket after the preceding one, using the service's hint. - # https://learn.microsoft.com/en-us/graph/api/resources/planner-order-hint-format - order_hint = "#{state["bucket_order_hint"]?.try(&.as_s) || ""} !" - result = calendar.create_bucket(plan_id, name, order_hint).get - buckets[name] = JSON::Any.new(vip_planner_id(result)) - state["bucket_order_hint"] = result["orderHint"]? || JSON::Any.new(order_hint) - yield - end - - task_ids = state["task_ids"]?.try(&.as_h) || {} of String => JSON::Any - state["task_ids"] = JSON::Any.new(task_ids) - due_at = booking["booking_start"]?.try(&.as_i64?).try { |value| Time.unix(value).to_rfc3339 } - tasks.each do |key, title| - next if task_ids[key]? - result = calendar.create_task( - plan_id: plan_id, - title: title, - bucket_id: buckets["To Do"].as_s, - assigned_to_user_ids: assignments[key]?, - due_date_time: due_at, - percent_complete: 0, - ).get - task_ids[key] = JSON::Any.new(vip_planner_id(result)) - yield - end - state["planner_complete"] = JSON::Any.new(true) - yield - end - - private def vip_planner_id(result : JSON::Any) : String - id = result["id"]?.try(&.as_s?).presence - raise "Calendar returned no Planner resource ID" unless id - id - end - - private def vip_planner_tasks(booking : JSON::Any) : Hash(String, String) - data = booking["extension_data"]?.try(&.as_h?) || {} of String => JSON::Any - tasks = {} of String => String - if value = vip_planner_option(data, "meet_greet") - label = case value.downcase - when "internal" then "Internal" - when "airport", "external - airport", "external_airport" then "Airport" - else value - end - tasks["meet_greet"] = "Meet & Greet - #{label}" - end - { - "tour" => "Walkthrough/Guided Tour", - "gift" => "Giveaway Gift", - "photographer" => "Photographer", - "welcome_screen" => "Welcome screen", - "presentation" => "Presentation", - }.each do |key, title| - selected = key == "tour" ? (data[key]? || data["walkthrough"]?) : data[key]? - tasks[key] = title if selected.try(&.as_bool?) == true - end - beverage_key = data.has_key?("beverage_preference") ? "beverage_preference" : "welcome_beverage" - if value = vip_planner_option(data, beverage_key) - notes = data["beverage_notes"]?.try(&.as_s?).presence || - data["welcome_beverage_notes"]?.try(&.as_s?).presence || - data["welcome_beverage_custom"]?.try(&.as_s?).presence - tasks["welcome_beverage"] = "Welcome Beverage - #{value}#{notes ? ": #{notes}" : ""}" - end - if restaurant = data["restaurant_reservation"]?.try(&.as_h?) - name = restaurant["name"]?.try(&.as_s?).presence - timestamp = restaurant["time"]?.try(&.as_i64?) - raise "Restaurant reservation requires name and Unix time" unless name && timestamp - zone = Time::Location.load(setting?(String, :timezone) || "Asia/Dubai") - time = Time.unix(timestamp).in(zone).to_s("%Y-%m-%d %H:%M %z") - address = restaurant["address"]?.try(&.as_s?).presence - tasks["restaurant_reservation"] = "Restaurant Reservation - #{name}#{address ? ", #{address}" : ""} - #{time}" - end - if value = vip_planner_option(data, "driver") - label = case value.downcase - when "in_house", "in-house" then "In-house" - when "third_party", "third party" then "Third Party" - else value - end - tasks["driver"] = "Driver - #{label}" - end - tasks.each do |key, title| - # Calendar currently has no task-details API. Keep all requested details - # in the title and fail explicitly rather than silently dropping data. - raise "Planner task #{key} exceeds 255 characters" if title.size > 255 - end - tasks - end - - private def vip_planner_option(data : Hash(String, JSON::Any), key : String) : String? - value = data[key]?.try(&.as_s?).try(&.strip) - return nil if value.nil? || value.empty? || value.downcase == "none" - value - end -end diff --git a/drivers/place/vip_visitor_readme.md b/drivers/place/vip_visitor_readme.md index 1f9be70ac8..a674765f1e 100644 --- a/drivers/place/vip_visitor_readme.md +++ b/drivers/place/vip_visitor_readme.md @@ -1,236 +1,316 @@ # VIP visitor automation integration -This workflow is for standalone Staff API bookings with `booking_type: "vip-visitor"`. -Bookings with a top-level `parent_id` or an `extension_data.parent_id` are excluded. -This also excludes children of group bookings; create individual standalone VIP -bookings for this implementation. Multiple-visitor group support is not included. -Planner operations use the existing Calendar driver, which provides `create_plan`, -`create_bucket`, and `create_task`. A separate Planner service driver is not required. -Creating a Planner plan in a configured Microsoft 365 group does not create a new -Microsoft Teams team or channel. Provision the intended group/Team separately. - -The `exclude_booking_types` option described below belongs to a companion -VisitorMailer change. It is not included in this new-driver-only change; ensure -that support is present before running both mail workflows for VIP bookings. - -## Configuration - -Add `VIPVisitorAutomation`, `StaffAPI_1`, and `Calendar_1` to the building's system. -Configure Template Mailer as `Mailer_1` and its downstream SMTP mailer as +This workflow handles standalone Staff API bookings with `booking_type: "vip-visitor"`. +Bookings must include the configured building zone ID. Cancelled, deleted, rejected +and child bookings (a top-level or extension-data `parent_id`) are excluded. Create +individual standalone bookings for multiple VIP visitors. + +Compile `drivers/place/vip_visitor_automation.cr` as **VIP Visitor Automation** and +add a `VIPVisitorAutomation` module to the building's system. Add `StaffAPI_1`, +`Calendar_1`, Template Mailer as `Mailer_1`, and its downstream SMTP mailer as `Mailer_2`. Configure one workflow instance per building. -| Setting | Purpose | +Planner orchestration is part of `VIPVisitorAutomation` and calls the existing +Calendar driver's `create_plan`, `create_bucket` and `create_task` methods. There is +no separate `VIPVisitorPlanner` driver or module. An earlier +`vip_visitor_planner.cr` source helper could not compile independently; removing +that file does not remove any obsolete driver record already registered in +Backoffice. Remove such a record after checking that no system modules reference it. + +## Module settings + +Configure deployment-specific values on the VIPVisitorAutomation module. + +| Setting | Value and purpose | | --- | --- | -| `building_id` | Required building zone ID; bookings outside it are ignored | -| `planner_group_id` | Existing Microsoft 365 group that owns the plans | -| `confirmation_url` | HTTPS address of the compatible confirmation application | -| `domain_uri` | PlaceOS authority URL used as JWT audience | -| `jwt_private_key` | Signing key trusted by the PlaceOS backend | -| `confirmation_field` | Boolean extension-data submission marker; defaults to `vip_confirmed` | -| `handler_emails` | Recipients of the completed form email | -| `timezone` | Email time zone, default `Asia/Dubai` | -| `location`, `google_maps_url`, `parking_details`, `valet_details` | Invitation template details | -| `notify_arrival_departure` | Enable optional arrival/departure emails; default false | -| `notification_emails` | Arrival/departure recipients, e.g. office/building managers | -| `planner_task_assignments` | Task-key to Microsoft user-ID array; unspecified tasks remain unassigned | - -Configure Template Mailer templates `vip_visitor.invitation`, -`vip_visitor.confirmed`, and, when enabled, `vip_visitor.arrived` and -`vip_visitor.departed`. Arguments include extension-data fields, `booking_id`, -`booking_title`, `booking_user_name`, `booking_user_email`, `booking_booking_start`, -`booking_booking_end`, `event_date`, `event_time`, `event_end_time`, and configured location details. -The invitation also provides `confirmation_url`, `visitor_email`, and an inline -QR image referenced through `qr_code`. - -`submitted_details` contains the extension data as JSON. Template Mailer performs -literal placeholder replacement, so use a plain-text completed-form template for -untrusted form fields rather than inserting raw values into HTML. Restrict template -recipients to the VIP handlers; template-level `to`, `cc`, and `bcc` settings can -override or extend the recipients configured on this driver. - -Before acceptance, changes to the booking time, title, visitor email, or assistant name/email send a replacement invitation. Repeated unchanged events do not resend. - -The confirmed template receives the submitted extension-data fields. Include all -requested form fields in that template to produce the completed-form email. - -The confirmation endpoint must save `extension_data.vip_confirmed: true` (or the -configured field) with the submitted details. An ordinary booking edit without -that marker must not create a plan. - -Workflow progress is checkpointed in the driver setting `workflow_state` after -successful downstream operations using the framework’s asynchronous `define_setting` mechanism. Keep this setting across restarts. An operator -can retry a failed workflow with administrator-only `process_booking(booking_id)`. -There is a crash window between a successful external operation and its saved -checkpoint, so this is not a transactional exactly-once guarantee across services. - -Example settings (replace placeholders; the confirmation endpoint must be ready -before enabling live invitations): +| `building_id` | Required PlaceOS building **zone ID**, such as `zone-building`; not a system ID. Bookings outside this zone are ignored. | +| `planner_group_id` | Optional default Microsoft 365 group object ID. A booking's `extension_data.planner_group_id` takes precedence. At least one is required when creating a plan. | +| `confirmation_url` | HTTPS URL of the external form the assistant must complete; see the confirmation section below. | +| `domain_uri` | PlaceOS HTTPS authority URL; its hostname becomes the invitation JWT audience. | +| `jwt_private_key` | Signing key trusted by the deployment. Defaults to the key exposed by the framework; only override with the matching deployment key. | +| `handler_emails` | Array of completed-form email recipients. Required when sending the confirmation email. Template To/CC/BCC can override or extend recipients. | +| `timezone` | IANA timezone used in emails and restaurant reservation task titles, e.g. `Asia/Dubai` or `Europe/London`. Default: `Asia/Dubai`. | +| `planner_task_assignments` | Task keys mapped to arrays of Microsoft user object IDs; omitted tasks remain unassigned. See below. | +| `workflow_state` | Automatically maintained progress, including destination, plan, bucket and task IDs. Do not populate manually or clear to retry; clearing progress can repeat external operations. | + +Example: ```yaml -building_id: zone-aecb-building +building_id: zone-building planner_group_id: microsoft-365-group-object-id -timezone: Asia/Dubai +timezone: Europe/London domain_uri: https://placeos.example.com confirmation_url: https://placeos.example.com/enrolment/#/ -confirmation_field: vip_confirmed handler_emails: - vip-handlers@example.com -location: Rolex Tower -google_maps_url: https://maps.google.com/?q=Rolex+Tower+Dubai -parking_details: Use the visitor parking entrance. -valet_details: Contact reception on arrival. -notify_arrival_departure: false +planner_task_assignments: + meet_greet: + - microsoft-user-object-id ``` -Use the platform's configured signing key or set `jwt_private_key` securely; never -place a private key in a committed example configuration. The driver adds the JWT -as the fragment query parameter `uid` to the confirmation URL. +There is no configurable confirmation field: acceptance is the boolean +`extension_data.vip_confirmed: true`. The driver has no settings for location, +map links, parking or valet wording, arrival/departure enablement, or notification +recipient lists. Those presentation and notification choices belong to templates. -If the ordinary Visitor Mailer is also active in this building, set this on that -driver to prevent normal invitation and notification emails for VIP bookings: +## Planner destination and assignments -```yaml -exclude_booking_types: - - vip-visitor -``` +For a booking-specific destination, the internal booking request should persist: -The exclusion defaults to an empty list and covers booking guest events, booking -changes, previous-host notifications, and booking reminders. Calendar-event -visitors remain unaffected. +```json +{ + "extension_data": { + "planner_group_id": "microsoft-365-group-object-id" + } +} +``` -## Deployment checks +A nonblank booking value overrides the module default. After plan creation +succeeds, the resolved destination is saved as `workflow_state.planner_group_id` +alongside the plan ID. Once a plan exists, retries keep that destination even if +the booking or module setting changes. If creation fails before a plan ID is +returned, you can correct the booking or module group and retry. The assistant +submission method preserves this internal booking field and does not accept a +replacement destination. -- Implement and test the restricted confirmation endpoint and the form's explicit - acceptance marker; the existing generic booking PATCH route is insufficient. -- Configure the existing Microsoft 365 group, Calendar's Planner access, signing - key and authority domain; a new Teams team/channel is not created. -- Configure invitation and completed-form templates, QR image, location, map, - parking/valet information, and handler recipients. Check template overrides. -- Exclude VIP bookings from the ordinary Visitor Mailer when both drivers run. -- Verify invitation, submission email, selected tasks, retry after failure, and - duplicate-event suppression in staging with test recipients. -- Enable optional arrival/departure notifications only after confirming recipients. +The group must already exist. Each confirmed visit gets a new plan with **To Do**, +**In Progress**, and **Done** buckets. Selected tasks start in To Do. This workflow +does not create a Team, channel, Microsoft 365 group, or group membership. -These are deployment instructions; development and tests do not send live emails -or create live Microsoft Planner resources. +`planner_task_assignments` chooses who receives each type of task. For example: -## Staff API events +```yaml +planner_task_assignments: + meet_greet: + - reception-user-object-id + - protocol-officer-user-object-id + welcome_beverage: + - catering-user-object-id + driver: + - transport-user-object-id +``` -The locally inspected Staff API publishes `staff/booking/changed` for booking -creation and updates. The payload includes `id`, `booking_type`, `zones`, -`booking_start`, `booking_end`, `user_email`, `booked_by_email`, and `extension_data`. +These values are Microsoft user object IDs, not email addresses, PlaceOS user IDs +or AD group IDs. The array can contain more than one user. It is passed to +Calendar's `assigned_to_user_ids` when that task is created; it does not create the +task unless the booking selected the corresponding option. -| Action | Meaning | +| Task key | Task | | --- | --- | -| `create` | New booking | -| `metadata_changed` | Ordinary booking PATCH without a time/resource change | -| `changed` | Booking PATCH that resets booking state | -| `extdata_changed` | PATCH `/bookings/:id/ext_data?signal_changes=true` | -| `checked_in` | Check-in **or check-out**; inspect `checked_in` | - -The extension-data-only endpoint defaults `signal_changes` to false. Use true -when the form submission needs to trigger automation. - -`staff/guest/attending` is emitted when an attendee is added, including initial -booking creation. It is not a confirmation-form-submitted event, and does not -contain `booking_type` or extension data. The sequence diagram's claim that a -metadata PATCH produces that event does not match the inspected implementation. - -`staff/guest/checkin` carries `booking_id` and `checkin: true/false`. Arrival and -departure must remain separate from acceptance of an invitation. - -## External confirmation app integration gap - -The AECB UI implementation inspected in `aecb-catering-host-backport` has the -enrolment route `/enrolment/#/?uid=`. Its token parser expects `u.r` and selects -VIP mode using `u.b` or a top-level `booking_id`. Its confirmation form PATCHes the -booking extension data, but currently writes no explicit acceptance marker. -The separate check-in button invokes the booking check-in endpoint. - -Before connecting that external form, implement a scoped backend confirmation -endpoint and update the form to use it. The endpoint must verify the token's -signature, expiry, audience, tenant and exact booking binding; permit only the -confirmation fields; and persist an explicit submission marker with the form -data before publishing the booking-changed event. Treat that marker as acceptance, -not the presence of optional phone/name/car fields or an arbitrary booking edit. - -The existing guest JWT scopes (`guest`, `metadata`) cannot read or PATCH the -general `/api/staff/v1/bookings/:id` endpoints in the inspected backend. Those -endpoints require public API scope and writes additionally require the booking -owner or a zone manager. Adding a booking claim to a JWT does not itself grant -access. Do not issue a broadly privileged staff token to the external assistant. - -The guest profile PATCH endpoint updates the guest record, not booking metadata. -Guest catering endpoints support a limited beverage selection, not arbitrary VIP -form submission. Neither is a substitute for the required confirmation endpoint. - -## Field compatibility - -The implementation document and the existing AECB UI use some different keys: - -| Document key/value | Existing AECB UI key/value | +| `meet_greet` | Internal or airport meet and greet | +| `tour` | Walkthrough/guided tour | +| `welcome_beverage` | Selected beverage, including custom notes | +| `gift` | Giveaway gift | +| `photographer` | Photographer | +| `restaurant_reservation` | Restaurant name, address and reservation time | +| `driver` | In-house or third-party driver | +| `welcome_screen` | Welcome screen | +| `presentation` | Presentation | + +Omit a key, or leave the entire setting as `{}`, to leave those tasks unassigned. +Changing assignments later does not reassign already-created tasks. Tasks are +created from the confirmed booking's details; later booking edits do not rewrite a +completed plan. No template plan is cloned. Configure Calendar with the necessary +Planner access and tenant consent for the intended groups and users. + +## Templates and zone names + +Create these Template Mailer triggers: + +| Trigger | Default recipient and behaviour | | --- | --- | -| `tour` | `walkthrough` | -| `vip_mobile_number` | `vip_contact_number` | -| `vip_assistant_name` (submitted) | `assistant_name` | -| `vip_assistant_mobile_number` | `assistant_contact_number` | -| `protocol_officer_mobile_number` | `protocol_officer_contact_number` | -| `welcome_beverage` (submitted) | `beverage_preference` | -| Beverage notes | `beverage_notes` (submitted), `welcome_beverage_custom` (booked) | -| `In-house`, `Third Party` | `in_house`, `third_party` | - -The UI uses lower-case `none`, `standard`, `custom` beverage values. Prefer the -submitted beverage choice over the original booking choice when both are present. -Keep all submitted fields available to the handler email template. - -## Scope of source documents - -Both local PDFs were read, and the journey diagram was rendered and inspected. -The wider journey diagram includes reminders, WhatsApp messages, catering, -access control, welcome screens, and thank-you messages. Those are separate -automations from the core invitation, submission email, and Planner workflow. -The diagram's phrase “Space on Teams” does not add a Teams-creation operation to -the Calendar driver's Planner methods. - -## Planner permissions - -The Calendar connection needs Planner write permissions. Microsoft documents -`Tasks.ReadWrite` for delegated work/school accounts and `Tasks.ReadWrite.All` -for application access for [creating plans](https://learn.microsoft.com/en-us/graph/api/planner-post-plans?view=graph-rest-1.0). -Confirm tenant consent and access to the configured group before deployment. -Tasks are created from the confirmed booking snapshot; later edits do not rewrite -an already completed Planner workflow. No existing template plan is cloned: -the three buckets and conditional tasks are defined by this driver. - -## Minimal template bodies - -For `vip_visitor.invitation`, a plain-text starting point is: +| `vip_visitor.invitation` | The booking's `extension_data.vip_assistant_email`; includes the form link and QR image. | +| `vip_visitor.confirmed` | `handler_emails`; includes submitted form fields. | +| `vip_visitor.arrived` | Booking host (`user_email`); skipped when this template is absent. | +| `vip_visitor.departed` | Booking host (`user_email`); skipped when this template is absent. | + +Use template **To** to replace the default recipient and **CC/BCC** to add recipients. +For arrival/departure emails, the presence of the corresponding template enables +sending. No notification settings need to be switched on. An absent template is +skipped without marking that notification as sent; adding it later allows a +subsequent event or manual invocation to send it. Notifications are sent once per +booking and action after a successful send. + +`building_name` is the configured building zone's `display_name`, falling back to +its `name`. `level_name` comes from the booking zone tagged `level`, with the same +fallback; it is empty when the booking contains no level zone. Template selection +uses Template Mailer's configured organisation and building zones; the notification +presence check uses those same zones. + +Concierge users put map links and parking/valet instructions directly into the +email template. For example: ```text VIP visit: %{booking_title} %{event_date}, %{event_time} – %{event_end_time} -Location: %{location} -Google Maps: %{google_maps_url} -Parking: %{parking_details} -Valet: %{valet_details} +Location: %{building_name}, %{level_name} +Map: [insert the desired map link here] +Parking: [write the current visitor parking instructions here] +Valet: [write the current valet instructions here] Please complete the visit details: %{confirmation_url} ``` -In the HTML invitation, reference the attached QR image with +The invitation includes an inline QR image; an HTML template can use `Visitor QR code`. -For `vip_visitor.confirmed`, include `%{submitted_details}` in the plain-text body -to return every submitted field to the handlers. These are template configuration -examples; the driver does not create or send tenant templates during installation. -## Validation +The confirmed template receives the actual form field names listed below, plus +compatibility aliases from the original scope document. `%{submitted_details}` +contains the booking extension data as JSON. Template Mailer replaces placeholders +literally, so use a plain-text completed-form body for submitted free text. +`template_fields` supplies available field definitions to Template Mailer; it does +not send an email or process a booking. -The VIP automation driver/spec compiled and passed the driver harness, covering -conditional tasks, submitted field aliases, invitation refresh and duplicate -suppression, explicit acceptance, partial-failure resume, and lifecycle events. -The focused VisitorMailer exclusion regression passed with the complete spec -restored afterwards. Formatting and diff checks passed. +## Confirmation URL and form submission + +`confirmation_url` is the address of the web form the external assistant opens. +It is not the submission API URL. For example, configuring +`https://placeos.example.com/enrolment/#/` produces an invitation link shaped like: + +```text +https://placeos.example.com/enrolment/#/?uid= +``` + +The driver adds `uid` to the URL fragment's query parameters. The token identifies +the visitor and exact booking (`u.b`), includes the permitted resource IDs (`u.r`), +and expires at the booking end time. The app reads the token to identify the visit. +Setting this URL does not deploy the form or implement its backend endpoint. + +For testing from Backoffice, execute **`submit_confirmation`** with the numeric +booking ID and the same fields the AECB enrolment form submits: + +```json +{ + "booking_id": 12345, + "vip_title": "Dr", + "vip_full_name": "Example Visitor", + "vip_contact_number": "+971500000001", + "assistant_name": "Example Assistant", + "assistant_contact_number": "+971500000002", + "protocol_officer_name": "Example Officer", + "protocol_officer_contact_number": "+971500000003", + "vehicle_plate_number": "12345", + "vehicle_plate_type": "Private", + "beverage_preference": "custom", + "beverage_notes": "Tea, no sugar" +} +``` + +Replace `12345` with a real standalone VIP booking ID. Provide the named strings; +unused optional form details can be empty strings. `vip_full_name` must not be +blank. Beverage preference accepts `none`, `standard`, or `custom` and is normalised +to lower case. `beverage_notes` defaults to an empty string and is cleared unless +the preference is `custom`. Submitted custom notes, including an empty string, +replace the organiser's original beverage notes. + +This method merges just these fields and the fixed `vip_confirmed: true` marker +into the booking via Staff API. It preserves other options, assistant email, and +Planner destination. It saves with `signal_changes: false`, then directly runs the +workflow: completed-form email followed by Planner provisioning. **This performs +real booking updates, emails and Planner operations.** It is an administrator-only +method, not a dry run or an external guest endpoint. Use `preview_booking` for +inspection without those effects. + +The UI inspected on `origin/custom/ACB012M` currently saves these form fields but +sets no acceptance marker. Its separate check-in action does not constitute form +acceptance. Production form integration must save the fixed marker when submitting. + +### External integration still required + +Before connecting the external form, implement a scoped backend endpoint for +reading/submitting the permitted booking details and update the form to use it. +The endpoint must verify the invitation token's signature, expiry, audience, +tenant and booking binding. It must permit only the confirmation fields and save +`vip_confirmed: true` with them, then trigger processing through a booking-change +signal or a trusted server-side workflow invocation. + +The current `guest`/`metadata` JWT cannot read or PATCH the general +`/api/staff/v1/bookings/:id` routes in the inspected backend. Those routes require +public API scope and writes also require ownership or zone-manager permission. +A booking claim alone does not grant this access. Do not solve this by granting +the external assistant a broadly privileged staff token. The Backoffice submission +method lets an administrator test the completed-form workflow while this external +integration remains outstanding. + +## Executable methods and a Backoffice test sequence + +All methods below require administrator access. Individual stage methods share +validation and saved progress with automatic processing. + +| Method | Behaviour | +| --- | --- | +| `list_bookings(period_start, period_end)` | Lists eligible VIP bookings in the configured building over an explicit Unix-seconds time window. Use a result's numeric `id`. | +| `get_booking(booking_id)` | Fetches the booking and rejects an ineligible booking. | +| `workflow_status(booking_id)` | Returns saved progress; an unprocessed booking has an empty object. No processing occurs. | +| `preview_booking(booking_id)` | Returns confirmation status, resolved Planner group, proposed task titles, template arguments and current progress. Creates no token, email, booking update or Planner resource. | +| `send_invitation(booking_id, force = false)` | Sends only the invitation for an unconfirmed booking. Skips an unchanged invitation unless `force` is true. | +| `submit_confirmation(...)` | Persists the form fields and acceptance marker, then runs confirmation email and Planner stages. See the complete example above. | +| `send_confirmation(booking_id)` | Sends only the completed-form email for an already-confirmed booking; skips an already-sent email. | +| `provision_plan(booking_id)` | Creates/resumes only the plan, buckets and selected tasks for an already-confirmed booking. Returns the plan ID. | +| `send_arrival_notification(booking_id)` | Sends only the arrival email if a template exists and it has not already been sent. Does not check the visitor in. | +| `send_departure_notification(booking_id)` | Sends only the departure email if a template exists and it has not already been sent. Does not check the visitor out. | +| `process_booking(booking_id, action = "changed")` | Runs applicable stages from the persisted booking and resumes failures. `arrived`/`departed` also attempts the corresponding notification; an action alone does not change booking state. | + +A practical test is: list bookings, inspect one with `get_booking` and +`preview_booking`, send its invitation, then execute `submit_confirmation` and +inspect `workflow_status`. Use test recipients and an intended test Planner group. +To test confirmation email and Planner provisioning separately, start with an +already-confirmed booking that has not been processed and invoke each stage method. + +Repeated unchanged events skip completed operations. Before acceptance, changing +the visit time, title, visitor email or assistant name/email sends a replacement +invitation. `workflow_state` is checkpointed through the framework's asynchronous +`define_setting` mechanism. There is a crash window between a successful external +operation and its saved checkpoint; this is not a transactional exactly-once +promise across services. Retry with `process_booking` or the failed stage rather +than deleting the saved state. + +## Automatic events + +On load, the module subscribes to `staff/booking/changed`, +`staff/guest/attending`, and `staff/guest/checkin`. It fetches the booking, checks +eligibility, and determines acceptance from `vip_confirmed`. It does not perform a +startup scan or scheduled retry of missed events. + +| Event/action | Meaning | +| --- | --- | +| Booking `create` | New booking; send the invitation unless already confirmed. | +| Booking `metadata_changed` or `changed` | Fetch current details and run applicable stages. | +| Booking `extdata_changed` | Extension-data PATCH with `signal_changes=true`. | +| Booking `checked_in` | `checked_in: true` means arrival; false means departure. | +| Guest `attending` | An attendee was added, including during creation; this alone is neither acceptance nor arrival. | +| Guest `checkin` | `checkin: true/false` means arrival/departure. | + +For a form endpoint that writes extension data directly, request +`signal_changes=true` so the update triggers the automation. The driver submission +method deliberately uses false because it invokes processing itself. + +## Field compatibility and deployment + +The AECB form uses `vip_contact_number`, `assistant_name`, +`assistant_contact_number`, `protocol_officer_contact_number`, +`beverage_preference` and `beverage_notes`. For existing templates, the driver also +provides the original document aliases `vip_mobile_number`, `vip_assistant_name`, +`vip_assistant_mobile_number`, `protocol_officer_mobile_number`, +`welcome_beverage` and `welcome_beverage_notes`, preferring submitted values. +Planner selection accepts `tour` or the booking form's `walkthrough`, and `driver` +values `In-house`/`Third Party` or `in_house`/`third_party`. + +When ordinary Visitor Mailer also handles the building, its companion +`exclude_booking_types` support must be installed and configured with +`["vip-visitor"]` to avoid duplicate ordinary visitor emails. That companion change +is not part of this VIP driver change. + +The wider journey's reminders, WhatsApp messages, catering, access control, +welcome screens and thank-you messages remain separate automations. Validate the +external form endpoint, invitation, submitted-details email, selected tasks, +retries and template-controlled arrival/departure emails before deployment. +The harness uses mocked services and does not validate live Microsoft access or +external form authentication. + +## Validation -The complete existing VisitorMailer suite did not pass in this environment: -separate runs failed in existing system-lookup retry and debounce timing -assertions before reaching the new exclusion checks. No production mail or -Microsoft Graph resources were used in these tests. +The driver and expanded spec compile and pass the PlaceOS harness: **1 tested, +0 failures, 0 timeouts**. Coverage includes independent executable stages, +read-only inspection, form persistence and validation, template-controlled +notifications, zone names, Planner destination overrides, retries, duplicate +suppression, and cleared beverage notes. Formatting and diff checks also pass.