jsfe 1.104.0 → 1.105.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -543,6 +543,13 @@ const engine = new WorkflowEngine(logger, aiCallback, flows, tools,
543
543
  elsewhere, or the host's `cargo.verb`), and `yesNoKeys(lang, cargo, yes, no)` ("Press 1 or say YES, or press 2 or say
544
544
  NO." on a call): every yes/no question names 1 for YES and 2 for NO on a call. A FLOW call's parameters interpolate
545
545
  values, not expressions, so build such a question in a SET step and pass the variable.
546
+ - Schedules and appointment times (`{timezone, hours: {mon: [{open, close}]}}`, the User Admin hours editor's shape):
547
+ `scheduleOpenNow(schedule, now)` (no hours = always open), `hoursPhrase(schedule, lang)` ("every day from 9 AM to 5 PM,
548
+ Pacific time"), `zipCovered(zips, zip)` ('913xx', '91301-91311', '91325'), `readWhen(text, {now, timezone})` (what a
549
+ customer said about when, in English or Spanish, as `{dates, from, to, at, later, any}`, or null), `openSlots({hours,
550
+ calendars, service, busy, preference, now, zip, calendar, count})` (up to `count` open times, earliest first, with
551
+ `label` / `label_es`; no business hours = nothing to book), `slotToWords(slot, lang, today)`, `todayIn(timezone)` and
552
+ `minutesUntil(time)`.
546
553
  - Checks: `validateDigits(input, min, max)` (digits only, length in range), `validatePhone(phone, acceptInternational)`
547
554
  (10 digits, or 11 with a leading 1; with `acceptInternational`, any 11 to 15), `validateEmail` (`x@y.z`, no spaces),
548
555
  `validateCardNumber` (12 to 19 digits passing Luhn), `validateExpiration(MM, YY)` (a real month, not expired, at most
@@ -973,6 +980,8 @@ See the [retry/yield/recovery contract](docs/copilot-reference.md#retry-yield-an
973
980
 
974
981
  > Transfer departments (`transfer-to-line`): the host stamps `cargo.transferLines` and consumes `cargo.transferTo`, see [docs/transfer-lines.md](docs/transfer-lines.md).
975
982
 
983
+ > Scheduling (`sched-*` workers): the host stamps `cargo.scheduling` and answers one tool, `iag:calendar` (busy, find, book, move, cancel); the host's Save attaches the fixed part of each tenant-authored booking form with `attachScheduling(form, {service, op})` and installs `schedulingChangeForms()`; the shapes are in the header of [src/forms/scheduling-flows.js](src/forms/scheduling-flows.js).
984
+
976
985
  A flow can take actions in the outside world through `CALL-TOOL` — charge a card, send an SMS,
977
986
  create a ticket. For ordinary `CALL-TOOL` flows, **the session returned by `updateActivity` records
978
987
  which steps already ran**; the host owns its persistence. Native performers can additionally use an
@@ -1 +1 @@
1
- {"version":3,"file":"address-flows.d.ts","sourceRoot":"","sources":["../../src/forms/address-flows.js"],"names":[],"mappings":"AA+EA,0BAA0H"}
1
+ {"version":3,"file":"address-flows.d.ts","sourceRoot":"","sources":["../../src/forms/address-flows.js"],"names":[],"mappings":"AAgFA,0BAA0H"}
@@ -1,6 +1,6 @@
1
1
  /** Shared geocoded mailing-address collector over host-provided geocode tools. */
2
2
  import { defineForm, defineWorker } from './contracts.js';
3
- import { addressDraft, zipLocation, cityChoices, streetLocation, resolvedAddress, listedPlace, addressLine, addressVerdict, streetCheck, checkDeclined, unitQuestion, unitPrecheck, unitResult, unitsGiven, streetAccepted } from '../helpers/address.js';
3
+ import { addressDraft, zipLocation, cityChoices, streetLocation, resolvedAddress, listedPlace, addressLine, addressVerdict, streetCheck, checkDeclined, unitQuestion, unitPrecheck, unitResult, unitsGiven, streetAccepted, streetUnit } from '../helpers/address.js';
4
4
  const S = (id, variable, value) => ({ id, type: 'SET', variable, value });
5
5
  const F = (id, value, parameters = {}, callType = 'call') => ({ id, type: 'FLOW', value, parameters, callType });
6
6
  const W = (id, condition, step) => ({ id, type: 'CASE', branches: { ['condition: ' + condition]: step, default: S(id + '_skip', 'noop', 'true') } });
@@ -20,7 +20,7 @@ const address = defineForm({ id: 'collect-geocoded-address', name: 'CollectGeoco
20
20
  { name: 'city', argument_description: 'city name alone', label: 'city', label_es: 'ciudad', names: ['city', 'ciudad'], profile: { kind: 'choice', choices: [], accept_other: true, other_needs_letter: true }, choices_from: 'city_choices', validator: 'address-city-validate', when: { 'form.data.city_known': true }, required_when: { 'form.data.city_ask': 'yes' }, depends_on: ['zip'], reset_on: ['zip'], prepare: 'address-city-prompt', question_from: 'city_question', question: 'Which city is it?', question_es: '¿Qué ciudad es?', form_client: { control: 'combobox', autofill: 'address-level2' } },
21
21
  { name: 'city_state', argument_description: 'city and state', label: 'city and state', label_es: 'ciudad y estado', names: ['city', 'ciudad'], profile: { kind: 'text' }, when: { 'form.data.need_city': true }, depends_on: ['zip'], question_from: 'city_state_question', question: 'What city and state is that in?', question_es: '¿En qué ciudad y estado está?' },
22
22
  { name: 'street', argument_description: 'street number and street name, without the apartment', label: 'street address', label_es: 'dirección', names: ['street', 'calle'], profile: { kind: 'pattern', regex: streetPattern, spoken_digits: 'house_number', accept_other: true }, depends_on: ['zip'], validator: 'address-street-validate', after: 'address-street-accepted', prepare: 'address-street-prompt', question_from: 'street_question', question: 'What is the street address?', question_es: '¿Cuál es la dirección?', form_client: { control: 'place', types: 'address', regions: ['us'], fills: { zip: 'postal_code', city: 'locality' }, autofill: 'address-line1' } },
23
- { name: 'unit', declinable: true, validator: 'address-unit-validate', argument_description: 'apartment or unit number alone, such as 4 or 12B', depends_on: ['street'], reset_on: ['street'], label: 'apartment or unit', label_es: 'apartamento o unidad', names: ['apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'], profile: { kind: 'pattern', regex: '(?:\\bapartment|\\bapartamento|\\bdepartamento|\\bapt\\.?|\\bunit|\\bunidad|#)\\s*([\\w-]+)', group: 1, spoken_digits: true, accept_other: true }, question_from: 'unit_question', question: 'Is there an apartment or unit number? {{channelVerb(\'en\', cargo, true)}} the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? {{channelVerb(\'es\', cargo, true)}} el número, o NINGUNO.', form_client: { autofill: 'address-line2' } }],
23
+ { name: 'unit', declinable: true, silent: true, validator: 'address-unit-validate', argument_description: 'apartment or unit number alone, such as 4 or 12B', reset_on: ['street'], label: 'apartment or unit', label_es: 'apartamento o unidad', names: ['apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'], profile: { kind: 'pattern', regex: '(?:\\bapartment|\\bapartamento|\\bdepartamento|\\bapt\\.?|\\bunit|\\bunidad|#)\\s*([\\w-]+)', group: 1, spoken_digits: true, accept_other: true }, question_from: 'unit_question', question: 'Is there an apartment or unit number? {{channelVerb(\'en\', cargo, true)}} the number, or NONE.', question_es: '¿Hay un número de apartamento o unidad? {{channelVerb(\'es\', cargo, true)}} el número, o NINGUNO.', form_client: { autofill: 'address-line2' } }],
24
24
  before_confirm: [S('address_resolved', 'address_result', E(resolvedAddress, 'cargo.forms[form_instance].values', 'cargo.forms[form_instance].data'))],
25
25
  confirm: { named_fields: true, reply_context: 'This is a mailing address read back for confirmation. A reply may correct one part or several at once: the street number, street name or street type, the apartment or unit, the city, or the ZIP code.', no_keys: ['2', 'not right', 'not correct', 'incorrect', 'wrong', 'no es correcto', 'no es correcta', 'incorrecta'], question: "Your {{address_label}} is {{address_result.line}}. Is that correct? {{yesNoKeys('en', cargo)}}", question_es: "Su {{address_label_es}} es {{address_result.line}}. ¿Es correcta? {{yesNoKeys('es', cargo)}}" },
26
26
  after: [S('address_result_store', 'noop', '(cargo.forms[form_instance].values.resolved = address_result, cargo.address = address_result, cargo.addressDraft = null, true)')], declined: [S('address_retry_noop', 'noop', 'true')] });
@@ -37,12 +37,13 @@ const street = C('address-street-validate', 'Validate a proposed street against
37
37
  W('address_street_located', '!held', S('address_street_projection', 'location', E(streetLocation, 'result', 'value', 'values.zip'))),
38
38
  W('address_street_derive', '!held', S('address_street_result', 'noop', "(cargo.forms[form].data.street=location, location.city&&cargo.forms[form].accepted&&cargo.forms[form].accepted.city&&cargo.forms[form].accepted.city.origin==='derived'&&cargo.forms[form].values.city!==location.city?(cargo.forms[form].values.city=location.city):null, true)")),
39
39
  // The whole address, checked once by Google Address Validation (owner 2026-12-05). Its failure leaves the form as before.
40
- S('address_street_line', 'line', E(addressLine, 'value', "''", 'Object.assign({},cargo.forms[form].values,values)', 'cargo.forms[form].data')),
40
+ S('address_street_unit', 'unit', E(streetUnit, 'cargo.forms[form]', 'values', 'reading')),
41
+ S('address_street_line', 'line', E(addressLine, 'value', 'unit', 'Object.assign({},cargo.forms[form].values,values)', 'cargo.forms[form].data')),
41
42
  W('address_street_check', '!held', { id: 'address_street_validate', type: 'CALL-TOOL', tool: 'validate-address', variable: 'checked', args: { address: '{{line}}', previous_response_id: '' }, onFail: S('address_street_check_failed', 'checked', 'null') }),
42
43
  S('address_street_verdict', 'verdict', E(addressVerdict, 'checked', 'value')),
43
- S('address_street_checked', 'noop', '(cargo.inputCheck=' + E(streetCheck, 'cargo.forms[form]', 'values', 'verdict', 'value', 'reading', "({en:yesNoKeys('en',cargo),es:yesNoKeys('es',cargo)})") + ', true)'),
44
+ S('address_street_checked', 'noop', '(cargo.inputCheck=' + E(streetCheck, 'cargo.forms[form]', 'values', 'verdict', 'value', 'reading', "({en:yesNoKeys('en',cargo),es:yesNoKeys('es',cargo)})", 'unit') + ', true)'),
44
45
  S('address_street_unit_question', 'noop', E(unitQuestion, 'cargo.forms[form].data', BUILDING))
45
- ], { parameters: [P('form'), P('value'), P('values', 'object'), P('reading', 'object')], variables: V({ components: '', result: null, location: null, held: false, line: '', checked: null, verdict: null }), contract: { tools: ['geocode-street', 'validate-address'], result: { path: 'cargo.inputCheck', type: 'object' } } });
46
+ ], { parameters: [P('form'), P('value'), P('values', 'object'), P('reading', 'object')], variables: V({ components: '', result: null, location: null, held: false, unit: '', line: '', checked: null, verdict: null }), contract: { tools: ['geocode-street', 'validate-address'], result: { path: 'cargo.inputCheck', type: 'object' } } });
46
47
  // A ZIP code with several place names: the city is one of them (accents, case and edge punctuation folded), never other text.
47
48
  const city = C('address-city-validate', 'Match a city to the ZIP code\'s listed place names; any city when the ZIP code lists none.', [
48
49
  S('address_city_check', 'noop', "(function(choices,listed){cargo.inputCheck=!choices.length?{ok:true,value:String(value)}:listed?{ok:true,value:listed}:{ok:false,quiet:true};return true;})(cargo.forms[form].data.city_choices || []," + E(listedPlace, 'value', 'cargo.forms[form].data.city_choices') + ")")
@@ -52,7 +53,7 @@ const unit = C('address-unit-validate', 'Refuse a unit answer that is not a unit
52
53
  S('address_unit_pre', 'pre', E(unitPrecheck, 'cargo.forms[form].data', 'value')),
53
54
  S('address_unit_line', 'line', "pre.check ? " + E(addressLine, 'cargo.forms[form].data.check_street', 'pre.unit', 'Object.assign({},cargo.forms[form].values,values)', 'cargo.forms[form].data') + " : ''"),
54
55
  S('address_unit_rid', 'rid', "String(cargo.forms[form].data.check_rid || '')"),
55
- W('address_unit_check', 'pre.check === true', { id: 'address_unit_validate', type: 'CALL-TOOL', tool: 'validate-address', variable: 'checked', args: { address: '{{line}}', previous_response_id: '{{rid}}' }, onFail: S('address_unit_check_failed', 'checked', 'null') }),
56
+ W('address_unit_check', 'pre.check === true && !pre.known', { id: 'address_unit_validate', type: 'CALL-TOOL', tool: 'validate-address', variable: 'checked', args: { address: '{{line}}', previous_response_id: '{{rid}}' }, onFail: S('address_unit_check_failed', 'checked', 'null') }),
56
57
  S('address_unit_result', 'noop', '(cargo.inputCheck=' + E(unitResult, 'cargo.forms[form].data', 'pre', 'checked') + ', true)')
57
58
  ], { parameters: [P('form'), P('value'), P('values', 'object')], variables: V({ pre: null, line: '', rid: '', checked: null }), contract: { tools: ['validate-address'], result: { path: 'cargo.inputCheck', type: 'object' } } });
58
59
  const formCheck = C('address-form-validate', 'The whole address: a card that left the unit blank on a building with units is asked it once.', [
@@ -65,7 +66,7 @@ const checkNo = C('address-check-declined', 'NO to Google\'s version of the addr
65
66
  S('address_check_declined', 'noop', E(checkDeclined, 'cargo', 'form', 'acceptFormReadings', 'resetFormInputs'))
66
67
  ], { parameters: [P('form'), P('input'), P('value'), P('reading', 'object')] });
67
68
  const zipPrompt = C('address-zip-prompt', 'Render the ZIP question from the owned address instance, naming the calling form\'s label.', [S('address_zip_prompt', 'noop', "(cargo.forms[form].data.zip_question=(cargo.forms[form].data.retry ? \"Let's try again. \" : '')+'What is the 5-digit zip code of your '+(cargo.forms[form].data.label||'new address')+'?',cargo.forms[form].data.zip_question_es=(cargo.forms[form].data.retry?'Intentémoslo otra vez. ':'')+'¿Cuál es el código postal de 5 dígitos de su '+(cargo.forms[form].data.label_es||'nueva dirección')+'?',true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
68
- const streetPrompt = C('address-street-prompt', 'Include the ZIP-derived location when asking for the street.', [S('address_street_prompt', 'noop', "(cargo.forms[form].data.street_question=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'Got it. ':cargo.forms[form].data.location?'Got it, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'What is the street of your '+cargo.forms[form].data.label+'?':'What is the street address?'),cargo.forms[form].data.street_question_es=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'Entendido. ':cargo.forms[form].data.location?'Entendido, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'¿Cuál es la calle de su '+cargo.forms[form].data.label_es+'?':'¿Cuál es la dirección?'),true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
69
+ const streetPrompt = C('address-street-prompt', 'Include the ZIP-derived location when asking for the street; no acknowledgement when no city is named yet.', [S('address_street_prompt', 'noop', "(cargo.forms[form].data.street_question=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'':cargo.forms[form].data.location?'Got it, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'What is the street of your '+cargo.forms[form].data.label+'?':'What is the street address?'),cargo.forms[form].data.street_question_es=(cargo.forms[form].data.city_choice&&!cargo.forms[form].values.city?'':cargo.forms[form].data.location?'Entendido, '+(cargo.forms[form].values.city?cargo.forms[form].values.city+', '+cargo.forms[form].data.location.state:cargo.forms[form].data.location.line)+'. ':'')+(cargo.forms[form].data.labelled?'¿Cuál es la calle de su '+cargo.forms[form].data.label_es+'?':'¿Cuál es la dirección?'),true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
69
70
  const cityPrompt = C('address-city-prompt', 'Ask which of the ZIP code\'s place names the address carries.', [S('address_city_prompt', 'noop', "(function(data,voice){var names=(data.location&&data.location.cities)||[],n=names.length,list=function(and){return names.slice(0,-1).join(', ')+' '+and+' '+names[n-1];};if(n<2){data.city_question=data.labelled?'What city is your '+data.label+' in?':'What city is it?';data.city_question_es=data.labelled?'¿En qué ciudad está su '+data.label_es+'?':'¿Qué ciudad es?';return true;}data.city_question=(data.labelled?'Which city is your '+data.label+' in: ':'Which city is it: ')+list('or')+'? '+(voice?names.map(function(c,i){return (i?'':'Press ')+(i+1)+' for '+c;}).join(', ')+'.':'Type the city or its number, 1 to '+n+'.');data.city_question_es=(data.labelled?'¿En qué ciudad está su '+data.label_es+': ':'¿Qué ciudad es: ')+list('o')+'? '+(voice?names.map(function(c,i){return (i?'':'Presione ')+(i+1)+' para '+c;}).join(', ')+'.':'Escriba la ciudad o su número, del 1 al '+n+'.');return true;})(cargo.forms[form].data,cargo.voice===true)")], { parameters: [P('form')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
70
71
  // NO at the read-back asks which part is wrong and re-asks only that part; ALL starts over.
71
72
  const PARTS = [{ key: 'zip', label: 'ZIP code', label_es: 'Código postal', phrases: ['1', 'zip', 'zip code', 'postal code', 'código postal', 'codigo postal'] }, { key: 'city', label: 'City', label_es: 'Ciudad', phrases: ['2', 'city', 'ciudad'] }, { key: 'street', label: 'Street', label_es: 'Calle', phrases: ['3', 'street', 'calle'] }, { key: 'unit', label: 'Apartment', label_es: 'Apartamento', phrases: ['4', 'apartment', 'apt', 'unit', 'apartamento', 'unidad', 'departamento'] }, { key: 'all', label: 'Everything', label_es: 'Todo', phrases: ['5', 'all', 'everything', 'all of it', 'todo', 'toda'] }];
@@ -5,6 +5,7 @@ export { explainSession } from "./inspection.js";
5
5
  export { continuationBreaks } from "./continuation-compat.js";
6
6
  export { inheritFlowDeclaration } from "./declaration-capture.js";
7
7
  export { withSafetyRevision, CONTINUATION_SAFETY_REQUIREMENT } from "./continuation-safety.js";
8
+ export { attachScheduling, schedulingChangeForms } from "./scheduling-flows.js";
8
9
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue, confirmationFirmness } from "./flows.js";
9
10
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from "./contracts.js";
10
11
  export { addressDraft, zipLocation, streetLocation, resolvedAddress } from "../helpers/address.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAQA,0BAA+K"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/forms/index.js"],"names":[],"mappings":"AAUA,0BAA6L"}
@@ -6,7 +6,9 @@ import { FLOWS as CHOICE_FLOWS } from './choice-flow.js';
6
6
  import { FLOWS as IDENTITY } from './identity-flows.js';
7
7
  import { FLOWS as SEND_COPY } from './send-copy-flow.js';
8
8
  import { FLOWS as TRANSFER_LINE } from './transfer-line-flow.js';
9
- export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY, ...SEND_COPY, ...TRANSFER_LINE].map(flow => withSafetyRevision(flow, 'dispatch-intake-2026-10-22'));
9
+ import { FLOWS as SCHEDULING } from './scheduling-flows.js';
10
+ export { attachScheduling, schedulingChangeForms } from './scheduling-flows.js';
11
+ export const FLOWS = [...FORM_FLOWS, ...ADDRESS_FLOWS, ...CHOICE_FLOWS, ...IDENTITY, ...SEND_COPY, ...TRANSFER_LINE, ...SCHEDULING].map(flow => withSafetyRevision(flow, 'dispatch-intake-2026-10-22'));
10
12
  export { FIELD_PRESETS, formFlow, declinedFlow, textValue, confirmationFirmness } from './flows.js';
11
13
  export { FLOWS as IDENTITY_FLOWS } from './identity-flows.js';
12
14
  export { linkFormSchemas, defineWorker, defineProvider, defineForm, definePerformer, validateFlowContracts, operationWorkers, providerQuestions, providerParameter } from './contracts.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The scheduling inputs, first step, read-back and action, attached to a form the tenant authored (its name, description
3
+ * and own fields, as the Leads card writes them). `op` is book, move or cancel; `service` the cargo.scheduling.services
4
+ * key a booking form books. Idempotent: a form saved again gets the current fixed part, its own fields untouched.
5
+ */
6
+ export function attachScheduling(declaration: any, { service, op }?: {
7
+ service?: string | undefined;
8
+ op?: string | undefined;
9
+ }): any;
10
+ /** The tenant's reschedule and cancel forms: no fields of their own, so nothing for the tenant to author. */
11
+ export function schedulingChangeForms(): any[];
12
+ export const FLOWS: any[];
13
+ //# sourceMappingURL=scheduling-flows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduling-flows.d.ts","sourceRoot":"","sources":["../../src/forms/scheduling-flows.js"],"names":[],"mappings":"AAoRA;;;;GAIG;AACH;;;QAeC;AAED,6GAA6G;AAC7G,+CAMC;AAED,0BAAwG"}
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Scheduling (owner 2026-12-05): the shared workers behind the tenant's booking, reschedule and cancel forms.
3
+ * Tenant-agnostic; built into the system set like transfer-to-line.
4
+ *
5
+ * The User Admin Scheduling card writes ordinary native Performers that call these workers; the tenant's calendars and
6
+ * services are not in any flow. The host stamps them on every turn as cargo.scheduling:
7
+ * { hours: { timezone, hours }, the business hours (the User Admin hours editor's shape)
8
+ * calendars: [{ key, name, name_es?, schedule?, zips?, skills? }],
9
+ * services: { <key>: { name, name_es?, length, buffer?, time: 'exact'|'window', step?, windows?, per?,
10
+ * avail: 'check'|'accept', notice?, ahead?, skill?, who: 'pick'|'first'|'later', leads: 'us'|'customer',
11
+ * cutoff? (minutes before the start after which it cannot be changed here) } },
12
+ * identified: true when the channel's own number identifies the customer (a call, a text) }
13
+ *
14
+ * One host tool, iag:calendar ({ op, request, container: the cargo }), does everything that needs a tenant's data or credentials:
15
+ * busy { calendars, days } → [{ calendar, start, end }]
16
+ * find {} → { bookings: [{ id, service, calendar, start, end, date, from, to, window }] }
17
+ * the bookings of the verified customer: the caller's own number, or the contact a one-time code proved
18
+ * book { service, calendar, start, end, window, zip, customer } → { status: 'booked'|'taken'|'failed', id? }
19
+ * move { id, service, calendar, start, end, window } → { status: 'moved'|'taken'|'failed' } (the old time
20
+ * is kept until the new one is booked)
21
+ * cancel { id } → { status: 'cancelled'|'failed' }
22
+ *
23
+ * The forms: the tenant authors a booking form per service (name, description and its own fields, as the Leads card
24
+ * writes them); the host's Save calls attachScheduling(form, {service, op:'book'}) for the fixed part (inputs sched_zip,
25
+ * sched_calendar, sched_when, sched_slot, the first step, the read-back and the action) and installs
26
+ * schedulingChangeForms() for reschedule and cancel. Both are below; the journeys test exactly these.
27
+ */
28
+ import { defineWorker } from './contracts.js';
29
+ const S = (id, variable, value) => ({ id, type: 'SET', variable, value });
30
+ const W = (id, condition, step) => ({ id, type: 'CASE', branches: { ['condition: ' + condition]: step, default: S(id + '_skip', 'noop', 'true') } });
31
+ const V = o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, { type: Array.isArray(v) ? 'array' : v === null || typeof v === 'object' ? 'object' : typeof v, value: v }]));
32
+ const E = (fn, ...args) => `(${fn.toString()})(${args.join(',')})`;
33
+ const P = (name, type = 'string') => ({ name, type, description: name });
34
+ const C = (id, summary, steps, extra = {}) => defineWorker({ id, name: id.split('-').map(w => w[0].toUpperCase() + w.slice(1)).join(''), description: summary, ...extra, contract: { role: 'worker', summary, ...extra.contract }, steps });
35
+ const CALENDAR = (id, op, request, variable, fallback) => ({ id, type: 'CALL-TOOL', tool: 'iag:calendar', variable, args: { op, request, container: '{{cargo}}' }, onFail: S(id + '_failed', variable, fallback) });
36
+ // Ends the form and every flow under it: a worker's own END would end only the worker, and the form would ask on.
37
+ // Its wording is set in the worker's own stop_* variables first, so the new root flow receives plain values.
38
+ const STOP = (id, condition, message, message_es, outcome, reason) => [
39
+ S(id + '_message', 'stop_message', message), S(id + '_message_es', 'stop_message_es', message_es), S(id + '_outcome', 'stop_outcome', outcome), S(id + '_reason', 'stop_reason', reason),
40
+ W(id, condition, { id: id + '_flow', type: 'FLOW', value: 'sched-stop', callType: 'reboot', parameters: { message: '{{stop_message}}', message_es: '{{stop_message_es}}', outcome: '{{stop_outcome}}', reason: '{{stop_reason}}' } })
41
+ ];
42
+ const STOP_VARS = { stop_message: '', stop_message_es: '', stop_outcome: '', stop_reason: '' };
43
+ const ANYTHING_ELSE = " {{anythingElse('en')}}";
44
+ const ANYTHING_ELSE_ES = " {{anythingElse('es')}}";
45
+ // ---- pure pieces, inlined into the expressions (standard functions are in scope by name there) ----
46
+ // The form's settings, from cargo.scheduling and the service the form names.
47
+ function startData(cargo, form, service, op) {
48
+ const cfg = cargo.scheduling || {}, svc = (cfg.services || {})[service] || null, cals = Array.isArray(cfg.calendars) ? cfg.calendars : [];
49
+ // every flag a form's conditions read is set, false when it does not apply: an unset one blocks the form
50
+ const data = Object.assign({}, cargo.forms[form].data || {}, { op: op, service: service, ok: op !== 'book' || !!svc, need_zip: false, pick: false, customer_leads: false });
51
+ if (svc) {
52
+ data.service_name = String(svc.name || service);
53
+ data.service_name_es = String(svc.name_es || svc.name || service);
54
+ data.need_zip = cals.some(function (c) { return Array.isArray(c.zips) && c.zips.length > 0; });
55
+ data.pick = svc.who === 'pick' && cals.length > 1;
56
+ data.customer_leads = svc.leads === 'customer';
57
+ }
58
+ else {
59
+ data.service_name = '';
60
+ data.service_name_es = '';
61
+ }
62
+ cargo.forms[form].data = data;
63
+ return data.ok;
64
+ }
65
+ // The calendars that can take the service at the customer's zip code.
66
+ function eligible(cfg, svc, zip) {
67
+ const skill = String((svc && svc.skill) || '').toLowerCase();
68
+ return (Array.isArray(cfg.calendars) ? cfg.calendars : []).filter(function (c) {
69
+ return zipCovered(c.zips, zip) && (!skill || (Array.isArray(c.skills) && c.skills.some(function (s) { return String(s).toLowerCase() === skill; })));
70
+ });
71
+ }
72
+ // "a, b or c" / "a, b o c" (inlined functions see no module scope: offerData and bookingData carry their own copy).
73
+ function listed(items, or) {
74
+ return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1];
75
+ }
76
+ // The offered times as choices, and the question that offers them.
77
+ function offerData(data, slots, voice) {
78
+ const listed = function (items, or) { return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1]; };
79
+ const later = { key: 'later', phrases: ['later', 'something later', 'a later time', 'later times', 'más tarde', 'algo más tarde', 'otra hora más tarde'], label: 'A later time', label_es: 'Más tarde', neutral: true };
80
+ data.slots = slots;
81
+ // an exact time is also picked by its clock ("10 AM", "a las 10"), never by a bare number, which is a key
82
+ const clocks = function (s) {
83
+ if (s.window)
84
+ return [];
85
+ const h = parseInt(s.from, 10), m = s.from.slice(3), h12 = h % 12 || 12, ap = h < 12 ? 'am' : 'pm', hm = m === '00' ? String(h12) : h12 + ':' + m;
86
+ return [hm + ' ' + ap, hm + ap, 'at ' + hm, 'a las ' + (m === '00' ? String(h) : h + ':' + m), 'a la ' + hm];
87
+ };
88
+ const clockCount = {};
89
+ slots.forEach(function (s) { clocks(s).forEach(function (c) { clockCount[c] = (clockCount[c] || 0) + 1; }); });
90
+ data.slot_choices = slots.map(function (s, i) {
91
+ const own = clocks(s).filter(function (c) { return clockCount[c] === 1; });
92
+ return { key: s.key, keys: [String(i + 1)], phrases: [s.label, s.label_es].concat(own, slots.length === 1 ? ['yes', 'sí', 'si', 'that works', 'ok', 'okay'] : []), label: s.label, label_es: s.label_es, neutral: true };
93
+ }).concat(slots.length ? [later] : []);
94
+ const en = slots.map(function (s) { return s.label; }), es = slots.map(function (s) { return s.label_es; });
95
+ const keysEn = voice ? '' : ' ' + (slots.length > 1 ? 'Type 1 to ' + slots.length + '.' : 'Type 1 or YES.');
96
+ const keysEs = voice ? '' : ' ' + (slots.length > 1 ? 'Escriba del 1 al ' + slots.length + '.' : 'Escriba 1 o SÍ.');
97
+ if (!slots.length) {
98
+ data.slot_question = data.pref ? 'I do not have an opening then. What other day or time would work for you?' : 'I do not see an opening in the coming days. What day or time would work for you?';
99
+ data.slot_question_es = data.pref ? 'No tengo un espacio disponible en ese momento. ¿Qué otro día u hora le funcionaría?' : 'No veo espacios disponibles en los próximos días. ¿Qué día u hora le funcionaría?';
100
+ }
101
+ else if (slots.length === 1) {
102
+ data.slot_question = 'I have ' + en[0] + '. Does that work for you?' + keysEn;
103
+ data.slot_question_es = 'Tengo ' + es[0] + '. ¿Le funciona?' + keysEs;
104
+ }
105
+ else {
106
+ data.slot_question = 'I have ' + listed(en, 'or') + '. Which works for you? You can also ask for another day or time.' + keysEn;
107
+ data.slot_question_es = 'Tengo ' + listed(es, 'o') + '. ¿Cuál le funciona? También puede pedir otro día u hora.' + keysEs;
108
+ }
109
+ return true;
110
+ }
111
+ // The customer's bookings as choices; one too close to change is named and not offered.
112
+ function bookingData(data, bookings, services, timezone, voice) {
113
+ const listed = function (items, or) { return items.length < 2 ? (items[0] || '') : items.slice(0, -1).join(', ') + ' ' + or + ' ' + items[items.length - 1]; };
114
+ const today = todayIn(timezone);
115
+ const name = function (b, es) { const s = services[b.service] || {}; return String((es ? s.name_es : '') || s.name || b.service || (es ? 'cita' : 'appointment')); };
116
+ const word = function (b, es) { return name(b, es) + (es ? ' ' : ' ') + slotToWords(b, es ? 'es' : 'en', today); };
117
+ const open = [], locked = [];
118
+ (Array.isArray(bookings) ? bookings : []).forEach(function (b) {
119
+ const cutoff = Number((services[b.service] || {}).cutoff) || 0;
120
+ if (minutesUntil(b.start) < Math.max(0, cutoff)) {
121
+ locked.push(b);
122
+ }
123
+ else {
124
+ open.push(b);
125
+ }
126
+ });
127
+ data.bookings = open;
128
+ data.booking_choices = open.map(function (b, i) { return { key: String(b.id), keys: [String(i + 1)], phrases: [word(b, false), word(b, true)].concat(open.length === 1 ? ['yes', 'sí', 'si', 'that one', 'esa'] : []), label: word(b, false), label_es: word(b, true), neutral: true }; });
129
+ data.locked_note = locked.length ? 'Your ' + word(locked[0], false) + ' is too close to change here; please call our office.' : '';
130
+ data.locked_note_es = locked.length ? 'Su cita de ' + word(locked[0], true) + ' está demasiado cerca para cambiarla aquí; por favor llame a nuestra oficina.' : '';
131
+ data.no_bookings = !open.length;
132
+ const keys = voice ? '' : (open.length > 1 ? ' Type 1 to ' + open.length + '.' : ' Type 1 or YES.');
133
+ const keysEs = voice ? '' : (open.length > 1 ? ' Escriba del 1 al ' + open.length + '.' : ' Escriba 1 o SÍ.');
134
+ data.booking_question = open.length === 1 ? 'I found your ' + word(open[0], false) + '. Is that the one?' + keys : 'Which appointment is it: ' + listed(open.map(function (b) { return word(b, false); }), 'or') + '?' + keys;
135
+ data.booking_question_es = open.length === 1 ? 'Encontré su cita de ' + word(open[0], true) + '. ¿Es esa?' + keysEs : '¿Qué cita es: ' + listed(open.map(function (b) { return word(b, true); }), 'o') + '?' + keysEs;
136
+ return true;
137
+ }
138
+ // The exact request for the confirmed action, and the read-back that confirms it.
139
+ function prepareData(cargo, form) {
140
+ const f = cargo.forms[form], d = f.data || {}, v = f.values || {}, cfg = cargo.scheduling || {};
141
+ const svc = (cfg.services || {})[d.service] || {}, tz = (cfg.hours && cfg.hours.timezone) || 'UTC', today = todayIn(tz);
142
+ const cal = (cfg.calendars || []).filter(function (c) { return d.slot && c.key === d.slot.calendar; })[0];
143
+ const yn = { en: yesNoKeys('en', cargo), es: yesNoKeys('es', cargo) };
144
+ const name = { en: d.service_name || 'appointment', es: d.service_name_es || d.service_name || 'cita' };
145
+ const customer = {};
146
+ Object.keys(v).forEach(function (k) { if (k.indexOf('sched_') !== 0)
147
+ customer[k] = v[k]; });
148
+ if (d.op === 'cancel') {
149
+ cargo.actionRequest = { op: 'cancel', id: String(d.booking.id) };
150
+ cargo.schedulingConfirm = {
151
+ question: 'Would you like me to cancel your ' + name.en + ' ' + slotToWords(d.booking, 'en', today) + '? If you would rather move it to another time, just say so. ' + yn.en,
152
+ question_es: '¿Desea que cancele su cita de ' + name.es + ' ' + slotToWords(d.booking, 'es', today) + '? Si prefiere cambiarla a otra hora, solo dígalo. ' + yn.es
153
+ };
154
+ return true;
155
+ }
156
+ const who = svc.who === 'later' ? '' : String(d.slot.calendar || '');
157
+ const withWhom = d.pick && cal ? { en: ' with ' + cal.name, es: ' con ' + (cal.name_es || cal.name) } : { en: '', es: '' };
158
+ if (d.op === 'move') {
159
+ cargo.actionRequest = { op: 'move', id: String(d.booking.id), service: d.service, calendar: who, start: d.slot.start, end: d.slot.end, window: !!d.slot.window };
160
+ cargo.schedulingConfirm = {
161
+ question: 'To confirm: I will move your ' + name.en + ' from ' + slotToWords(d.booking, 'en', today) + ' to ' + slotToWords(d.slot, 'en', today) + '. Is that right? ' + yn.en,
162
+ question_es: 'Para confirmar: cambiaré su cita de ' + name.es + ' de ' + slotToWords(d.booking, 'es', today) + ' a ' + slotToWords(d.slot, 'es', today) + '. ¿Es correcto? ' + yn.es
163
+ };
164
+ return true;
165
+ }
166
+ cargo.actionRequest = { op: 'book', service: d.service, calendar: who, start: d.slot.start, end: d.slot.end, window: !!d.slot.window, zip: String(v.sched_zip || ''), customer: customer };
167
+ cargo.schedulingConfirm = {
168
+ question: 'To confirm: ' + name.en + ' ' + slotToWords(d.slot, 'en', today) + withWhom.en + '. Shall I book it? ' + yn.en,
169
+ question_es: 'Para confirmar: ' + name.es + ' ' + slotToWords(d.slot, 'es', today) + withWhom.es + '. ¿Reservo la cita? ' + yn.es
170
+ };
171
+ return true;
172
+ }
173
+ // What the customer hears once the calendar answered.
174
+ function presentLine(cargo, form, result, es) {
175
+ const d = cargo.forms[form].data || {}, cfg = cargo.scheduling || {}, svc = (cfg.services || {})[d.service] || {};
176
+ const today = todayIn((cfg.hours && cfg.hours.timezone) || 'UTC');
177
+ const L = es ? 'es' : 'en', name = es ? (d.service_name_es || d.service_name || 'cita') : (d.service_name || 'appointment');
178
+ const status = result && result.status;
179
+ if (status === 'booked') {
180
+ return es ? 'Listo, su cita de ' + name + ' quedó reservada para ' + slotToWords(d.slot, L, today) + '.' + (svc.who === 'later' ? ' Nuestra oficina le avisará quién irá.' : '')
181
+ : 'You are all set: ' + name + ' ' + slotToWords(d.slot, L, today) + '.' + (svc.who === 'later' ? ' Our office will let you know who is coming.' : '');
182
+ }
183
+ else if (status === 'moved') {
184
+ return es ? 'Listo, su cita de ' + name + ' ahora es ' + slotToWords(d.slot, L, today) + '.' : 'Done. Your ' + name + ' is now ' + slotToWords(d.slot, L, today) + '.';
185
+ }
186
+ else if (status === 'cancelled') {
187
+ return es ? 'Su cita de ' + name + ' ' + slotToWords(d.booking, L, today) + ' quedó cancelada.' : 'Your ' + name + ' ' + slotToWords(d.booking, L, today) + ' is cancelled.';
188
+ }
189
+ else if (status === 'taken') {
190
+ return es ? 'Lo siento, ese horario se acaba de ocupar. Pídame otra hora cuando guste.' : 'I am sorry, that time was just taken. Ask me for another time whenever you like.';
191
+ }
192
+ else if (status === 'failed') {
193
+ return es ? 'Lo siento, no pude hacer ese cambio en este momento.' : 'I am sorry, I could not make that change right now.';
194
+ }
195
+ else {
196
+ return es ? 'No pude confirmar si el cambio se hizo, así que por favor consulte con nuestra oficina antes de intentarlo de nuevo.' : 'I could not confirm whether that went through, so please check with our office before trying again.';
197
+ }
198
+ }
199
+ // ---- workers ----
200
+ const start = C('sched-start', 'Load the service the form books from cargo.scheduling; a service the tenant does not offer ends the form.', [
201
+ S('sched_start', 'ok', E(startData, 'cargo', 'form', 'service', 'op')),
202
+ ...STOP('sched_start_stop', '!ok', "'Sorry, I cannot book that here.'", "'Lo siento, no puedo reservar eso aquí.'", "'unresolved'", "'scheduling_not_offered'")
203
+ ], { parameters: [P('form'), P('service'), P('op')], variables: V({ ok: false, ...STOP_VARS }), contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
204
+ const zip = C('sched-zip-validate', 'A zip code no calendar covers is outside the service area.', [
205
+ S('sched_zip_check', 'noop', "(function(cfg,svc,zip){var ok=" + E(eligible, 'cfg', 'svc', 'zip') + ".length>0;cargo.inputCheck=ok?{ok:true,value:zip}:{ok:false,message:'Sorry, we do not serve zip code '+zip+'.',message_es:'Lo siento, no damos servicio en el código postal '+zip+'.'};return true;})(cargo.scheduling||{},((cargo.scheduling||{}).services||{})[cargo.forms[form].data.service],String(value))")
206
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
207
+ const calendarPrompt = C('sched-calendar-prompt', 'Offer the calendars that cover the customer\'s zip code, by name, and first available.', [
208
+ S('sched_calendar_prompt', 'noop', "(function(d,cfg,voice){var cals=" + E(eligible, 'cfg', '(cfg.services||{})[d.service]', "String((cargo.forms[form].values||{}).sched_zip||'')") + ",names=cals.map(function(c){return c.name;}),names_es=cals.map(function(c){return c.name_es||c.name;});d.calendar_choices=cals.map(function(c,i){return {key:c.key,keys:[String(i+1)],phrases:[c.name].concat(c.name_es?[c.name_es]:[]),label:c.name,label_es:c.name_es||c.name,neutral:true};}).concat([{key:'any',keys:[String(cals.length+1)],phrases:['first available','anyone','any','whoever is first','el primero disponible','cualquiera'],label:'First available',label_es:'El primero disponible',neutral:true}]);d.calendar_question='Who would you like: '+" + E(listed, 'names', "'or'") + "+'? Or I can book whoever is first available.'+(voice?'':' Type 1 to '+(cals.length+1)+'.');d.calendar_question_es='¿Con quién desea: '+" + E(listed, 'names_es', "'o'") + "+'? O puedo reservar con el primero disponible.'+(voice?'':' Escriba del 1 al '+(cals.length+1)+'.');return true;})(cargo.forms[form].data,cargo.scheduling||{},cargo.voice===true)")
209
+ ], { parameters: [P('form'), P('input')], contract: { result: { path: 'cargo.forms[form].data', type: 'object' } } });
210
+ const when = C('sched-when-validate', 'Read when the customer would like to come; a time with no day keeps the day already asked for; words with no day or time are asked again.', [
211
+ S('sched_when_read', 'pref', "readWhen(String(value),{timezone:((cargo.scheduling||{}).hours||{}).timezone||'UTC'})"),
212
+ S('sched_when_check', 'noop', "(function(d){if(!pref){cargo.inputCheck={ok:false,message:'Sorry, I did not catch a day or time.',message_es:'Disculpe, no entendí un día o una hora.'};return true;}if(!pref.dates&&!pref.later&&!pref.any&&d.pref&&d.pref.dates){pref.dates=d.pref.dates;}d.not_before=pref.later&&d.slots&&d.slots.length?new Date(Date.parse(d.slots[d.slots.length-1].start)+60000).toISOString():null;d.pref=pref.any||pref.later?null:pref;cargo.inputCheck={ok:true,value:String(value)};return true;})(cargo.forms[form].data)")
213
+ ], { parameters: [P('form'), P('value')], variables: V({ pref: null }), contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
214
+ const offer = C('sched-offer', 'Before each time question: read the busy times (unless the customer\'s time is accepted) and offer up to three open times.', [
215
+ S('sched_offer_cfg', 'cfg', 'cargo.scheduling || {}'),
216
+ S('sched_offer_data', 'd', 'cargo.forms[form].data'),
217
+ S('sched_offer_svc', 'svc', "(cfg.services || {})[d.service] || {}"),
218
+ S('sched_offer_values', 'vals', 'cargo.forms[form].values || {}'),
219
+ S('sched_offer_cals', 'cals', E(eligible, 'cfg', 'svc', "String(vals.sched_zip || '')") + ".filter(function(c){return (!vals.sched_calendar || vals.sched_calendar === 'any' || c.key === vals.sched_calendar) && (!d.booking || !d.booking.calendar || c.key === d.booking.calendar);})"),
220
+ S('sched_offer_keys', 'keys', 'cals.map(function(c){return c.key;})'),
221
+ S('sched_offer_days', 'days', 'Number(svc.ahead) || 30'),
222
+ W('sched_offer_busy', "svc.avail !== 'accept' && cals.length > 0", CALENDAR('sched_offer_busy_tool', 'busy', { calendars: '{{keys}}', days: '{{days}}' }, 'busy', 'null')),
223
+ S('sched_offer_slots', 'slots', "svc.avail !== 'accept' && !Array.isArray(busy) ? [] : openSlots({hours:cfg.hours,calendars:cals,service:svc,busy:Array.isArray(busy)?busy:[],preference:d.not_before?Object.assign({},d.pref||{},{notBefore:d.not_before}):d.pref,zip:String(vals.sched_zip||''),count:3})"),
224
+ S('sched_offer_question', 'noop', E(offerData, 'd', 'slots', 'cargo.voice === true')),
225
+ W('sched_offer_unreachable', "svc.avail !== 'accept' && cals.length > 0 && !Array.isArray(busy)", S('sched_offer_unreachable_q', 'noop', "(d.slot_question='I am sorry, I cannot see our calendar right now. Please try again a little later.',d.slot_question_es='Lo siento, no puedo ver nuestro calendario en este momento. Por favor intente un poco más tarde.',true)"))
226
+ ], { parameters: [P('form'), P('input')], variables: V({ cfg: null, d: null, svc: null, vals: null, cals: [], keys: [], days: 30, busy: null, slots: [] }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.forms[form].data', type: 'object' } } });
227
+ const slot = C('sched-slot-validate', 'Take an offered time; LATER moves the offer past the last time offered.', [
228
+ S('sched_slot_check', 'noop', "(function(d){var key=String(value),s=(d.slots||[]).filter(function(x){return x.key===key;})[0];if(key==='later'){d.not_before=d.slots&&d.slots.length?new Date(Date.parse(d.slots[d.slots.length-1].start)+60000).toISOString():null;cargo.inputCheck={ok:false,quiet:true};return true;}if(!s){cargo.inputCheck={ok:false,quiet:true};return true;}d.slot=s;cargo.inputCheck={ok:true,value:key};return true;})(cargo.forms[form].data)")
229
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
230
+ const find = C('sched-find', 'Before the booking question: prove who the customer is (a one-time code unless their own number identifies them), then list their upcoming bookings.', [
231
+ W('sched_find_verify', "!((cargo.scheduling || {}).identified === true) && cargo.otpVerified !== true", { id: 'sched_find_auth', type: 'FLOW', value: 'authenticate-user', callType: 'call', parameters: { parent_form: '{{form}}' } }),
232
+ W('sched_find_lookup', "(cargo.scheduling || {}).identified === true || cargo.otpVerified === true", CALENDAR('sched_find_tool', 'find', {}, 'found', 'null')),
233
+ S('sched_find_data', 'noop', E(bookingData, 'cargo.forms[form].data', 'found && found.bookings', "(cargo.scheduling || {}).services || {}", "((cargo.scheduling || {}).hours || {}).timezone || 'UTC'", 'cargo.voice === true')),
234
+ ...STOP('sched_find_stop', "cargo.forms[form].data.no_bookings", "!found ? 'I am sorry, I cannot look up appointments right now.' : (cargo.forms[form].data.locked_note || 'I do not see any upcoming appointments for you.')", "!found ? 'Lo siento, no puedo consultar citas en este momento.' : (cargo.forms[form].data.locked_note_es || 'No veo citas próximas a su nombre.')", "found ? 'resolved' : 'unresolved'", "found ? (cargo.forms[form].data.locked_note ? 'booking_inside_cutoff' : 'no_bookings') : 'calendar_unavailable'")
235
+ ], { parameters: [P('form'), P('input')], variables: V({ found: null, ...STOP_VARS }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.forms[form].data', type: 'object' } } });
236
+ const booking = C('sched-booking-validate', 'Take one of the customer\'s bookings; a move offers times for the same service, on the same calendar.', [
237
+ S('sched_booking_check', 'noop', "(function(d){var b=(d.bookings||[]).filter(function(x){return String(x.id)===String(value);})[0];if(!b){cargo.inputCheck={ok:false,quiet:true};return true;}var svc=((cargo.scheduling||{}).services||{})[b.service]||{};d.booking=b;d.service=b.service;d.customer_leads=svc.leads==='customer';d.service_name=String(svc.name||b.service||'');d.service_name_es=String(svc.name_es||svc.name||b.service||'');cargo.inputCheck={ok:true,value:String(b.id)};return true;})(cargo.forms[form].data)")
238
+ ], { parameters: [P('form'), P('value')], contract: { result: { path: 'cargo.inputCheck', type: 'object' } } });
239
+ const prepare = C('sched-prepare', 'The exact request for the confirmed booking, move or cancellation, and its read-back.', [
240
+ S('sched_prepare', 'noop', E(prepareData, 'cargo', 'form'))
241
+ ], { parameters: [P('form')], contract: { result: { path: 'cargo.actionRequest', type: 'object' } } });
242
+ const execute = C('sched-execute', 'Send the confirmed request to the tenant\'s calendar once; no answer is an unknown result, never a retry.', [
243
+ CALENDAR('sched_execute_tool', '{{request.op}}', '{{request}}', 'reply', "({status:'unknown'})"),
244
+ S('sched_execute_result', 'noop', "(cargo.actionOutcome = reply && typeof reply === 'object' && reply.status ? reply : {status:'unknown'}, true)")
245
+ ], { parameters: [P('request', 'object')], variables: V({ reply: null }), contract: { tools: ['iag:calendar'], result: { path: 'cargo.actionOutcome', type: 'object' } } });
246
+ const present = C('sched-present', 'Tell the customer what the calendar did.', [
247
+ S('sched_present_en', 'line', E(presentLine, 'cargo', 'form', 'result', 'false')),
248
+ S('sched_present_es', 'line_es', E(presentLine, 'cargo', 'form', 'result', 'true')),
249
+ { id: 'sched_present_say', type: 'SAY', value: '{{line}}' + ANYTHING_ELSE, value_es: '{{line_es}}' + ANYTHING_ELSE_ES }
250
+ ], { parameters: [P('form'), P('request', 'object'), P('result', 'object')], variables: V({ line: '', line_es: '' }) });
251
+ const stop = C('sched-stop', 'Say why scheduling cannot go on here, and end.', [
252
+ { id: 'sched_stop_say', type: 'SAY', value: '{{message}}' + ANYTHING_ELSE, value_es: '{{message_es || message}}' + ANYTHING_ELSE_ES },
253
+ { id: 'sched_stop_end', type: 'END', outcome: '{{outcome}}', reason: '{{reason}}' }
254
+ ], { parameters: [P('message'), P('message_es'), P('outcome'), P('reason')] });
255
+ // ---- the fixed part of every scheduling form: one source for the host's Save and for the tests ----
256
+ const WHEN_HINT = 'When the customer would rather come, in their own words: a day, a date, a part of the day or a time ("Thursday afternoon", "after 5", "el sábado por la mañana"), or a request for later times';
257
+ const INPUTS = {
258
+ sched_zip: { name: 'sched_zip', field: 'zip', when: { 'form.data.need_zip': true }, validator: 'sched-zip-validate', question: 'What is the zip code where you need us?', question_es: '¿Cuál es el código postal donde nos necesita?' },
259
+ sched_calendar: { name: 'sched_calendar', label: 'who', label_es: 'con quién', profile: { kind: 'choice', choices: [] }, choices_from: 'calendar_choices', refresh: 'sched-calendar-prompt', question_from: 'calendar_question', question: 'Who would you like?', question_es: '¿Con quién desea?', when: { 'form.data.pick': true }, reset_on: ['sched_zip'] },
260
+ sched_when: { name: 'sched_when', label: 'preferred time', label_es: 'hora preferida', argument_description: WHEN_HINT, profile: { kind: 'text' }, validator: 'sched-when-validate', required_when: { 'form.data.customer_leads': true }, question: 'When would be a good time for us?', question_es: '¿Cuándo sería un buen momento para usted?' },
261
+ sched_slot: { name: 'sched_slot', label: 'time', label_es: 'hora', profile: { kind: 'choice', choices: [] }, choices_from: 'slot_choices', refresh: 'sched-offer', question_from: 'slot_question', validator: 'sched-slot-validate', max_attempts: 8, rank_parameters: [{ name: 'sched_when', description: WHEN_HINT, reads: 'sched_when' }], question: 'Which time works for you?', question_es: '¿Qué hora le funciona?' },
262
+ sched_booking: { name: 'sched_booking', label: 'appointment', label_es: 'cita', profile: { kind: 'choice', choices: [] }, choices_from: 'booking_choices', refresh: 'sched-find', question_from: 'booking_question', validator: 'sched-booking-validate', question: 'Which appointment is it?', question_es: '¿Qué cita es?' },
263
+ };
264
+ const ACTIONS = {
265
+ book: { action: 'book_appointment', effect: 'write', ok: 'booked' },
266
+ move: { action: 'move_appointment', effect: 'write', ok: 'moved' },
267
+ cancel: { action: 'cancel_appointment', effect: 'cancel', ok: 'cancelled' },
268
+ };
269
+ const OWN_STEP = 'sched_begin';
270
+ const clone = value => JSON.parse(JSON.stringify(value));
271
+ /**
272
+ * The scheduling inputs, first step, read-back and action, attached to a form the tenant authored (its name, description
273
+ * and own fields, as the Leads card writes them). `op` is book, move or cancel; `service` the cargo.scheduling.services
274
+ * key a booking form books. Idempotent: a form saved again gets the current fixed part, its own fields untouched.
275
+ */
276
+ export function attachScheduling(declaration, { service = '', op = 'book' } = {}) {
277
+ if (!ACTIONS[op])
278
+ throw new Error(`attachScheduling: unknown op ${op}`);
279
+ const flow = clone(declaration), form = flow.form = flow.form || {};
280
+ const own = (form.inputs || []).filter(input => !String(input && input.name || '').startsWith('sched_'));
281
+ const fixed = op === 'book' ? [INPUTS.sched_zip, INPUTS.sched_calendar, INPUTS.sched_when, { ...INPUTS.sched_slot, reset_on: ['sched_zip', 'sched_calendar', 'sched_when'] }]
282
+ : op === 'move' ? [INPUTS.sched_booking, INPUTS.sched_when, { ...INPUTS.sched_slot, depends_on: ['sched_booking'], reset_on: ['sched_when', 'sched_booking'] }]
283
+ : [INPUTS.sched_booking];
284
+ form.inputs = [...clone(fixed), ...own];
285
+ form.before = [{ id: OWN_STEP, type: 'FLOW', value: 'sched-start', callType: 'call', parameters: { form: '{{form_instance}}', service, op } }, ...(form.before || []).filter(step => step && step.id !== OWN_STEP)];
286
+ form.confirm = { question: '{{cargo.schedulingConfirm.question}}', question_es: '{{cargo.schedulingConfirm.question_es}}' };
287
+ const a = ACTIONS[op];
288
+ flow.performs = [{ action: a.action, effect: a.effect, flow: 'sched-execute', confirm: { exact: true }, outcomes: { [a.ok]: 'resolved', taken: 'unresolved', failed: 'unresolved', unknown: 'unresolved' } }];
289
+ flow.prepare = 'sched-prepare';
290
+ flow.present = 'sched-present';
291
+ return flow;
292
+ }
293
+ /** The tenant's reschedule and cancel forms: no fields of their own, so nothing for the tenant to author. */
294
+ export function schedulingChangeForms() {
295
+ const base = (id, name, description) => ({ declarationVersion: 2, id, name, version: '1.0.0', primary: true, description, form: { inputs: [] } });
296
+ return [
297
+ attachScheduling(base('reschedule-appointment', 'RescheduleAppointment', 'The customer wants to move an appointment they already have to another day or time.'), { op: 'move' }),
298
+ attachScheduling(base('cancel-appointment', 'CancelAppointment', 'The customer wants to cancel an appointment they already have.'), { op: 'cancel' }),
299
+ ];
300
+ }
301
+ export const FLOWS = [stop, start, zip, calendarPrompt, when, offer, slot, find, booking, prepare, execute, present];
@@ -43,7 +43,10 @@ export function addressVerdict(result: any, said: any): {
43
43
  } | null;
44
44
  /** The validate-address verdict applied to the street answer (the street validator's last step). Returns the validator's
45
45
  * answer: a proposal to confirm Google's version first, or the street accepted. `keys` are the yes/no words for each language. */
46
- export function streetCheck(state: any, values: any, verdict: any, value: any, reading: any, keys: any): {
46
+ /** The unit that goes into the street's one check: the form's, else the unit the street answer itself carries ("# 2",
47
+ * "Apt 2", "apartamento 2"), read with the unit input's own pattern. '' when none, or when it is not unit-shaped. */
48
+ export function streetUnit(state: any, values: any, reading: any): any;
49
+ export function streetCheck(state: any, values: any, verdict: any, value: any, reading: any, keys: any, unit: any): {
47
50
  ok: boolean;
48
51
  value: string;
49
52
  proposal: any;
@@ -73,9 +76,20 @@ export function unitsGiven(state: any): {
73
76
  invalid: {
74
77
  name: string;
75
78
  }[];
79
+ message?: undefined;
80
+ message_es?: undefined;
81
+ } | {
82
+ ok: boolean;
83
+ invalid: {
84
+ name: string;
85
+ }[];
86
+ message: string;
87
+ message_es: string;
76
88
  } | {
77
89
  ok: boolean;
78
90
  invalid?: undefined;
91
+ message?: undefined;
92
+ message_es?: undefined;
79
93
  };
80
94
  /** The unit question: the building's own wording once Google says it has units, else the form's ordinary one. */
81
95
  export function unitQuestion(data: any, building: any): boolean;
@@ -87,24 +101,43 @@ export function unitPrecheck(data: any, value: any): {
87
101
  message_es: string;
88
102
  value?: undefined;
89
103
  check?: undefined;
104
+ known?: undefined;
105
+ confirmed?: undefined;
90
106
  unit?: undefined;
91
107
  } | {
92
108
  ok: boolean;
93
109
  value: string;
94
110
  check: boolean;
111
+ known: boolean;
112
+ confirmed: any;
95
113
  unit: string;
96
114
  message?: undefined;
97
115
  message_es?: undefined;
116
+ } | {
117
+ ok: boolean;
118
+ value: string;
119
+ check: boolean;
120
+ unit: string;
121
+ message?: undefined;
122
+ message_es?: undefined;
123
+ known?: undefined;
124
+ confirmed?: undefined;
98
125
  } | {
99
126
  ok: boolean;
100
127
  value: string;
101
128
  message?: undefined;
102
129
  message_es?: undefined;
103
130
  check?: undefined;
131
+ known?: undefined;
132
+ confirmed?: undefined;
104
133
  unit?: undefined;
105
134
  };
106
135
  /** Google's answer for the address with its unit: a unit it could not confirm is asked once more, then kept as given. */
107
136
  export function unitResult(data: any, pre: any, checked: any): {
137
+ ok: boolean;
138
+ message: string;
139
+ message_es: string;
140
+ } | {
108
141
  message?: any;
109
142
  message_es?: any;
110
143
  quiet?: boolean | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src/helpers/address.js"],"names":[],"mappings":"AAEA;;;;;EAQC;AACD;;;;;SAWC;AACD,gDAEC;AACD;;;;;EASC;AACD;gHACgH;AAChH,8DAIC;AACD,sGAAsG;AACtG,oFAKC;AACD;;;uGAGuG;AACvG;;;;;;;;;;;;;;SAeC;AACD;kIACkI;AAClI;;;;;;;;;;;;;;;;EAyCC;AACD;qFACqF;AACrF,uFASC;AACD;mGACmG;AACnG,oDAKC;AACD;sDACsD;AACtD;;;;;;;;EAIC;AACD,iHAAiH;AACjH,gEAIC;AACD;0EAC0E;AAC1E;;;;;;;;;;;;;;;;;;;;;EAKC;AACD,yHAAyH;AACzH;;;;;;EAUC;AACD;;;;;;;;;;;EAQC"}
1
+ {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../../src/helpers/address.js"],"names":[],"mappings":"AAEA;;;;;EAQC;AACD;;;;;SAWC;AACD,gDAEC;AACD;;;;;EASC;AACD;gHACgH;AAChH,8DAIC;AACD,sGAAsG;AACtG,oFAKC;AACD;;;uGAGuG;AACvG;;;;;;;;;;;;;;SAeC;AACD;kIACkI;AAClI;qHACqH;AACrH,uEASC;AACD;;;;;;;;;;;;;;;;EA2CC;AACD;qFACqF;AACrF,uFASC;AACD;mGACmG;AACnG,oDAKC;AACD;sDACsD;AACtD;;;;;;;;;;;;;;;;;;;EAUC;AACD,iHAAiH;AACjH,gEAIC;AACD;0EAC0E;AAC1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAMC;AACD,yHAAyH;AACzH;;;;;;;;;;EAaC;AACD;;;;;;;;;;;EAQC"}