@curless/hotel-storefront 0.63.0 → 0.63.2

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.
@@ -37,8 +37,37 @@ export const TERMS_MS = 10 * 60_000;
37
37
  export const SESSION_IDLE_MS = 2 * 60 * 60_000;
38
38
  /** A payment's status is asked for at most this often per order (§12.1, 15). */
39
39
  export const STATUS_EVERY_MS = 10_000;
40
- /** The same stay for the same account asked for again within this long is the first order (a second press, a lost answer). */
41
- export const REPEAT_MS = 10 * 60_000;
40
+ /**
41
+ * An order 13 did not answer for, not found in the group's list this long
42
+ * after it was asked for - and nothing there that could be it - no longer holds
43
+ * the stay back (总线程's re-review of 0.63.1, 1). Eight times the 15 minutes
44
+ * the document's checkout holds a room unpaid.
45
+ */
46
+ export const UNCONFIRMED_GIVE_UP_MS = 2 * 60 * 60_000;
47
+ /**
48
+ * An order waiting for its payment with no time to pay by from 13: taken as
49
+ * payable this long after it was made, or after the payment status (15) last
50
+ * said it is still waiting (总线程's re-review of 0.63.1, 2).
51
+ */
52
+ export const ASSUMED_HOLD_MS = 30 * 60_000;
53
+ /** What the payment status (15) says of a payment that can no longer be made. */
54
+ export const CLOSED_PAYMENT_STATUSES = new Set([
55
+ 'EXPIRED',
56
+ 'CLOSED',
57
+ 'CANCELLED',
58
+ 'CANCELED',
59
+ 'FAILED',
60
+ 'TIMEOUT',
61
+ ]);
62
+ /** What an order row (12) says of an order that holds nothing now. */
63
+ const DEAD_ROW_STATUSES = new Set([
64
+ 'CANCELLED',
65
+ 'CANCELED',
66
+ 'FAILED',
67
+ 'REFUNDED',
68
+ 'EXPIRED',
69
+ 'CLOSED',
70
+ ]);
42
71
  /** The longest terms shown word for word - longer is refused rather than cut. */
43
72
  export const TERMS_MAX = 50_000;
44
73
  /** A guest's reason for cancelling, as the group's staff are sent it. */
@@ -49,11 +78,16 @@ const PENDING_PER_ACCOUNT = 5;
49
78
  /** The orders checked on one look at the bookings - newest first; the rest wait for the next look. */
50
79
  const CHECKED_PER_LOOK = 5;
51
80
  /**
52
- * The payment pages a guest may be sent to, until a deployment says otherwise
53
- * (总线程 11-10: the two the document's own examples name). Exact host names:
54
- * no wildcard, no other port.
81
+ * The payment pages a guest may be sent to, until a deployment says otherwise:
82
+ * the group checkout host of 13's own example (`pay.discoverasr.com`). Exact
83
+ * host names: no wildcard, no other port. ⚠️ NOT `mcp.curless.ai` (总线程's
84
+ * re-review of 0.63.1, 720f5e4f): that is our own hosted checkout, which takes
85
+ * any merchant and any amount - and it only ever appeared in the example of 8,
86
+ * which is never called here.
55
87
  */
56
- export const DEFAULT_CHECKOUT_HOSTS = ['mcp.curless.ai', 'pay.discoverasr.com'];
88
+ export const DEFAULT_CHECKOUT_HOSTS = ['pay.discoverasr.com'];
89
+ /** How long a refund's preview can be sent back (总线程's review of 0.63.0, B). */
90
+ export const REFUND_PREVIEW_MS = 10 * 60_000;
57
91
  const refusal = (code, message) => Object.assign(new Error(message), { code });
58
92
  const signInRefusal = (code, message, groups) => Object.assign(new Error(message), { code, groups: [...groups] });
59
93
  const num = (v) => {
@@ -71,9 +105,46 @@ const moneyOf = (amount, currency) => {
71
105
  return money(toMinor(a, c), c);
72
106
  };
73
107
  const same = (a, b) => !!a && !!b && a.currency === b.currency && a.minor === b.minor;
108
+ /**
109
+ * A path as its segments, the way a server reads it: empty segments (`//`)
110
+ * gone, `%2e` read as `.`, `.` and `..` resolved - or undefined for a segment
111
+ * holding an encoded or literal slash or backslash (`%2f`, `%5c`, `\`), which
112
+ * a server may read as more than one segment.
113
+ */
114
+ export const pathSegments = (path) => {
115
+ const out = [];
116
+ for (const raw of path.split('/')) {
117
+ if (!raw)
118
+ continue;
119
+ if (/%2f|%5c/i.test(raw) || raw.includes('\\'))
120
+ return undefined;
121
+ const seg = raw.replace(/%2e/gi, '.');
122
+ if (seg === '.')
123
+ continue;
124
+ if (seg === '..') {
125
+ out.pop();
126
+ continue;
127
+ }
128
+ out.push(seg);
129
+ }
130
+ return out;
131
+ };
132
+ /** One `checkoutHosts` entry: a host, and - written `host/a/b/` - the path a page must be under. */
133
+ export const checkoutEntryOf = (entry) => {
134
+ const e = entry.trim();
135
+ const slash = e.indexOf('/');
136
+ const host = (slash < 0 ? e : e.slice(0, slash)).toLowerCase();
137
+ const under = slash < 0 ? [] : (pathSegments(e.slice(slash)) ?? ['\u0000']);
138
+ return { host, under };
139
+ };
74
140
  /**
75
141
  * Where a payment page may send the guest: `https:`, an exact host on the
76
- * list, no other port, no user in it - or nothing (总线程 11-10).
142
+ * list, no other port, no user in it - or nothing (总线程 11-10). An entry
143
+ * written with a path (`mcp.curless.ai/pay/`) also holds it to that path, by
144
+ * whole segments, compared after the path is put the way a server reads it
145
+ * (`pathSegments`: no `..`, `%2e` or `//` slips past); an entry of a host alone
146
+ * takes any path on it (总线程's review of 0.63.0, 8). The page handed on is
147
+ * the one checked: its path as compared.
77
148
  */
78
149
  export const payPageOf = (raw, hosts) => {
79
150
  if (!raw)
@@ -88,8 +159,16 @@ export const payPageOf = (raw, hosts) => {
88
159
  const host = u.hostname.toLowerCase();
89
160
  if (u.protocol !== 'https:' || u.username || u.password || u.port)
90
161
  return undefined;
91
- if (!hosts.includes(host))
162
+ const segs = pathSegments(u.pathname);
163
+ if (!segs)
92
164
  return undefined;
165
+ const allowed = hosts.some((h) => {
166
+ const e = checkoutEntryOf(h);
167
+ return e.host === host && e.under.every((seg, i) => segs[i] === seg);
168
+ });
169
+ if (!allowed)
170
+ return undefined;
171
+ u.pathname = `/${segs.join('/')}${segs.length && u.pathname.endsWith('/') ? '/' : ''}`;
93
172
  return { url: u.toString(), host };
94
173
  };
95
174
  /** The host of a URL for the log - never its path or query (they carry the payment token). */
@@ -110,6 +189,36 @@ const firstText = (o, keys) => {
110
189
  }
111
190
  return undefined;
112
191
  };
192
+ /**
193
+ * The statuses a cancellation (9 `booking/cancel`, 14 `checkout/cancel`) is
194
+ * taken as DONE by - exactly these, case aside (总线程's review of 0.63.0, 4):
195
+ * the document's own words ("CANCELLED"; 14's "CANCELLED", "SUCCESS") and
196
+ * their spelling variants. ⚠️ NOT A PATTERN: /CANCEL|CLOSED|SUCCESS/ took
197
+ * CANCEL_FAILED and NOT_CANCELLABLE as done. Anything else is not done; no
198
+ * status at all is not known (`cancelOutcome`).
199
+ */
200
+ export const CANCELLED_STATUSES = new Set([
201
+ 'CANCELLED',
202
+ 'CANCELED',
203
+ 'CLOSED',
204
+ 'SUCCESS',
205
+ ]);
206
+ /**
207
+ * What a cancellation's answer says: `done` - `success` not false and a status
208
+ * in `CANCELLED_STATUSES`; `refused` - `success` false, or another status;
209
+ * `unknown` - no status said (an empty answer): nothing is changed on our side,
210
+ * and the guest is told so.
211
+ */
212
+ export const cancelOutcome = (out) => {
213
+ if (out?.success === false)
214
+ return 'refused';
215
+ const s = String(out?.status ?? '')
216
+ .trim()
217
+ .toUpperCase();
218
+ if (!s)
219
+ return 'unknown';
220
+ return CANCELLED_STATUSES.has(s) ? 'done' : 'refused';
221
+ };
113
222
  const TERMS_TEXT_KEYS = ['terms', 'terms_text', 'termsText', 'terms_content', 'termsContent'];
114
223
  const TERMS_TOKEN_KEYS = ['terms_token', 'termsToken'];
115
224
  const isCode = (err, code) => err instanceof OtalessError && !(err instanceof OtalessBusy) && err.backendCode === code;
@@ -182,6 +291,10 @@ export const createOtalessBookings = (deps) => {
182
291
  ? [orders.get(id)]
183
292
  : [...orders.values()].filter((o) => !!o.code && o.code.toLowerCase() === low);
184
293
  for (const r of named) {
294
+ // ⚠️ LET GO AT ONCE, NOT THE GUEST'S TO ACT ON (总线程's review of 0.63.0, 7):
295
+ // one that could not be undone is a person's.
296
+ if (r.released)
297
+ continue;
185
298
  const acct = accountFor(who, r.group);
186
299
  if (acct && acct.owner === r.owner)
187
300
  return { r, acct };
@@ -297,8 +410,21 @@ export const createOtalessBookings = (deps) => {
297
410
  return signInRefusal('signed-out', `The guest's sign-in at ${name} is over, so nothing was done - ask them to sign in to ${name} through their ${deps.brand} account again.`, [acct.group]);
298
411
  };
299
412
  // ── an order, as a booking ────────────────────────────────────────────────
413
+ /** One of the amounts the order asked: 13's, the quote's, or the quote's USD. */
414
+ const asked = (m, r) => same(m, r.charged) || same(m, r.quoted) || same(m, r.quotedUsd);
415
+ /** What was paid - as the group reported it, else what the order asked (总线程's re-review of 0.63.1, 3). */
416
+ const paidOf = (r) => r.paidAmount ?? r.charged ?? r.quoted;
417
+ /**
418
+ * Until when an order waiting for its payment may still be paid: 13's time,
419
+ * else `ASSUMED_HOLD_MS` after it was made or last said waiting (总线程's
420
+ * re-review of 0.63.1, 2).
421
+ */
422
+ const payableUntil = (r) => r.payBy ? Date.parse(r.payBy) : Date.parse(r.pendingSeenAt ?? r.createdAt) + ASSUMED_HOLD_MS;
300
423
  const paymentOf = (r) => {
301
- const amount = r.charged ?? r.quoted;
424
+ const amount = paidOf(r);
425
+ // Said paid at another amount: nothing about its money is said but by a person.
426
+ if (r.needsPerson)
427
+ return undefined;
302
428
  if (r.refund)
303
429
  return {
304
430
  method: 'card',
@@ -311,7 +437,8 @@ export const createOtalessBookings = (deps) => {
311
437
  if (r.paid)
312
438
  return { method: 'card', amount, status: 'paid' };
313
439
  if (r.status === 'awaiting-payment') {
314
- const url = payLinks.get(r.id);
440
+ // ⚠️ NO LINK PAST ITS TIME: a page that cannot be paid any more is not handed on.
441
+ const url = now() < payableUntil(r) ? payLinks.get(r.id) : undefined;
315
442
  return {
316
443
  method: 'card',
317
444
  amount,
@@ -342,11 +469,12 @@ export const createOtalessBookings = (deps) => {
342
469
  day: r.stay.checkIn,
343
470
  };
344
471
  const payment = paymentOf(r);
345
- return {
472
+ const booking = {
346
473
  id: r.id,
347
474
  supplier: r.group,
348
475
  confirmationCode: r.code || r.id,
349
- status: r.status,
476
+ // A person is looking at its payment: not known, as the type says it.
477
+ status: r.needsPerson ? 'unconfirmed' : r.status,
350
478
  createdAt: r.createdAt,
351
479
  hotelId: r.hotelId,
352
480
  hotelName: r.hotelName,
@@ -364,6 +492,8 @@ export const createOtalessBookings = (deps) => {
364
492
  },
365
493
  ...(r.cancelledAt ? { cancelledAt: r.cancelledAt } : {}),
366
494
  };
495
+ // Beside the type, for the words (0.63.2): why it is not known.
496
+ return Object.assign(booking, r.unverifiable ? { unverifiable: true } : {}, r.needsPerson ? { needsPerson: r.needsPerson } : {});
367
497
  };
368
498
  const failedStay = (a, why, code) => ({
369
499
  hotelId: a.hotel.id,
@@ -422,7 +552,8 @@ export const createOtalessBookings = (deps) => {
422
552
  providerCode: a.group,
423
553
  reason: 'price or payment page not as quoted',
424
554
  }, cred, deps.callerOf(a.who)));
425
- if (done?.success === false)
555
+ // Not said to be done - refused, or not known: a person, as any failure here.
556
+ if (cancelOutcome(done) !== 'done')
426
557
  throw new Error('not cancelled');
427
558
  r.status = 'cancelled';
428
559
  r.cancelledAt = iso();
@@ -587,6 +718,25 @@ export const createOtalessBookings = (deps) => {
587
718
  }
588
719
  return settle(a, w);
589
720
  };
721
+ /**
722
+ * An order row that could be an order 13 did not answer for: of the group,
723
+ * for those nights, not one of ours, and holding something (not cancelled,
724
+ * failed, refunded or closed).
725
+ */
726
+ const couldBe = (row, group, stay) => {
727
+ const id = text(row.unifiedOrderId);
728
+ if (id && orders.has(id))
729
+ return false;
730
+ const code = text(row.providerCode)?.toLowerCase();
731
+ if (code && code !== group)
732
+ return false;
733
+ const dates = String(row.dates ?? '');
734
+ if (!dates.includes(stay.checkIn) || !dates.includes(stay.checkOut))
735
+ return false;
736
+ return !DEAD_ROW_STATUSES.has(String(row.status ?? '')
737
+ .trim()
738
+ .toUpperCase());
739
+ };
590
740
  const requestBooking = async (trip, guest, who) => {
591
741
  // ⚠️ SIGNED IN AT EVERY GROUP OF THE TRIP, OR NOTHING IS SENT (robin 11-10:
592
742
  // one sign-in per group, the backend's own) - the whole trip is refused
@@ -659,16 +809,66 @@ export const createOtalessBookings = (deps) => {
659
809
  failed.push({ ...failedStay(label, signInFirst([group]).message), groups: [group] });
660
810
  continue;
661
811
  }
662
- // A second press, a lost answer: the order already made for this stay.
663
812
  const lockKey = `${acct.owner}|${hotel.id}|${line.roomRef}|${stay.checkIn}|${stay.checkOut}|${rooms}`;
664
- const before = [...orders.values()].find((o) => o.owner === acct.owner &&
813
+ const sameStay = (o) => o.owner === acct.owner &&
814
+ !o.released &&
665
815
  o.hotelId === hotel.id &&
666
816
  o.roomId === line.roomRef &&
667
817
  o.stay.checkIn === stay.checkIn &&
668
818
  o.stay.checkOut === stay.checkOut &&
669
- o.rooms === rooms &&
670
- (o.status === 'awaiting-payment' || o.status === 'unconfirmed') &&
671
- now() - Date.parse(o.createdAt) < REPEAT_MS);
819
+ o.rooms === rooms;
820
+ // ⚠️ AN EARLIER ORDER OF THIS STAY THAT MAY HAVE BEEN MADE IS LOOKED FOR
821
+ // FIRST, HOWEVER OLD (总线程's review of 0.63.0, 5): the group's order list
822
+ // (12) is read; not found there - or not readable - nothing new is sent.
823
+ const name = deps.groupOf(group).name;
824
+ // Said paid at another amount: a person's - nothing new beside it.
825
+ if ([...orders.values()].some((o) => sameStay(o) && o.needsPerson)) {
826
+ failed.push(failedStay(label, `An earlier booking of this stay needs a person to check its payment with ${name}, so nothing new was booked.`,
827
+ // For the card to say in the guest's language (酒店平台 0.63.2, `NoRoomsCode`).
828
+ 'earlier-needs-person'));
829
+ continue;
830
+ }
831
+ const unknown = [...orders.values()].filter((o) => sameStay(o) && o.status === 'unconfirmed' && !o.unverifiable);
832
+ if (unknown.length) {
833
+ const rows = await lookAtOrders(acct, who, group, unknown);
834
+ const still = unknown.filter((o) => o.status === 'unconfirmed');
835
+ // ⚠️ THE WAY OUT (总线程's re-review of 0.63.1, 1): long enough after it
836
+ // was asked for - past any hold on an unpaid room - and with nothing in
837
+ // the group's list that could be it, the stay is no longer held back.
838
+ // The guest is told first, as it is; asked again, a new booking is made.
839
+ // (Not by the payment status, 15: an order 13 never named has no id to
840
+ // ask it by - its list, 12, is all there is.)
841
+ if (rows &&
842
+ still.length &&
843
+ still.every((o) => now() - Date.parse(o.createdAt) >= UNCONFIRMED_GIVE_UP_MS) &&
844
+ !rows.some((row) => couldBe(row, group, stay))) {
845
+ for (const o of still) {
846
+ o.unverifiable = true;
847
+ put(o);
848
+ }
849
+ log(`[otaless] ${still.length} order(s) 13 did not answer for at ${group} could not be verified - the stay is no longer held back`);
850
+ failed.push(failedStay(label, `The earlier booking of this stay could not be confirmed with ${name}: it may have been made, so the guest should check with ${name} before booking it again. Nothing new was booked this time - asked again, a new booking is made.`, 'earlier-unconfirmed'));
851
+ continue;
852
+ }
853
+ if (!rows || still.length) {
854
+ failed.push(failedStay(label, `An earlier booking of this stay is still being looked into with ${name} - whether it was made is not known yet, so nothing new was booked. Look at the bookings again in a few minutes.`));
855
+ continue;
856
+ }
857
+ }
858
+ // A second press, a lost answer, an order found in the list: the order
859
+ // already made for this stay, while it may still be paid. ⚠️ WITH NO TIME
860
+ // TO PAY BY FROM 13, THE PAYMENT STATUS (15) IS ASKED FIRST (总线程's
861
+ // re-review of 0.63.1, 2): closed, it lapses and its link is not handed
862
+ // on again; not known, it is held to `ASSUMED_HOLD_MS`.
863
+ let before;
864
+ for (const o of [...orders.values()].filter((x) => sameStay(x) && x.status === 'awaiting-payment' && !x.needsPerson)) {
865
+ if (!o.payBy)
866
+ await lookAtPayment(acct, who, o, true);
867
+ if (o.status === 'awaiting-payment' && !o.needsPerson && now() < payableUntil(o)) {
868
+ before = o;
869
+ break;
870
+ }
871
+ }
672
872
  if (before) {
673
873
  booked.push(toBooking(before));
674
874
  reused.push(before.id);
@@ -856,50 +1056,83 @@ export const createOtalessBookings = (deps) => {
856
1056
  return { status: 'failed' };
857
1057
  return {};
858
1058
  };
859
- /** One order's payment, by 15 - at most every `STATUS_EVERY_MS`. */
860
- const lookAtPayment = async (acct, who, r) => {
861
- if (r.status !== 'awaiting-payment' || r.id.startsWith('pending:'))
862
- return;
1059
+ /**
1060
+ * One order's payment, by 15 - at most every `STATUS_EVERY_MS`, or now
1061
+ * (`force`). What it came to: `paid`; `closed` - it can no longer be paid
1062
+ * (the payment status says so, or its time is past): the order lapses and its
1063
+ * link goes; `pending` - still waiting to be paid; `unknown` - not asked, not
1064
+ * answered, or answered with nothing to go by.
1065
+ *
1066
+ * ⚠️ PAID AT ANOTHER AMOUNT IS NOT PAID (总线程's re-review of 0.63.1, 3): a
1067
+ * person looks (`needsPerson`), and no link is handed on.
1068
+ */
1069
+ const lookAtPayment = async (acct, who, r, force = false) => {
1070
+ if (r.status !== 'awaiting-payment' || r.id.startsWith('pending:') || r.needsPerson)
1071
+ return 'unknown';
863
1072
  const last = checkedAt.get(r.id) ?? 0;
864
- if (now() - last < STATUS_EVERY_MS)
865
- return;
1073
+ if (!force && now() - last < STATUS_EVERY_MS)
1074
+ return 'unknown';
866
1075
  checkedAt.set(r.id, now());
867
1076
  try {
868
1077
  const s = await withSession(acct, who, (cred) => client.paymentStatus({ unifiedOrderId: r.id, providerCode: r.group }, cred, deps.callerOf(who)));
869
- const paid = s?.paid === true || String(s?.status ?? '').toUpperCase() === 'PAID';
1078
+ const said = String(s?.status ?? '')
1079
+ .trim()
1080
+ .toUpperCase();
1081
+ const paid = s?.paid === true || said === 'PAID';
870
1082
  const amount = moneyOf(s?.amount, s?.currency);
871
- if (paid &&
872
- amount &&
873
- !(same(amount, r.charged) || same(amount, r.quoted) || same(amount, r.quotedUsd))) {
874
- log(`[otaless] NEEDS A PERSON: ${forTheLog(r.id)} at ${r.group} paid ${amount.currency} ${amount.minor}, not what was asked - status left as it was`);
875
- return;
876
- }
877
1083
  if (paid) {
1084
+ if (amount && !asked(amount, r)) {
1085
+ r.needsPerson = 'paid-amount';
1086
+ payLinks.delete(r.id);
1087
+ put(r);
1088
+ log(`[otaless] NEEDS A PERSON: ${forTheLog(r.id)} at ${r.group} paid ${amount.currency} ${amount.minor}, not what was asked - not taken as paid`);
1089
+ return 'unknown';
1090
+ }
878
1091
  r.paid = true;
879
1092
  r.status = 'confirmed';
1093
+ // ⚠️ WHAT WAS PAID, AS SAID: what a refund previews.
1094
+ if (amount)
1095
+ r.paidAmount = amount;
880
1096
  payLinks.delete(r.id);
881
1097
  put(r);
1098
+ return 'paid';
882
1099
  }
883
- else if (r.payBy && now() > Date.parse(r.payBy) && s?.pollAgain !== true) {
1100
+ if (s?.pollAgain !== true &&
1101
+ (CLOSED_PAYMENT_STATUSES.has(said) || (!!r.payBy && now() > Date.parse(r.payBy)))) {
884
1102
  r.status = 'expired';
885
1103
  payLinks.delete(r.id);
886
1104
  put(r);
1105
+ return 'closed';
887
1106
  }
1107
+ if (s?.pollAgain === true || said === 'PENDING' || said === 'PENDING_PAYMENT') {
1108
+ r.pendingSeenAt = iso();
1109
+ put(r);
1110
+ return 'pending';
1111
+ }
1112
+ return 'unknown';
888
1113
  }
889
1114
  catch (err) {
890
- if (err instanceof Error && 'code' in err)
891
- return; // our own refusal: the list still answers
892
- log(`[otaless] payment status of an order at ${r.group} not read: ${err instanceof Error ? err.name : 'error'}`);
1115
+ if (!(err instanceof Error && 'code' in err))
1116
+ log(`[otaless] payment status of an order at ${r.group} not read: ${err instanceof Error ? err.name : 'error'}`);
1117
+ return 'unknown';
893
1118
  }
894
1119
  };
895
- /** The group's order list (12): statuses, a lost payment link, and an order 13 did not answer for. */
1120
+ /**
1121
+ * The group's order list (12): statuses, a lost payment link, and an order
1122
+ * 13 did not answer for. The rows when the list was read - undefined when it
1123
+ * could not be (and nothing changed).
1124
+ *
1125
+ * ⚠️ WHAT IS LET GO OR STILL BEING LOOKED FOR IS NOT TOUCHED (总线程's review
1126
+ * of 0.63.0, 3 and 7): a released order gets no status and no payment link
1127
+ * back; an unconfirmed one moves only by being claimed, below.
1128
+ */
896
1129
  const lookAtOrders = async (acct, who, group, mine) => {
897
1130
  let rows;
898
1131
  try {
899
1132
  rows = await withSession(acct, who, (cred) => client.orders({ providerCode: group }, cred, deps.callerOf(who)));
900
1133
  }
901
1134
  catch {
902
- return;
1135
+ return undefined;
903
1136
  }
904
1137
  const known = new Set(orders.keys());
905
1138
  for (const row of rows) {
@@ -907,8 +1140,23 @@ export const createOtalessBookings = (deps) => {
907
1140
  if (!id)
908
1141
  continue;
909
1142
  const r = orders.get(id);
910
- if (r && r.owner === acct.owner) {
1143
+ if (r) {
1144
+ if (r.owner !== acct.owner || r.released || r.status === 'unconfirmed' || r.needsPerson)
1145
+ continue;
911
1146
  const s = statusOfRow(row.status);
1147
+ // ⚠️ "PAID" AT ANOTHER AMOUNT - OR NONE - IS NOT PAID (总线程's re-review
1148
+ // of 0.63.1, 3): a person looks; nothing else of the row is taken.
1149
+ if (s.paid && !r.paid) {
1150
+ const amount = moneyOf(row.totalAmount, row.currency);
1151
+ if (!amount || !asked(amount, r)) {
1152
+ r.needsPerson = 'paid-amount';
1153
+ payLinks.delete(r.id);
1154
+ put(r);
1155
+ log(`[otaless] NEEDS A PERSON: ${forTheLog(r.id)} at ${group} is listed PAID at ${amount ? `${amount.currency} ${amount.minor}` : 'no amount'}, not what was asked - not taken as paid`);
1156
+ continue;
1157
+ }
1158
+ r.paidAmount ??= amount;
1159
+ }
912
1160
  // ⚠️ AN UNPAID ORDER STAYS WAITING ("CONFIRMED" is not paid, questions
913
1161
  // #53): only PAID, a cancellation or a failure moves it.
914
1162
  if (s.status &&
@@ -932,11 +1180,24 @@ export const createOtalessBookings = (deps) => {
932
1180
  }
933
1181
  if (known.has(id))
934
1182
  continue;
935
- // An order 13 did not answer for: the one unclaimed row of the same group and nights.
1183
+ // ── an order 13 did not answer for (总线程's review of 0.63.0, 3) ──
1184
+ // ⚠️ THE SAME HOTEL, THE SAME ROOM, THE SAME NIGHTS - BY ID: the group and
1185
+ // the nights alone would claim another stay of the guest's. The document's
1186
+ // order rows carry no hotel or room id; until the backend sends them
1187
+ // (questions, 11-10 late), no row is claimed and the stay stays "being
1188
+ // looked into" - for a person.
1189
+ const hotelId = text(row.unifiedHotelId) ?? text(row.hotelId);
1190
+ const roomId = text(row.unifiedRoomId) ?? text(row.roomId);
936
1191
  const dates = String(row.dates ?? '');
937
1192
  const waiting = mine.filter((o) => o.status === 'unconfirmed' &&
938
1193
  o.id.startsWith('pending:') &&
1194
+ !o.released &&
1195
+ o.owner === acct.owner &&
939
1196
  o.group === group &&
1197
+ !!hotelId &&
1198
+ !!roomId &&
1199
+ o.hotelId === hotelId &&
1200
+ o.roomId === roomId &&
940
1201
  dates.includes(o.stay.checkIn) &&
941
1202
  dates.includes(o.stay.checkOut));
942
1203
  if (waiting.length !== 1)
@@ -945,33 +1206,30 @@ export const createOtalessBookings = (deps) => {
945
1206
  if (!o)
946
1207
  continue;
947
1208
  const charged = moneyOf(row.totalAmount, row.currency);
1209
+ // ⚠️ AT ANOTHER AMOUNT, NOT CLAIMED: the record keeps its own id and stays
1210
+ // unconfirmed - for a person.
1211
+ if (!charged || !(same(charged, o.quoted) || same(charged, o.quotedUsd))) {
1212
+ log(`[otaless] NEEDS A PERSON: an order 13 did not answer for was found at ${group} at another amount - not claimed`);
1213
+ continue;
1214
+ }
1215
+ const s = statusOfRow(row.status);
1216
+ const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
948
1217
  orders.delete(o.id);
949
1218
  o.id = id;
950
1219
  o.code = text(row.originalOrderId) ?? '';
951
- if (charged)
952
- o.charged = charged;
953
- const s = statusOfRow(row.status);
954
- if (!charged || !(same(charged, o.quoted) || same(charged, o.quotedUsd))) {
955
- // Found, at another amount: kept unconfirmed for a person - never handed on.
956
- log(`[otaless] NEEDS A PERSON: an order 13 did not answer for was found at ${group} at another amount`);
1220
+ o.charged = charged;
1221
+ // ⚠️ PAID IS ONLY "PAID": "CONFIRMED" unpaid is still waiting for its payment.
1222
+ if (s.paid) {
1223
+ o.status = 'confirmed';
1224
+ o.paid = true;
1225
+ o.paidAmount = charged;
957
1226
  }
958
- else if (s.status) {
959
- o.status =
960
- s.status === 'confirmed' && !s.paid && text(row.checkoutUrl ?? undefined)
961
- ? 'awaiting-payment'
962
- : s.status;
963
- if (s.paid)
964
- o.paid = true;
965
- const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
966
- if (ok && o.status === 'awaiting-payment') {
967
- o.payHost = ok.host;
968
- payLinks.set(id, ok.url);
969
- }
1227
+ else if (s.status === 'cancelled' || s.status === 'failed') {
1228
+ o.status = s.status;
970
1229
  }
971
- else if (text(row.checkoutUrl ?? undefined)) {
972
- const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
1230
+ else {
1231
+ o.status = 'awaiting-payment';
973
1232
  if (ok) {
974
- o.status = 'awaiting-payment';
975
1233
  o.payHost = ok.host;
976
1234
  payLinks.set(id, ok.url);
977
1235
  }
@@ -979,6 +1237,7 @@ export const createOtalessBookings = (deps) => {
979
1237
  known.add(id);
980
1238
  put(o);
981
1239
  }
1240
+ return rows;
982
1241
  };
983
1242
  /** The guest's orders brought up to date, each by their sign-in at its group (`signed`). */
984
1243
  const refresh = async (who, mine, signed) => {
@@ -1033,7 +1292,7 @@ export const createOtalessBookings = (deps) => {
1033
1292
  return null;
1034
1293
  const { r, acct } = own;
1035
1294
  await refresh(who, [r], new Map([[r.group, acct]]));
1036
- const amount = r.charged ?? r.quoted;
1295
+ const amount = paidOf(r);
1037
1296
  const base = { bookingId: r.id, supplier: r.group, confirmationCode: r.code || r.id };
1038
1297
  const g = deps.groupOf(r.group).name;
1039
1298
  if (r.status === 'cancelled' || r.status === 'expired' || r.status === 'failed')
@@ -1097,8 +1356,12 @@ export const createOtalessBookings = (deps) => {
1097
1356
  const out = await withSession(acct, who, (cred) => unpaid
1098
1357
  ? client.cancelCheckout({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who))
1099
1358
  : client.cancelBooking({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who)));
1100
- const s = String(out?.status ?? '').toUpperCase();
1101
- if (out?.success === false || (s && !/CANCEL|CLOSED|SUCCESS/.test(s)))
1359
+ const said = cancelOutcome(out);
1360
+ // ⚠️ NOTHING SAID IS NOT DONE (总线程's review of 0.63.0, 4): our record
1361
+ // stays as it was, and the guest is told it is not known yet.
1362
+ if (said === 'unknown')
1363
+ throw refusal('cancel-unknown', `${g} answered without saying whether it cancelled it, so nothing is changed here - look at the bookings again in a few minutes before asking again.`);
1364
+ if (said === 'refused')
1102
1365
  throw refusal('not-cancelled', `${g} did not cancel it - it stands as it was.`);
1103
1366
  r.status = 'cancelled';
1104
1367
  r.cancelledAt = iso();
@@ -1109,8 +1372,46 @@ export const createOtalessBookings = (deps) => {
1109
1372
  put(r);
1110
1373
  return toBooking(r);
1111
1374
  };
1112
- // ── refund, add-ons (9.1, 10, 11) ─────────────────────────────────────────
1113
- const refund = async (ref, who, reason) => {
1375
+ // ── refund: a preview, then the refund it previewed (9.1; 总线程's review of 0.63.0, B) ──
1376
+ /** Refund previews waiting to be sent, by their `preview`. */
1377
+ const refundPreviews = new Map();
1378
+ const refundable = (r) => {
1379
+ if (!r.paid)
1380
+ throw refusal('not-paid', 'Nothing was paid for this booking, so there is nothing to refund.');
1381
+ };
1382
+ const previewRefund = async (ref, who) => {
1383
+ const own = ownOrder(ref, who);
1384
+ if (!own)
1385
+ return null;
1386
+ const { r } = own;
1387
+ if (r.refund)
1388
+ throw refusal('refunded', 'A refund was already asked for this booking.');
1389
+ refundable(r);
1390
+ for (const [k, v] of refundPreviews)
1391
+ if (now() - v.at > REFUND_PREVIEW_MS || v.orderId === r.id)
1392
+ refundPreviews.delete(k);
1393
+ while (refundPreviews.size >= PENDING_MAX) {
1394
+ const first = refundPreviews.keys().next().value;
1395
+ if (first === undefined)
1396
+ break;
1397
+ refundPreviews.delete(first);
1398
+ }
1399
+ const amount = paidOf(r);
1400
+ const preview = randomBytes(18).toString('base64url');
1401
+ refundPreviews.set(preview, { orderId: r.id, owner: r.owner, amount, at: now() });
1402
+ return {
1403
+ preview,
1404
+ bookingId: r.id,
1405
+ confirmationCode: r.code || r.id,
1406
+ supplier: r.group,
1407
+ amount,
1408
+ fromPayment: !!r.paidAmount,
1409
+ groupDecides: true,
1410
+ terms: r.terms ?? '',
1411
+ until: iso(now() + REFUND_PREVIEW_MS),
1412
+ };
1413
+ };
1414
+ const refund = async (ref, who, reason, preview) => {
1114
1415
  const own = ownOrder(ref, who);
1115
1416
  if (!own)
1116
1417
  return null;
@@ -1118,8 +1419,18 @@ export const createOtalessBookings = (deps) => {
1118
1419
  if (r.refund)
1119
1420
  return toBooking(r);
1120
1421
  const g = deps.groupOf(r.group).name;
1121
- if (!r.paid)
1122
- throw refusal('not-paid', 'Nothing was paid for this booking, so there is nothing to refund.');
1422
+ refundable(r);
1423
+ // ⚠️ THE PREVIEW OF THIS VERY BOOKING, FOR THIS GUEST, AT THIS AMOUNT, ONCE
1424
+ // (总线程's review of 0.63.0, B): nothing is sent without it.
1425
+ const shown = preview ? refundPreviews.get(preview) : undefined;
1426
+ if (preview)
1427
+ refundPreviews.delete(preview);
1428
+ if (!shown ||
1429
+ now() - shown.at > REFUND_PREVIEW_MS ||
1430
+ shown.orderId !== r.id ||
1431
+ shown.owner !== r.owner ||
1432
+ !same(shown.amount, paidOf(r)))
1433
+ throw refusal('refund-preview', 'Nothing was asked: a refund is asked only after the guest was shown what it asks for (the refund preview of this booking) - show it to them again first.');
1123
1434
  const why = cleanReason(reason);
1124
1435
  // ⚠️ ALL OF IT, NEVER A PART (`amountUsd` is never sent), and no
1125
1436
  // `sessionToken` (questions #53): the backend takes the guest from the sign-in.
@@ -1147,7 +1458,11 @@ export const createOtalessBookings = (deps) => {
1147
1458
  per_night: 'night',
1148
1459
  per_guest_per_day: 'person-night',
1149
1460
  };
1461
+ /** Add-ons after booking, off unless the deployment turns them on (总线程's review of 0.63.0, A). */
1462
+ const addonsOff = () => refusal('addons-off', 'Nothing can be added to a booking here.');
1150
1463
  const addons = async (ref, who) => {
1464
+ if (!deps.addonsOn)
1465
+ throw addonsOff();
1151
1466
  const own = ownOrder(ref, who);
1152
1467
  if (!own?.r.code)
1153
1468
  return null;
@@ -1174,6 +1489,8 @@ export const createOtalessBookings = (deps) => {
1174
1489
  return out;
1175
1490
  };
1176
1491
  const bookAddon = async (ref, extraId, details, who) => {
1492
+ if (!deps.addonsOn)
1493
+ throw addonsOff();
1177
1494
  const own = ownOrder(ref, who);
1178
1495
  if (!own?.r.code)
1179
1496
  return null;
@@ -1216,6 +1533,7 @@ export const createOtalessBookings = (deps) => {
1216
1533
  return found ? view(found.p) : undefined;
1217
1534
  },
1218
1535
  acceptTerms,
1536
+ previewRefund,
1219
1537
  refund,
1220
1538
  addons,
1221
1539
  bookAddon,