@curless/hotel-storefront 0.63.0 → 0.63.1

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.
@@ -54,6 +54,8 @@ const CHECKED_PER_LOOK = 5;
54
54
  * no wildcard, no other port.
55
55
  */
56
56
  export const DEFAULT_CHECKOUT_HOSTS = ['mcp.curless.ai', 'pay.discoverasr.com'];
57
+ /** How long a refund's preview can be sent back (总线程's review of 0.63.0, B). */
58
+ export const REFUND_PREVIEW_MS = 10 * 60_000;
57
59
  const refusal = (code, message) => Object.assign(new Error(message), { code });
58
60
  const signInRefusal = (code, message, groups) => Object.assign(new Error(message), { code, groups: [...groups] });
59
61
  const num = (v) => {
@@ -71,9 +73,46 @@ const moneyOf = (amount, currency) => {
71
73
  return money(toMinor(a, c), c);
72
74
  };
73
75
  const same = (a, b) => !!a && !!b && a.currency === b.currency && a.minor === b.minor;
76
+ /**
77
+ * A path as its segments, the way a server reads it: empty segments (`//`)
78
+ * gone, `%2e` read as `.`, `.` and `..` resolved - or undefined for a segment
79
+ * holding an encoded or literal slash or backslash (`%2f`, `%5c`, `\`), which
80
+ * a server may read as more than one segment.
81
+ */
82
+ export const pathSegments = (path) => {
83
+ const out = [];
84
+ for (const raw of path.split('/')) {
85
+ if (!raw)
86
+ continue;
87
+ if (/%2f|%5c/i.test(raw) || raw.includes('\\'))
88
+ return undefined;
89
+ const seg = raw.replace(/%2e/gi, '.');
90
+ if (seg === '.')
91
+ continue;
92
+ if (seg === '..') {
93
+ out.pop();
94
+ continue;
95
+ }
96
+ out.push(seg);
97
+ }
98
+ return out;
99
+ };
100
+ /** One `checkoutHosts` entry: a host, and - written `host/a/b/` - the path a page must be under. */
101
+ export const checkoutEntryOf = (entry) => {
102
+ const e = entry.trim();
103
+ const slash = e.indexOf('/');
104
+ const host = (slash < 0 ? e : e.slice(0, slash)).toLowerCase();
105
+ const under = slash < 0 ? [] : (pathSegments(e.slice(slash)) ?? ['\u0000']);
106
+ return { host, under };
107
+ };
74
108
  /**
75
109
  * 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).
110
+ * list, no other port, no user in it - or nothing (总线程 11-10). An entry
111
+ * written with a path (`mcp.curless.ai/pay/`) also holds it to that path, by
112
+ * whole segments, compared after the path is put the way a server reads it
113
+ * (`pathSegments`: no `..`, `%2e` or `//` slips past); an entry of a host alone
114
+ * takes any path on it (总线程's review of 0.63.0, 8). The page handed on is
115
+ * the one checked: its path as compared.
77
116
  */
78
117
  export const payPageOf = (raw, hosts) => {
79
118
  if (!raw)
@@ -88,8 +127,16 @@ export const payPageOf = (raw, hosts) => {
88
127
  const host = u.hostname.toLowerCase();
89
128
  if (u.protocol !== 'https:' || u.username || u.password || u.port)
90
129
  return undefined;
91
- if (!hosts.includes(host))
130
+ const segs = pathSegments(u.pathname);
131
+ if (!segs)
92
132
  return undefined;
133
+ const allowed = hosts.some((h) => {
134
+ const e = checkoutEntryOf(h);
135
+ return e.host === host && e.under.every((seg, i) => segs[i] === seg);
136
+ });
137
+ if (!allowed)
138
+ return undefined;
139
+ u.pathname = `/${segs.join('/')}${segs.length && u.pathname.endsWith('/') ? '/' : ''}`;
93
140
  return { url: u.toString(), host };
94
141
  };
95
142
  /** The host of a URL for the log - never its path or query (they carry the payment token). */
@@ -110,6 +157,36 @@ const firstText = (o, keys) => {
110
157
  }
111
158
  return undefined;
112
159
  };
160
+ /**
161
+ * The statuses a cancellation (9 `booking/cancel`, 14 `checkout/cancel`) is
162
+ * taken as DONE by - exactly these, case aside (总线程's review of 0.63.0, 4):
163
+ * the document's own words ("CANCELLED"; 14's "CANCELLED", "SUCCESS") and
164
+ * their spelling variants. ⚠️ NOT A PATTERN: /CANCEL|CLOSED|SUCCESS/ took
165
+ * CANCEL_FAILED and NOT_CANCELLABLE as done. Anything else is not done; no
166
+ * status at all is not known (`cancelOutcome`).
167
+ */
168
+ export const CANCELLED_STATUSES = new Set([
169
+ 'CANCELLED',
170
+ 'CANCELED',
171
+ 'CLOSED',
172
+ 'SUCCESS',
173
+ ]);
174
+ /**
175
+ * What a cancellation's answer says: `done` - `success` not false and a status
176
+ * in `CANCELLED_STATUSES`; `refused` - `success` false, or another status;
177
+ * `unknown` - no status said (an empty answer): nothing is changed on our side,
178
+ * and the guest is told so.
179
+ */
180
+ export const cancelOutcome = (out) => {
181
+ if (out?.success === false)
182
+ return 'refused';
183
+ const s = String(out?.status ?? '')
184
+ .trim()
185
+ .toUpperCase();
186
+ if (!s)
187
+ return 'unknown';
188
+ return CANCELLED_STATUSES.has(s) ? 'done' : 'refused';
189
+ };
113
190
  const TERMS_TEXT_KEYS = ['terms', 'terms_text', 'termsText', 'terms_content', 'termsContent'];
114
191
  const TERMS_TOKEN_KEYS = ['terms_token', 'termsToken'];
115
192
  const isCode = (err, code) => err instanceof OtalessError && !(err instanceof OtalessBusy) && err.backendCode === code;
@@ -182,6 +259,10 @@ export const createOtalessBookings = (deps) => {
182
259
  ? [orders.get(id)]
183
260
  : [...orders.values()].filter((o) => !!o.code && o.code.toLowerCase() === low);
184
261
  for (const r of named) {
262
+ // ⚠️ LET GO AT ONCE, NOT THE GUEST'S TO ACT ON (总线程's review of 0.63.0, 7):
263
+ // one that could not be undone is a person's.
264
+ if (r.released)
265
+ continue;
185
266
  const acct = accountFor(who, r.group);
186
267
  if (acct && acct.owner === r.owner)
187
268
  return { r, acct };
@@ -422,7 +503,8 @@ export const createOtalessBookings = (deps) => {
422
503
  providerCode: a.group,
423
504
  reason: 'price or payment page not as quoted',
424
505
  }, cred, deps.callerOf(a.who)));
425
- if (done?.success === false)
506
+ // Not said to be done - refused, or not known: a person, as any failure here.
507
+ if (cancelOutcome(done) !== 'done')
426
508
  throw new Error('not cancelled');
427
509
  r.status = 'cancelled';
428
510
  r.cancelledAt = iso();
@@ -659,16 +741,31 @@ export const createOtalessBookings = (deps) => {
659
741
  failed.push({ ...failedStay(label, signInFirst([group]).message), groups: [group] });
660
742
  continue;
661
743
  }
662
- // A second press, a lost answer: the order already made for this stay.
663
744
  const lockKey = `${acct.owner}|${hotel.id}|${line.roomRef}|${stay.checkIn}|${stay.checkOut}|${rooms}`;
664
- const before = [...orders.values()].find((o) => o.owner === acct.owner &&
745
+ const sameStay = (o) => o.owner === acct.owner &&
746
+ !o.released &&
665
747
  o.hotelId === hotel.id &&
666
748
  o.roomId === line.roomRef &&
667
749
  o.stay.checkIn === stay.checkIn &&
668
750
  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);
751
+ o.rooms === rooms;
752
+ // ⚠️ AN EARLIER ORDER OF THIS STAY THAT MAY HAVE BEEN MADE IS LOOKED FOR
753
+ // FIRST, HOWEVER OLD (总线程's review of 0.63.0, 5): the group's order list
754
+ // (12) is read; not found there - or not readable - nothing new is sent.
755
+ const unknown = [...orders.values()].filter((o) => sameStay(o) && o.status === 'unconfirmed');
756
+ if (unknown.length) {
757
+ const read = await lookAtOrders(acct, who, group, unknown);
758
+ if (!read || unknown.some((o) => o.status === 'unconfirmed')) {
759
+ failed.push(failedStay(label, `An earlier booking of this stay is still being looked into with ${deps.groupOf(group).name} - whether it was made is not known yet, so nothing new was booked. Look at the bookings again in a few minutes.`));
760
+ continue;
761
+ }
762
+ }
763
+ // A second press, a lost answer, an order found in the list: the order
764
+ // already made for this stay, while it may still be paid - with no time to
765
+ // pay by known, until 15 or 12 says otherwise. Never a second one beside it.
766
+ const before = [...orders.values()].find((o) => sameStay(o) &&
767
+ o.status === 'awaiting-payment' &&
768
+ (now() - Date.parse(o.createdAt) < REPEAT_MS || !o.payBy || now() < Date.parse(o.payBy)));
672
769
  if (before) {
673
770
  booked.push(toBooking(before));
674
771
  reused.push(before.id);
@@ -892,14 +989,22 @@ export const createOtalessBookings = (deps) => {
892
989
  log(`[otaless] payment status of an order at ${r.group} not read: ${err instanceof Error ? err.name : 'error'}`);
893
990
  }
894
991
  };
895
- /** The group's order list (12): statuses, a lost payment link, and an order 13 did not answer for. */
992
+ /**
993
+ * The group's order list (12): statuses, a lost payment link, and an order
994
+ * 13 did not answer for. True when the list was read - false when it could
995
+ * not be (and nothing changed).
996
+ *
997
+ * ⚠️ WHAT IS LET GO OR STILL BEING LOOKED FOR IS NOT TOUCHED (总线程's review
998
+ * of 0.63.0, 3 and 7): a released order gets no status and no payment link
999
+ * back; an unconfirmed one moves only by being claimed, below.
1000
+ */
896
1001
  const lookAtOrders = async (acct, who, group, mine) => {
897
1002
  let rows;
898
1003
  try {
899
1004
  rows = await withSession(acct, who, (cred) => client.orders({ providerCode: group }, cred, deps.callerOf(who)));
900
1005
  }
901
1006
  catch {
902
- return;
1007
+ return false;
903
1008
  }
904
1009
  const known = new Set(orders.keys());
905
1010
  for (const row of rows) {
@@ -907,7 +1012,9 @@ export const createOtalessBookings = (deps) => {
907
1012
  if (!id)
908
1013
  continue;
909
1014
  const r = orders.get(id);
910
- if (r && r.owner === acct.owner) {
1015
+ if (r) {
1016
+ if (r.owner !== acct.owner || r.released || r.status === 'unconfirmed')
1017
+ continue;
911
1018
  const s = statusOfRow(row.status);
912
1019
  // ⚠️ AN UNPAID ORDER STAYS WAITING ("CONFIRMED" is not paid, questions
913
1020
  // #53): only PAID, a cancellation or a failure moves it.
@@ -932,11 +1039,24 @@ export const createOtalessBookings = (deps) => {
932
1039
  }
933
1040
  if (known.has(id))
934
1041
  continue;
935
- // An order 13 did not answer for: the one unclaimed row of the same group and nights.
1042
+ // ── an order 13 did not answer for (总线程's review of 0.63.0, 3) ──
1043
+ // ⚠️ THE SAME HOTEL, THE SAME ROOM, THE SAME NIGHTS - BY ID: the group and
1044
+ // the nights alone would claim another stay of the guest's. The document's
1045
+ // order rows carry no hotel or room id; until the backend sends them
1046
+ // (questions, 11-10 late), no row is claimed and the stay stays "being
1047
+ // looked into" - for a person.
1048
+ const hotelId = text(row.unifiedHotelId) ?? text(row.hotelId);
1049
+ const roomId = text(row.unifiedRoomId) ?? text(row.roomId);
936
1050
  const dates = String(row.dates ?? '');
937
1051
  const waiting = mine.filter((o) => o.status === 'unconfirmed' &&
938
1052
  o.id.startsWith('pending:') &&
1053
+ !o.released &&
1054
+ o.owner === acct.owner &&
939
1055
  o.group === group &&
1056
+ !!hotelId &&
1057
+ !!roomId &&
1058
+ o.hotelId === hotelId &&
1059
+ o.roomId === roomId &&
940
1060
  dates.includes(o.stay.checkIn) &&
941
1061
  dates.includes(o.stay.checkOut));
942
1062
  if (waiting.length !== 1)
@@ -945,33 +1065,29 @@ export const createOtalessBookings = (deps) => {
945
1065
  if (!o)
946
1066
  continue;
947
1067
  const charged = moneyOf(row.totalAmount, row.currency);
1068
+ // ⚠️ AT ANOTHER AMOUNT, NOT CLAIMED: the record keeps its own id and stays
1069
+ // unconfirmed - for a person.
1070
+ if (!charged || !(same(charged, o.quoted) || same(charged, o.quotedUsd))) {
1071
+ log(`[otaless] NEEDS A PERSON: an order 13 did not answer for was found at ${group} at another amount - not claimed`);
1072
+ continue;
1073
+ }
1074
+ const s = statusOfRow(row.status);
1075
+ const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
948
1076
  orders.delete(o.id);
949
1077
  o.id = id;
950
1078
  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`);
1079
+ o.charged = charged;
1080
+ // ⚠️ PAID IS ONLY "PAID": "CONFIRMED" unpaid is still waiting for its payment.
1081
+ if (s.paid) {
1082
+ o.status = 'confirmed';
1083
+ o.paid = true;
957
1084
  }
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
- }
1085
+ else if (s.status === 'cancelled' || s.status === 'failed') {
1086
+ o.status = s.status;
970
1087
  }
971
- else if (text(row.checkoutUrl ?? undefined)) {
972
- const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
1088
+ else {
1089
+ o.status = 'awaiting-payment';
973
1090
  if (ok) {
974
- o.status = 'awaiting-payment';
975
1091
  o.payHost = ok.host;
976
1092
  payLinks.set(id, ok.url);
977
1093
  }
@@ -979,6 +1095,7 @@ export const createOtalessBookings = (deps) => {
979
1095
  known.add(id);
980
1096
  put(o);
981
1097
  }
1098
+ return true;
982
1099
  };
983
1100
  /** The guest's orders brought up to date, each by their sign-in at its group (`signed`). */
984
1101
  const refresh = async (who, mine, signed) => {
@@ -1097,8 +1214,12 @@ export const createOtalessBookings = (deps) => {
1097
1214
  const out = await withSession(acct, who, (cred) => unpaid
1098
1215
  ? client.cancelCheckout({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who))
1099
1216
  : 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)))
1217
+ const said = cancelOutcome(out);
1218
+ // ⚠️ NOTHING SAID IS NOT DONE (总线程's review of 0.63.0, 4): our record
1219
+ // stays as it was, and the guest is told it is not known yet.
1220
+ if (said === 'unknown')
1221
+ 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.`);
1222
+ if (said === 'refused')
1102
1223
  throw refusal('not-cancelled', `${g} did not cancel it - it stands as it was.`);
1103
1224
  r.status = 'cancelled';
1104
1225
  r.cancelledAt = iso();
@@ -1109,8 +1230,44 @@ export const createOtalessBookings = (deps) => {
1109
1230
  put(r);
1110
1231
  return toBooking(r);
1111
1232
  };
1112
- // ── refund, add-ons (9.1, 10, 11) ─────────────────────────────────────────
1113
- const refund = async (ref, who, reason) => {
1233
+ // ── refund: a preview, then the refund it previewed (9.1; 总线程's review of 0.63.0, B) ──
1234
+ /** Refund previews waiting to be sent, by their `preview`. */
1235
+ const refundPreviews = new Map();
1236
+ const refundable = (r) => {
1237
+ if (!r.paid)
1238
+ throw refusal('not-paid', 'Nothing was paid for this booking, so there is nothing to refund.');
1239
+ };
1240
+ const previewRefund = async (ref, who) => {
1241
+ const own = ownOrder(ref, who);
1242
+ if (!own)
1243
+ return null;
1244
+ const { r } = own;
1245
+ if (r.refund)
1246
+ throw refusal('refunded', 'A refund was already asked for this booking.');
1247
+ refundable(r);
1248
+ for (const [k, v] of refundPreviews)
1249
+ if (now() - v.at > REFUND_PREVIEW_MS || v.orderId === r.id)
1250
+ refundPreviews.delete(k);
1251
+ while (refundPreviews.size >= PENDING_MAX) {
1252
+ const first = refundPreviews.keys().next().value;
1253
+ if (first === undefined)
1254
+ break;
1255
+ refundPreviews.delete(first);
1256
+ }
1257
+ const amount = r.charged ?? r.quoted;
1258
+ const preview = randomBytes(18).toString('base64url');
1259
+ refundPreviews.set(preview, { orderId: r.id, owner: r.owner, amount, at: now() });
1260
+ return {
1261
+ preview,
1262
+ bookingId: r.id,
1263
+ confirmationCode: r.code || r.id,
1264
+ supplier: r.group,
1265
+ amount,
1266
+ terms: r.terms ?? '',
1267
+ until: iso(now() + REFUND_PREVIEW_MS),
1268
+ };
1269
+ };
1270
+ const refund = async (ref, who, reason, preview) => {
1114
1271
  const own = ownOrder(ref, who);
1115
1272
  if (!own)
1116
1273
  return null;
@@ -1118,8 +1275,18 @@ export const createOtalessBookings = (deps) => {
1118
1275
  if (r.refund)
1119
1276
  return toBooking(r);
1120
1277
  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.');
1278
+ refundable(r);
1279
+ // ⚠️ THE PREVIEW OF THIS VERY BOOKING, FOR THIS GUEST, AT THIS AMOUNT, ONCE
1280
+ // (总线程's review of 0.63.0, B): nothing is sent without it.
1281
+ const shown = preview ? refundPreviews.get(preview) : undefined;
1282
+ if (preview)
1283
+ refundPreviews.delete(preview);
1284
+ if (!shown ||
1285
+ now() - shown.at > REFUND_PREVIEW_MS ||
1286
+ shown.orderId !== r.id ||
1287
+ shown.owner !== r.owner ||
1288
+ !same(shown.amount, r.charged ?? r.quoted))
1289
+ 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
1290
  const why = cleanReason(reason);
1124
1291
  // ⚠️ ALL OF IT, NEVER A PART (`amountUsd` is never sent), and no
1125
1292
  // `sessionToken` (questions #53): the backend takes the guest from the sign-in.
@@ -1147,7 +1314,11 @@ export const createOtalessBookings = (deps) => {
1147
1314
  per_night: 'night',
1148
1315
  per_guest_per_day: 'person-night',
1149
1316
  };
1317
+ /** Add-ons after booking, off unless the deployment turns them on (总线程's review of 0.63.0, A). */
1318
+ const addonsOff = () => refusal('addons-off', 'Nothing can be added to a booking here.');
1150
1319
  const addons = async (ref, who) => {
1320
+ if (!deps.addonsOn)
1321
+ throw addonsOff();
1151
1322
  const own = ownOrder(ref, who);
1152
1323
  if (!own?.r.code)
1153
1324
  return null;
@@ -1174,6 +1345,8 @@ export const createOtalessBookings = (deps) => {
1174
1345
  return out;
1175
1346
  };
1176
1347
  const bookAddon = async (ref, extraId, details, who) => {
1348
+ if (!deps.addonsOn)
1349
+ throw addonsOff();
1177
1350
  const own = ownOrder(ref, who);
1178
1351
  if (!own?.r.code)
1179
1352
  return null;
@@ -1216,6 +1389,7 @@ export const createOtalessBookings = (deps) => {
1216
1389
  return found ? view(found.p) : undefined;
1217
1390
  },
1218
1391
  acceptTerms,
1392
+ previewRefund,
1219
1393
  refund,
1220
1394
  addons,
1221
1395
  bookAddon,