@voyantjs/bookings 0.119.1 → 0.119.3

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.
Files changed (49) hide show
  1. package/dist/action-ledger-drift.d.ts.map +1 -1
  2. package/dist/action-ledger-drift.js +7 -2
  3. package/dist/pricing-assignment/age.d.ts +33 -0
  4. package/dist/pricing-assignment/age.d.ts.map +1 -0
  5. package/dist/pricing-assignment/age.js +109 -0
  6. package/dist/pricing-assignment/draft.d.ts +69 -0
  7. package/dist/pricing-assignment/draft.d.ts.map +1 -0
  8. package/dist/pricing-assignment/draft.js +284 -0
  9. package/dist/pricing-assignment/types.d.ts +113 -0
  10. package/dist/pricing-assignment/types.d.ts.map +1 -0
  11. package/dist/pricing-assignment/types.js +30 -0
  12. package/dist/pricing-assignment/unit-helpers.d.ts +11 -0
  13. package/dist/pricing-assignment/unit-helpers.d.ts.map +1 -0
  14. package/dist/pricing-assignment/unit-helpers.js +19 -0
  15. package/dist/pricing-assignment/verify.d.ts +67 -0
  16. package/dist/pricing-assignment/verify.d.ts.map +1 -0
  17. package/dist/pricing-assignment/verify.js +121 -0
  18. package/dist/pricing-assignment.d.ts +4 -275
  19. package/dist/pricing-assignment.d.ts.map +1 -1
  20. package/dist/pricing-assignment.js +4 -558
  21. package/dist/routes-admin.d.ts +2894 -0
  22. package/dist/routes-admin.d.ts.map +1 -0
  23. package/dist/routes-admin.js +2111 -0
  24. package/dist/routes-public.d.ts +9 -2
  25. package/dist/routes-public.d.ts.map +1 -1
  26. package/dist/routes-public.js +8 -0
  27. package/dist/routes.d.ts +1 -2893
  28. package/dist/routes.d.ts.map +1 -1
  29. package/dist/routes.js +1 -2110
  30. package/dist/schema-core.d.ts.map +1 -1
  31. package/dist/schema-core.js +3 -1
  32. package/dist/schema-items.d.ts +1 -1
  33. package/dist/schema-items.d.ts.map +1 -1
  34. package/dist/schema-items.js +3 -1
  35. package/dist/service-core.d.ts +6240 -0
  36. package/dist/service-core.d.ts.map +1 -0
  37. package/dist/service-core.js +4350 -0
  38. package/dist/service-public-core.d.ts +907 -0
  39. package/dist/service-public-core.d.ts.map +1 -0
  40. package/dist/service-public-core.js +1176 -0
  41. package/dist/service-public.d.ts +1 -906
  42. package/dist/service-public.d.ts.map +1 -1
  43. package/dist/service-public.js +1 -1175
  44. package/dist/service.d.ts +1 -6239
  45. package/dist/service.d.ts.map +1 -1
  46. package/dist/service.js +1 -4304
  47. package/dist/workflows/refund-booking.d.ts.map +1 -1
  48. package/dist/workflows/refund-booking.js +7 -1
  49. package/package.json +6 -6
@@ -1,558 +1,4 @@
1
- /**
2
- * Pure, transport-agnostic logic for mapping travelers onto option_units
3
- * at booking-create time. Lives in `@voyantjs/bookings` so the
4
- * booking-create dialog (preview + submit) is the only call site today,
5
- * but the server can import the same module to validate or re-resolve
6
- * submit payloads in a follow-up — that wiring is not yet in place.
7
- *
8
- * Vocabulary:
9
- * - A **pricing tier** (`unit_type='person'`) is a per-pax price band
10
- * a traveler is billed as (Adult / Child 6-12 / Infant 0-5 / …).
11
- * - An **inventory unit** (`'room' | 'vehicle' | 'seat'`) is a finite
12
- * container a traveler is placed into (one DBL room holds 2 pax).
13
- * - "Person-priced options" are options that only have pricing tiers
14
- * (no inventory). Excursions. For these, line-item quantities
15
- * **derive from the traveler list** (1 adult + 1 child + 1 infant).
16
- * - "Accommodation options" have inventory units (and usually a
17
- * paired person unit for per-pax fees). For these, line-item
18
- * quantities **stay as the operator picked them** (1 DBL room is
19
- * still 1 line, not 2).
20
- *
21
- * The `pricingUnitSource` and `inventoryUnitSource` enums on the
22
- * traveler track operator intent so the resolver knows when to
23
- * re-derive ("auto") versus respect an explicit choice ("manual" /
24
- * "none" for No room).
25
- *
26
- * No React, no DB, no HTTP — just the assignment math.
27
- *
28
- * Tracking: voyantjs/voyant#1267.
29
- */
30
- /**
31
- * Compute integer age in full years from an ISO date-of-birth string.
32
- * Returns null when the DOB is missing or unparseable.
33
- */
34
- export function computeAgeYears(dob, now = new Date()) {
35
- if (!dob)
36
- return null;
37
- const birth = new Date(dob);
38
- if (Number.isNaN(birth.getTime()))
39
- return null;
40
- let age = now.getFullYear() - birth.getFullYear();
41
- const beforeBirthday = now.getMonth() < birth.getMonth() ||
42
- (now.getMonth() === birth.getMonth() && now.getDate() < birth.getDate());
43
- if (beforeBirthday)
44
- age -= 1;
45
- return age >= 0 ? age : null;
46
- }
47
- /**
48
- * Derive the age-banded traveler category from DOB + role hint.
49
- * DOB-derived age wins; role hint is the fallback for travelers
50
- * added before the operator filled in a birthday.
51
- */
52
- export function deriveDraftPaxBand(traveler, now = new Date()) {
53
- const age = computeAgeYears(traveler.dateOfBirth, now);
54
- if (age == null) {
55
- return traveler.role === "adult" || traveler.role === "child" || traveler.role === "infant"
56
- ? traveler.role
57
- : null;
58
- }
59
- if (age < 2)
60
- return "infant";
61
- if (age < 18)
62
- return "child";
63
- return "adult";
64
- }
65
- /**
66
- * Pick the unit for a traveler pricing band. Priorities:
67
- * 1. DOB-derived age that falls into a unit's `[minAge, maxAge]`
68
- * 2. Role hint mapped to a representative age (infant→1, child→8,
69
- * adult→30) matched against bands. Works for products coded
70
- * `child_0_5` / `child_6_12` (not just literal `INFANT`/`CHILD`).
71
- * 3. Code/name matching for legacy products with no min/max set.
72
- */
73
- export function pickUnitForAge(units, age, roleHint = null) {
74
- if (units.length === 0)
75
- return undefined;
76
- const personUnits = units.filter((u) => u.unitType == null || u.unitType === "person");
77
- const pool = personUnits.length > 0 ? personUnits : units;
78
- const sorted = [...pool].sort((a, b) => (a.minAge ?? 0) - (b.minAge ?? 0));
79
- const matchByAge = (target) => sorted.find((u) => (u.minAge == null || target >= u.minAge) && (u.maxAge == null || target <= u.maxAge));
80
- if (age != null) {
81
- const match = matchByAge(age);
82
- if (match)
83
- return match;
84
- }
85
- if (roleHint) {
86
- const HINT_AGE = { adult: 30, child: 8, infant: 1 };
87
- const hintAge = HINT_AGE[roleHint];
88
- // Only consider units with at least one explicit age bound.
89
- // Without this, legacy units with null min/max (just bare
90
- // ADULT/CHILD codes) would all match every hint age and collapse
91
- // onto the first sorted entry. Code-matching below handles those.
92
- const banded = sorted.filter((u) => u.minAge != null || u.maxAge != null);
93
- const match = banded.find((u) => (u.minAge == null || hintAge >= u.minAge) && (u.maxAge == null || hintAge <= u.maxAge));
94
- if (match)
95
- return match;
96
- }
97
- const findByCode = (code) => sorted.find((u) => (u.unitCode ?? "").toUpperCase() === code) ??
98
- sorted.find((u) => new RegExp(`\\b${code}\\b`, "i").test(u.unitName));
99
- if (roleHint === "child")
100
- return findByCode("CHILD") ?? sorted[0];
101
- if (roleHint === "infant")
102
- return findByCode("INFANT") ?? sorted[0];
103
- return findByCode("ADULT") ?? sorted[sorted.length - 1] ?? sorted[0];
104
- }
105
- /**
106
- * Find the unit whose `[minAge, maxAge]` contains the DOB-derived
107
- * age. Used by the UI to pre-pick a unit when a traveler attaches.
108
- */
109
- export function matchUnitByDob(units, dob) {
110
- if (!dob)
111
- return null;
112
- const age = computeAgeYears(dob);
113
- if (age == null)
114
- return null;
115
- const personUnits = units.filter((u) => u.unitType == null || u.unitType === "person");
116
- const match = personUnits.find((u) => (u.minAge == null || age >= u.minAge) && (u.maxAge == null || age <= u.maxAge));
117
- return match?.optionUnitId ?? null;
118
- }
119
- /**
120
- * Find the unit matching a role hint when DOB is missing. Same
121
- * HINT_AGE mapping as `pickUnitForAge`. Returns null when the role
122
- * carries no age signal (e.g. `lead`).
123
- */
124
- export function matchUnitByRoleHint(units, role) {
125
- if (!role || role === "lead")
126
- return null;
127
- const HINT_AGE = {
128
- adult: 30,
129
- child: 8,
130
- infant: 1,
131
- };
132
- const hintAge = HINT_AGE[role];
133
- if (hintAge == null)
134
- return null;
135
- const banded = units.filter((u) => (u.unitType == null || u.unitType === "person") && (u.minAge != null || u.maxAge != null));
136
- const match = banded.find((u) => (u.minAge == null || hintAge >= u.minAge) && (u.maxAge == null || hintAge <= u.maxAge));
137
- return match?.optionUnitId ?? null;
138
- }
139
- function optionKey(unit) {
140
- return unit.optionId ?? unit.optionUnitId;
141
- }
142
- function isPersonUnit(unit) {
143
- return unit.unitType == null || unit.unitType === "person";
144
- }
145
- /**
146
- * Inventory units are finite containers a traveler is placed into.
147
- * Rooms (hotels), vehicles (transfers), seats (where modeled
148
- * explicitly). Distinct from pricing tiers (`person`).
149
- */
150
- function isInventoryUnit(unit) {
151
- return unit.unitType === "room" || unit.unitType === "vehicle";
152
- }
153
- function roleHintForTraveler(traveler) {
154
- return traveler.role === "adult" || traveler.role === "child" || traveler.role === "infant"
155
- ? traveler.role
156
- : null;
157
- }
158
- /**
159
- * Resolve a booking-create draft into the per-unit quantities and
160
- * per-traveler unit assignments the submit pipeline + price preview
161
- * both need. Single source of truth for traveler→unit mapping.
162
- *
163
- * Shape branching:
164
- * - **Person-priced options** (only `person` units, no `room`):
165
- * quantities are derived from traveler assignments (1 adult + 1
166
- * child + 1 infant = 3 line items, not "3 x Adult"). Auto-source
167
- * travelers are re-derived against the current option's bands.
168
- * - **Accommodation options** (any `room` unit): operator-picked
169
- * stepper quantities are preserved (1 DBL room is 1 line). Per-
170
- * traveler room assignments still update `travelerIndexesByUnitId`
171
- * so `booking_item_travelers` rows can be created.
172
- *
173
- * Respects assignment sources:
174
- * - `none` → the corresponding field stays null
175
- * - `manual` → the existing unit is kept when valid for the chosen option
176
- * - `auto` → re-derived against current options
177
- */
178
- export function resolveBookingDraft(options) {
179
- const { quantities, travelers, now = new Date() } = options;
180
- const units = [...options.units];
181
- if (units.length === 0) {
182
- return { quantities, travelers: [...travelers], travelerIndexesByUnitId: {} };
183
- }
184
- const unitsByOption = new Map();
185
- const unitById = new Map();
186
- const unitToOption = new Map();
187
- for (const unit of units) {
188
- const key = optionKey(unit);
189
- unitById.set(unit.optionUnitId, unit);
190
- unitToOption.set(unit.optionUnitId, key);
191
- const list = unitsByOption.get(key);
192
- if (list)
193
- list.push(unit);
194
- else
195
- unitsByOption.set(key, [unit]);
196
- }
197
- const primaryInventoryByOption = new Map();
198
- for (const [key, optionUnits] of unitsByOption) {
199
- const inventoryUnit = optionUnits.find(isInventoryUnit);
200
- if (inventoryUnit)
201
- primaryInventoryByOption.set(key, inventoryUnit);
202
- }
203
- // An option is "person-priced" when it has at least one person unit
204
- // and no inventory unit (room/vehicle). That's the excursion shape:
205
- // line quantities derive from travelers, not from the stepper's
206
- // primary-unit count. Multi-day packages with both a room AND a
207
- // person-typed adult fee fall outside this set — the room
208
- // quantity passes through unchanged.
209
- const personPricedOptions = new Set();
210
- for (const [key, optionUnits] of unitsByOption) {
211
- const hasPerson = optionUnits.some(isPersonUnit);
212
- const hasInventory = optionUnits.some(isInventoryUnit);
213
- if (hasPerson && !hasInventory)
214
- personPricedOptions.add(key);
215
- }
216
- const totalByOption = new Map();
217
- for (const [unitId, quantity] of Object.entries(quantities)) {
218
- if (quantity <= 0)
219
- continue;
220
- const key = unitToOption.get(unitId);
221
- if (!key)
222
- continue;
223
- totalByOption.set(key, (totalByOption.get(key) ?? 0) + quantity);
224
- }
225
- const assignedForDefaulting = new Map();
226
- for (const traveler of travelers) {
227
- const inventorySource = traveler.inventoryUnitSource ?? "auto";
228
- const pricingSource = traveler.pricingUnitSource ?? "auto";
229
- const assignedUnitId = inventorySource !== "none" && traveler.inventoryUnitId
230
- ? traveler.inventoryUnitId
231
- : pricingSource !== "none"
232
- ? traveler.pricingUnitId
233
- : null;
234
- if (!assignedUnitId)
235
- continue;
236
- const key = unitToOption.get(assignedUnitId);
237
- if (!key)
238
- continue;
239
- assignedForDefaulting.set(key, (assignedForDefaulting.get(key) ?? 0) + 1);
240
- }
241
- const optionDemand = Array.from(totalByOption.entries());
242
- const pickOptionWithDemand = () => optionDemand.find(([candidate, total]) => (assignedForDefaulting.get(candidate) ?? 0) < total)?.[0] ?? optionDemand[0]?.[0];
243
- const resolvePricingUnitForTraveler = (traveler, key) => pickUnitForAge((unitsByOption.get(key) ?? []).filter(isPersonUnit), computeAgeYears(traveler.dateOfBirth, now), roleHintForTraveler(traveler));
244
- const resolveTargetOption = (traveler) => {
245
- const inventorySource = traveler.inventoryUnitSource ?? "auto";
246
- if (inventorySource !== "none" && traveler.inventoryUnitId) {
247
- const inventoryUnit = unitById.get(traveler.inventoryUnitId);
248
- const key = unitToOption.get(traveler.inventoryUnitId);
249
- if (key && inventoryUnit && isInventoryUnit(inventoryUnit))
250
- return { key, fromDemand: false };
251
- }
252
- const pricingSource = traveler.pricingUnitSource ?? "auto";
253
- if (pricingSource !== "none" && traveler.pricingUnitId) {
254
- const pricingUnit = unitById.get(traveler.pricingUnitId);
255
- const key = unitToOption.get(traveler.pricingUnitId);
256
- if (key && pricingUnit && isPersonUnit(pricingUnit))
257
- return { key, fromDemand: false };
258
- }
259
- const key = pickOptionWithDemand();
260
- return key ? { key, fromDemand: true } : null;
261
- };
262
- const nextTravelers = travelers.map((traveler) => {
263
- const target = resolveTargetOption(traveler);
264
- const pricingSource = traveler.pricingUnitSource ?? "auto";
265
- const inventorySource = traveler.inventoryUnitSource ?? "auto";
266
- if (!target) {
267
- return {
268
- ...traveler,
269
- pricingUnitId: null,
270
- inventoryUnitId: null,
271
- pricingUnitSource: pricingSource === "none" ? "none" : "auto",
272
- inventoryUnitSource: inventorySource === "none" ? "none" : "auto",
273
- };
274
- }
275
- const targetKey = target.key;
276
- const currentPricingUnit = traveler.pricingUnitId
277
- ? unitById.get(traveler.pricingUnitId)
278
- : undefined;
279
- const currentPricingKey = traveler.pricingUnitId
280
- ? unitToOption.get(traveler.pricingUnitId)
281
- : undefined;
282
- const keepManualPricing = pricingSource === "manual" &&
283
- currentPricingUnit &&
284
- isPersonUnit(currentPricingUnit) &&
285
- currentPricingKey === targetKey;
286
- const nextPricingUnit = pricingSource === "none"
287
- ? null
288
- : keepManualPricing
289
- ? currentPricingUnit
290
- : (resolvePricingUnitForTraveler(traveler, targetKey) ?? null);
291
- const currentInventoryUnit = traveler.inventoryUnitId
292
- ? unitById.get(traveler.inventoryUnitId)
293
- : undefined;
294
- const currentInventoryKey = traveler.inventoryUnitId
295
- ? unitToOption.get(traveler.inventoryUnitId)
296
- : undefined;
297
- const keepManualInventory = inventorySource === "manual" &&
298
- currentInventoryUnit &&
299
- isInventoryUnit(currentInventoryUnit) &&
300
- currentInventoryKey === targetKey;
301
- const targetInventoryUnit = primaryInventoryByOption.get(targetKey) ?? null;
302
- const nextInventoryUnit = inventorySource === "none"
303
- ? null
304
- : keepManualInventory
305
- ? currentInventoryUnit
306
- : targetInventoryUnit;
307
- if (target.fromDemand && (nextPricingUnit || nextInventoryUnit)) {
308
- assignedForDefaulting.set(targetKey, (assignedForDefaulting.get(targetKey) ?? 0) + 1);
309
- }
310
- return {
311
- ...traveler,
312
- pricingUnitId: nextPricingUnit?.optionUnitId ?? null,
313
- inventoryUnitId: nextInventoryUnit?.optionUnitId ?? null,
314
- pricingUnitSource: pricingSource === "none" ? "none" : keepManualPricing ? "manual" : "auto",
315
- inventoryUnitSource: inventorySource === "none" ? "none" : keepManualInventory ? "manual" : "auto",
316
- };
317
- });
318
- const next = {};
319
- const travelerIndexesByUnitId = {};
320
- // Accommodation quantities pass through unchanged — 1 DBL room
321
- // stays 1 line. Person-priced quantities are rebuilt from traveler
322
- // assignments below.
323
- for (const [unitId, quantity] of Object.entries(quantities)) {
324
- if (quantity <= 0)
325
- continue;
326
- const key = unitToOption.get(unitId);
327
- if (!key || personPricedOptions.has(key))
328
- continue;
329
- const submittedUnit = unitById.get(unitId);
330
- const targetUnitId = submittedUnit && isInventoryUnit(submittedUnit)
331
- ? unitId
332
- : (primaryInventoryByOption.get(key)?.optionUnitId ?? unitId);
333
- next[targetUnitId] = (next[targetUnitId] ?? 0) + quantity;
334
- }
335
- const assignedByOption = new Map();
336
- for (const [index, traveler] of nextTravelers.entries()) {
337
- const pricingSource = traveler.pricingUnitSource ?? "auto";
338
- const inventorySource = traveler.inventoryUnitSource ?? "auto";
339
- const pricingKey = pricingSource !== "none" && traveler.pricingUnitId
340
- ? unitToOption.get(traveler.pricingUnitId)
341
- : undefined;
342
- const inventoryKey = inventorySource !== "none" && traveler.inventoryUnitId
343
- ? unitToOption.get(traveler.inventoryUnitId)
344
- : undefined;
345
- const key = inventoryKey ?? pricingKey;
346
- if (!key)
347
- continue;
348
- if (personPricedOptions.has(key)) {
349
- if (!traveler.pricingUnitId || pricingSource === "none")
350
- continue;
351
- const unitIndexes = travelerIndexesByUnitId[traveler.pricingUnitId] ?? [];
352
- unitIndexes.push(index);
353
- travelerIndexesByUnitId[traveler.pricingUnitId] = unitIndexes;
354
- next[traveler.pricingUnitId] = (next[traveler.pricingUnitId] ?? 0) + 1;
355
- assignedByOption.set(key, (assignedByOption.get(key) ?? 0) + 1);
356
- }
357
- else if (traveler.inventoryUnitId && inventorySource !== "none") {
358
- const unitIndexes = travelerIndexesByUnitId[traveler.inventoryUnitId] ?? [];
359
- unitIndexes.push(index);
360
- travelerIndexesByUnitId[traveler.inventoryUnitId] = unitIndexes;
361
- }
362
- }
363
- // Person-priced residual: operator picked N seats but only added M
364
- // travelers (M < N) → put the leftover on the option's adult unit
365
- // so the line-item total matches the stepper.
366
- for (const [key, total] of totalByOption) {
367
- if (!personPricedOptions.has(key))
368
- continue;
369
- const assigned = assignedByOption.get(key) ?? 0;
370
- const residual = Math.max(0, total - assigned);
371
- if (residual === 0)
372
- continue;
373
- const adult = pickUnitForAge(unitsByOption.get(key) ?? [], null, "adult");
374
- if (!adult)
375
- continue;
376
- next[adult.optionUnitId] = (next[adult.optionUnitId] ?? 0) + residual;
377
- }
378
- return { quantities: next, travelers: nextTravelers, travelerIndexesByUnitId };
379
- }
380
- /**
381
- * Normalize per-person extras to charged traveler quantity and
382
- * stamp traveler links + `clientLineKey` so the server can link
383
- * each extra line to the travelers it applies to via
384
- * `booking_item_travelers`.
385
- *
386
- * Per-person mode (`pricingMode === "per_person"` or
387
- * `pricedPerPerson === true`): quantity multiplied by travelerCount,
388
- * `travelerKeys` set to all travelers when stable keys are supplied;
389
- * otherwise `travelerIndexes` is set as a deprecated fallback.
390
- * Non-per-person lines pass through with `clientLineKey` only.
391
- */
392
- export function resolveBookingExtraLines(options) {
393
- const travelerIndexes = Array.from({ length: options.travelerCount }, (_, index) => index);
394
- const travelerKeys = (options.travelerKeys ?? []).filter((key) => typeof key === "string" && key.trim().length > 0);
395
- const useTravelerKeys = travelerKeys.length === options.travelerCount;
396
- return options.extraLines.map((line) => {
397
- const perPerson = line.pricingMode === "per_person" || line.pricedPerPerson === true;
398
- if (!perPerson) {
399
- return {
400
- ...line,
401
- clientLineKey: line.clientLineKey ?? `extra:${line.productExtraId}`,
402
- };
403
- }
404
- const quantity = Math.max(1, options.travelerCount) * line.quantity;
405
- return {
406
- ...line,
407
- clientLineKey: line.clientLineKey ?? `extra:${line.productExtraId}`,
408
- quantity,
409
- totalSellAmountCents: line.unitSellAmountCents == null
410
- ? line.totalSellAmountCents
411
- : line.unitSellAmountCents * quantity,
412
- ...(useTravelerKeys ? { travelerKeys } : { travelerIndexes }),
413
- };
414
- });
415
- }
416
- /**
417
- * Project a resolved draft's traveler list into the wire-format
418
- * `BookingCreateTravelerInput[]` shape the dialog submits. Derives
419
- * the `travelerCategory` from DOB / role.
420
- *
421
- * `roomUnitId` is a deprecated compatibility alias for the pricing tier
422
- * option unit. Inventory placement is expressed only by item lines and their
423
- * `travelerKeys`; the server accepts this field but does not persist it.
424
- */
425
- export function travelersToRows(value, now = new Date()) {
426
- return value.travelers.map((traveler) => ({
427
- clientTravelerKey: traveler.clientTravelerKey?.trim() || null,
428
- personId: traveler.personId,
429
- firstName: traveler.firstName.trim(),
430
- lastName: traveler.lastName.trim(),
431
- email: traveler.email.trim() || null,
432
- phone: traveler.phone.trim() || null,
433
- preferredLanguage: traveler.preferredLanguage.trim() || null,
434
- participantType: "traveler",
435
- travelerCategory: deriveDraftPaxBand(traveler, now),
436
- isPrimary: traveler.role === "lead",
437
- roomUnitId: traveler.pricingUnitSource === "none" ? null : traveler.pricingUnitId,
438
- }));
439
- }
440
- /**
441
- * Re-derive what `resolveBookingDraft` would have produced from the
442
- * submitted wire-format payload and compare against the submitted
443
- * itemLines. Used server-side as a sanity check on the client's
444
- * draft resolution. Returns `ok: true` when the submitted lines
445
- * match the resolver, else lists per-unit mismatches.
446
- *
447
- * Behavior of this helper is *non-rejecting* — callers decide
448
- * whether to log, warn, or fail. The orchestrator currently logs;
449
- * a follow-up will flip to rejection once observability confirms
450
- * no legitimate clients trip the warning.
451
- *
452
- * Notes on the reconstruction:
453
- * - The wire format doesn't carry split per-traveler assignment
454
- * fields (the join-table model encodes them through
455
- * `itemLines[].travelerKeys`), so we reconstruct the relevant
456
- * pricing or inventory unit by walking item lines and matching
457
- * them to traveler keys. Deprecated `travelerIndexes` remain a
458
- * fallback for older clients.
459
- * - DOB doesn't round-trip on the wire today either; we feed the
460
- * resolver the `travelerCategory` as a role hint so age-banded
461
- * options can still be re-derived.
462
- */
463
- export function verifyBookingDraft(input) {
464
- if (input.itemLines.length === 0 || input.units.length === 0) {
465
- return { ok: true, mismatches: [] };
466
- }
467
- // Walk the submitted itemLines to recover the per-traveler unit
468
- // assignment the client intended. Prefer stable `travelerKeys`
469
- // when present; fall back to deprecated `travelerIndexes` for
470
- // legacy clients. If neither is present, we can't verify
471
- // per-traveler assignment — just compare aggregate quantities.
472
- // Booking-create schema validation rejects unknown traveler keys
473
- // before this verifier runs.
474
- const unitById = new Map(input.units.map((unit) => [unit.optionUnitId, unit]));
475
- const travelerIndexByKey = new Map();
476
- for (const [index, traveler] of input.travelers.entries()) {
477
- const key = traveler.clientTravelerKey?.trim();
478
- if (key && !travelerIndexByKey.has(key))
479
- travelerIndexByKey.set(key, index);
480
- }
481
- const unitByTravelerIndex = new Map();
482
- for (const line of input.itemLines) {
483
- const travelerKeys = (line.travelerKeys ?? []).filter((key) => key.trim().length > 0);
484
- const keyedIndexes = travelerKeys
485
- .map((key) => travelerIndexByKey.get(key.trim()))
486
- .filter((index) => typeof index === "number");
487
- const indexes = travelerKeys.length > 0 ? keyedIndexes : (line.travelerIndexes ?? []);
488
- for (const idx of indexes) {
489
- unitByTravelerIndex.set(idx, line.optionUnitId);
490
- }
491
- }
492
- const travelerDrafts = input.travelers.map((t, i) => {
493
- const cat = t.travelerCategory;
494
- const role = t.isPrimary === true
495
- ? "lead"
496
- : cat === "child" || cat === "infant" || cat === "adult"
497
- ? cat
498
- : "adult";
499
- const assigned = unitByTravelerIndex.get(i);
500
- const assignedUnit = assigned ? unitById.get(assigned) : undefined;
501
- return {
502
- personId: null,
503
- firstName: "",
504
- lastName: "",
505
- email: "",
506
- phone: "",
507
- preferredLanguage: "",
508
- role,
509
- dateOfBirth: null,
510
- // We deliberately use `auto` (not `manual`) here even though
511
- // the client effectively committed to an assignment when it
512
- // serialized the line. The point of verification is to ask
513
- // "would a fresh resolver, given the same role/category
514
- // signals, produce these quantities?" — i.e. allow the
515
- // resolver to re-derive instead of treating the submitted
516
- // value as ground truth. Otherwise the day-tour bug shape
517
- // (3 travelers all manually frozen to Adult) would round-trip
518
- // through the verifier unchanged.
519
- pricingUnitId: assigned && assignedUnit && isPersonUnit(assignedUnit) ? assigned : null,
520
- inventoryUnitId: assigned && assignedUnit && isInventoryUnit(assignedUnit) ? assigned : null,
521
- pricingUnitSource: "auto",
522
- inventoryUnitSource: "auto",
523
- };
524
- });
525
- // Aggregate submitted quantities for resolver input. For
526
- // accommodation options the resolver passes these through
527
- // unchanged; for person-priced options it rebuilds them from
528
- // traveler assignments.
529
- const submittedQuantities = {};
530
- for (const line of input.itemLines) {
531
- submittedQuantities[line.optionUnitId] =
532
- (submittedQuantities[line.optionUnitId] ?? 0) + line.quantity;
533
- }
534
- const resolved = resolveBookingDraft({
535
- quantities: submittedQuantities,
536
- travelers: travelerDrafts,
537
- units: input.units,
538
- });
539
- const mismatches = [];
540
- const allUnitIds = new Set([
541
- ...Object.keys(submittedQuantities),
542
- ...Object.keys(resolved.quantities),
543
- ]);
544
- for (const unitId of allUnitIds) {
545
- const submitted = submittedQuantities[unitId] ?? 0;
546
- const resolvedQty = resolved.quantities[unitId] ?? 0;
547
- if (submitted === resolvedQty)
548
- continue;
549
- const kind = submitted === 0 ? "missing" : resolvedQty === 0 ? "extra" : "qty";
550
- mismatches.push({
551
- kind,
552
- optionUnitId: unitId,
553
- submittedQuantity: submitted,
554
- resolvedQuantity: resolvedQty,
555
- });
556
- }
557
- return { ok: mismatches.length === 0, mismatches };
558
- }
1
+ export * from "./pricing-assignment/age.js";
2
+ export * from "./pricing-assignment/draft.js";
3
+ export * from "./pricing-assignment/types.js";
4
+ export * from "./pricing-assignment/verify.js";