@curless/hotel-storefront 0.65.2 → 0.67.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.
Files changed (82) hide show
  1. package/dist/account/fake-ota.d.ts +5 -0
  2. package/dist/account/fake-ota.d.ts.map +1 -1
  3. package/dist/account/fake-ota.js +8 -2
  4. package/dist/account/fake-ota.js.map +1 -1
  5. package/dist/account/index.d.ts +36 -0
  6. package/dist/account/index.d.ts.map +1 -1
  7. package/dist/account/index.js +208 -26
  8. package/dist/account/index.js.map +1 -1
  9. package/dist/account/ota-member.d.ts +2 -0
  10. package/dist/account/ota-member.d.ts.map +1 -1
  11. package/dist/account/ota-member.js +2 -0
  12. package/dist/account/ota-member.js.map +1 -1
  13. package/dist/account/pages.d.ts +51 -5
  14. package/dist/account/pages.d.ts.map +1 -1
  15. package/dist/account/pages.js +153 -23
  16. package/dist/account/pages.js.map +1 -1
  17. package/dist/account/requests.d.ts +2 -0
  18. package/dist/account/requests.d.ts.map +1 -1
  19. package/dist/account/requests.js.map +1 -1
  20. package/dist/account/store.d.ts +57 -2
  21. package/dist/account/store.d.ts.map +1 -1
  22. package/dist/account/store.js +52 -4
  23. package/dist/account/store.js.map +1 -1
  24. package/dist/card.generated.d.ts +1 -1
  25. package/dist/card.generated.js +2 -2
  26. package/dist/card.generated.js.map +1 -1
  27. package/dist/config.d.ts +10 -0
  28. package/dist/config.d.ts.map +1 -1
  29. package/dist/config.js.map +1 -1
  30. package/dist/otaless/backend.d.ts +6 -2
  31. package/dist/otaless/backend.d.ts.map +1 -1
  32. package/dist/otaless/backend.js +58 -9
  33. package/dist/otaless/backend.js.map +1 -1
  34. package/dist/otaless/booking.d.ts +190 -28
  35. package/dist/otaless/booking.d.ts.map +1 -1
  36. package/dist/otaless/booking.js +929 -374
  37. package/dist/otaless/booking.js.map +1 -1
  38. package/dist/otaless/client.d.ts +120 -34
  39. package/dist/otaless/client.d.ts.map +1 -1
  40. package/dist/otaless/client.js +133 -19
  41. package/dist/otaless/client.js.map +1 -1
  42. package/dist/otaless/fake.d.ts +59 -10
  43. package/dist/otaless/fake.d.ts.map +1 -1
  44. package/dist/otaless/fake.js +132 -34
  45. package/dist/otaless/fake.js.map +1 -1
  46. package/dist/otaless/make.d.ts +2 -0
  47. package/dist/otaless/make.d.ts.map +1 -1
  48. package/dist/otaless/make.js +56 -18
  49. package/dist/otaless/make.js.map +1 -1
  50. package/dist/otaless/places.d.ts +14 -0
  51. package/dist/otaless/places.d.ts.map +1 -1
  52. package/dist/otaless/places.js +108 -1
  53. package/dist/otaless/places.js.map +1 -1
  54. package/dist/pictures.d.ts +19 -0
  55. package/dist/pictures.d.ts.map +1 -0
  56. package/dist/pictures.js +74 -0
  57. package/dist/pictures.js.map +1 -0
  58. package/dist/server.d.ts +15 -2
  59. package/dist/server.d.ts.map +1 -1
  60. package/dist/server.js +236 -37
  61. package/dist/server.js.map +1 -1
  62. package/dist/sessions.d.ts +23 -0
  63. package/dist/sessions.d.ts.map +1 -1
  64. package/dist/sessions.js +39 -1
  65. package/dist/sessions.js.map +1 -1
  66. package/dist/supplier.js +4 -0
  67. package/dist/supplier.js.map +1 -1
  68. package/dist/surface.d.ts +24 -1
  69. package/dist/surface.d.ts.map +1 -1
  70. package/dist/surface.js +35 -6
  71. package/dist/surface.js.map +1 -1
  72. package/dist/tools.d.ts +24 -0
  73. package/dist/tools.d.ts.map +1 -1
  74. package/dist/tools.js +217 -23
  75. package/dist/tools.js.map +1 -1
  76. package/dist/trip-ids.d.ts +13 -1
  77. package/dist/trip-ids.d.ts.map +1 -1
  78. package/dist/trip-ids.js +30 -3
  79. package/dist/trip-ids.js.map +1 -1
  80. package/dist/types.d.ts +88 -2
  81. package/dist/types.d.ts.map +1 -1
  82. package/package.json +1 -1
@@ -6,19 +6,28 @@ import { movedSince } from '../huazhu/backend.js';
6
6
  import { money, toMinor } from '../money.js';
7
7
  import { CHANNEL_SESSION_EXPIRED, NOT_SIGNED_IN, OtalessBusy, OtalessError, REPEAT_SUBMIT, SESSION_ID, forTheLog, } from './client.js';
8
8
  // Booking on the Otaless hotel backend: items 8-16 of its document of
9
- // 2026-11-10, as 总线程 settled them that day (docs/otaless-hotels.md §12,
10
- // with 12.9 over 12.1-12.8). Real money - written to production's standard:
9
+ // 2026-11-10. Since 2026-11-11 the order is 8 `booking/create` - the backend's
10
+ // own answer to questions #56: 「booking/create 就行,checkout 所有的 api 不需要」
11
+ // (13 / 14 are not called any more) - as 总线程 settled it that day
12
+ // (docs/otaless-hotels.md §15, with 15.7 over the rest). Real money - written
13
+ // to production's standard. 8 holds no price and takes no "do not agree", so
14
+ // both are held here:
11
15
  //
12
- // - ONE ENDPOINT BOOKS: 13 `checkout/create`, one stay per order. Never 8
13
- // `booking/create`: it takes no price to hold the order to, and cannot be
14
- // told not to agree to the group's terms on the guest's behalf.
15
- // - THE PRICE THE GUEST SAW, OR NOTHING: the trip is priced again first and
16
- // checked against what the guest was shown; 13's own amount is then checked
17
- // against that price, and an order at any other is let go at once (14).
18
- // - TERMS ARE NEVER AGREED TO FOR THE GUEST: `termsAccepted` is false on
19
- // every call; terms that come back are kept here, shown to the guest word
20
- // for word, and sent back only once the guest has agreed (`acceptTerms`).
21
- // - A PAYMENT PAGE ON AN ADDRESS NOT LISTED IS NEVER HANDED ON.
16
+ // - TERMS FIRST, AGREED BY THE GUEST: every stay's cancellation terms - as the
17
+ // group sent them with the room, word for word - are shown before anything
18
+ // is ordered, and 8 is called only once the guest agreed on the card's own
19
+ // button or the one-time page (`acceptTerms`), never on the model's word.
20
+ // Terms the group answers the order with that are not the ones agreed hold
21
+ // the order's payment page back until the guest agrees to them too; not
22
+ // agreed, or not in `TERMS_MS`, the order is cancelled (9).
23
+ // - THE PRICE THE GUEST SAW, OR NOTHING: right before 8 the room is priced
24
+ // again (7) in the guest's own session - the one 8 then runs in (questions
25
+ // #62) - and held to the price the guest was shown; 8's own amount is then
26
+ // held to that quote, and an order at any other amount, for any other
27
+ // number of guests, or with a payment page not on the list is cancelled at
28
+ // once (9). One that cannot be cancelled is a person's, and said so.
29
+ // - A PAYMENT PAGE ON AN ADDRESS NOT LISTED IS NEVER HANDED ON - and a page
30
+ // listed with its order (`?order={order}`) only for that very order.
22
31
  // - AN ORDER IS ACTED ON ONLY IF IT IS IN OUR OWN RECORD, as this guest's
23
32
  // (their sign-in's member id): the id sent to the backend is the record's,
24
33
  // never the model's.
@@ -26,24 +35,36 @@ import { CHANNEL_SESSION_EXPIRED, NOT_SIGNED_IN, OtalessBusy, OtalessError, REPE
26
35
  // backend's own `/ota/sign-in`, its `accessToken` and `mcpSessionId` -
27
36
  // `bookingAuth`), never kept here; a session this connector opens after a
28
37
  // 4012 is kept by sign-in and group, in memory only. A 4012 is answered
29
- // with one new handshake and one more try - never a loop.
38
+ // with one new handshake and one more try - never a loop. An order not
39
+ // answered for is never asked for again.
30
40
  //
31
41
  // ⚠️ NOTHING HERE IS REACHED UNLESS THE DEPLOYMENT TURNS BOOKING ON
32
42
  // (`data.otaless.booking`, 酒店平台 0.63.0; robin 11-10 「我们要跑通测试流程的」):
33
43
  // read-only - the default - the tools that would call it are not offered.
34
- /** How long terms sent back for agreement are kept for the guest to agree to (§12.1). */
44
+ /**
45
+ * How long terms are kept for the guest to agree to (§12.1) - and how long an
46
+ * order whose terms changed holds its payment page back before it is
47
+ * cancelled (总线程 11-11, D).
48
+ */
35
49
  export const TERMS_MS = 10 * 60_000;
36
50
  /** How long a group's `Mcp-Session-Id` is kept unused (§12.3). */
37
51
  export const SESSION_IDLE_MS = 2 * 60 * 60_000;
38
52
  /** A payment's status is asked for at most this often per order (§12.1, 15). */
39
53
  export const STATUS_EVERY_MS = 10_000;
40
54
  /**
41
- * An order 13 did not answer for, not found in the group's list this long
55
+ * An order 8 did not answer for, not found in the group's list this long
42
56
  * after it was asked for - and nothing there that could be it - no longer holds
43
57
  * the stay back (总线程's re-review of 0.63.1, 1). Eight times the 15 minutes
44
58
  * the document's checkout holds a room unpaid.
45
59
  */
46
60
  export const UNCONFIRMED_GIVE_UP_MS = 2 * 60 * 60_000;
61
+ /**
62
+ * An order a person was to see to (`needsPerson`), still not settled this long
63
+ * after: no longer holds the stay back - the guest is told first, as it is
64
+ * (总线程's review of 0.66.0, 6). The same two hours as an order 8 did not
65
+ * answer for: any hold on an unpaid room is long gone by then.
66
+ */
67
+ export const NEEDS_PERSON_GIVE_UP_MS = 2 * 60 * 60_000;
47
68
  /**
48
69
  * An order waiting for its payment with no time to pay by from 13: taken as
49
70
  * payable this long after it was made, or after the payment status (15) last
@@ -79,11 +100,15 @@ const PENDING_PER_ACCOUNT = 5;
79
100
  const CHECKED_PER_LOOK = 5;
80
101
  /**
81
102
  * 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.
103
+ * the group checkout host of 13's example (`pay.discoverasr.com`). Exact host
104
+ * names: no wildcard, no other port. ⚠️ NOT `mcp.curless.ai` (总线程's
105
+ * re-review of 0.63.1, 720f5e4f; again 11-11, B): that is our own hosted
106
+ * checkout, which takes any merchant and any amount, and has no `/pay/cashier`
107
+ * behind it today - though 8's example names it. A page there is not handed
108
+ * on: the order is cancelled and its host logged, to ask the backend about.
109
+ * Should it ever be listed, it is as `mcp.curless.ai/pay/cashier?order={order}`
110
+ * - that page for that order alone (`payPageOf`). A page on a host listed
111
+ * alone must still name the order (总线程's review of 0.66.0, 2).
87
112
  */
88
113
  export const DEFAULT_CHECKOUT_HOSTS = ['pay.discoverasr.com'];
89
114
  /** How long a refund's preview can be sent back (总线程's review of 0.63.0, B). */
@@ -129,24 +154,63 @@ export const pathSegments = (path) => {
129
154
  }
130
155
  return out;
131
156
  };
132
- /** One `checkoutHosts` entry: a host, and - written `host/a/b/` - the path a page must be under. */
157
+ /**
158
+ * One `checkoutHosts` entry: a host; a host and the path a page must be under
159
+ * (`host/a/b/`); or a host, the exact path and the one query parameter that
160
+ * must name the order (`host/a/b?order={order}` - `order` is the parameter's
161
+ * name, 总线程 11-11, B). A malformed path or query matches nothing.
162
+ */
133
163
  export const checkoutEntryOf = (entry) => {
134
164
  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 };
165
+ const q = e.indexOf('?');
166
+ const left = q < 0 ? e : e.slice(0, q);
167
+ const slash = left.indexOf('/');
168
+ const host = (slash < 0 ? left : left.slice(0, slash)).toLowerCase();
169
+ const under = slash < 0 ? [] : (pathSegments(left.slice(slash)) ?? ['\u0000']);
170
+ if (q < 0)
171
+ return { host, under };
172
+ const m = /^([A-Za-z0-9_.~-]+)=\{order\}$/.exec(e.slice(q + 1));
173
+ return { host, under: under.length ? under : ['\u0000'], order: m?.[1] ?? '\u0000' };
174
+ };
175
+ /**
176
+ * What is wrong with a list of payment pages, or nothing: ⚠️ A HOST LISTED
177
+ * WITH ITS ORDER (`?order={order}`) IS LISTED NO WIDER (总线程 11-11, B) - no
178
+ * entry of it alone, or of a path a page is under, beside it: that would let
179
+ * any page there through. Entries naming the order are not wider than each other.
180
+ */
181
+ export const checkoutHostsProblem = (hosts) => {
182
+ const entries = hosts.map((h) => ({ h, e: checkoutEntryOf(h) }));
183
+ for (const { h, e } of entries) {
184
+ if (e.order === undefined)
185
+ continue;
186
+ const wider = entries.find((x) => x.e.host === e.host && x.e.order === undefined);
187
+ if (wider)
188
+ return `"${wider.h}" lets any page on ${e.host} through beside "${h}", which takes only the order's own page`;
189
+ }
190
+ return undefined;
139
191
  };
140
192
  /**
141
193
  * Where a payment page may send the guest: `https:`, an exact host on the
142
194
  * 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
195
+ * written with a path (`host/pay/`) also holds it to that path, by whole
196
+ * segments, compared after the path is put the way a server reads it
145
197
  * (`pathSegments`: no `..`, `%2e` or `//` slips past); an entry of a host alone
146
198
  * takes any path on it (总线程's review of 0.63.0, 8). The page handed on is
147
199
  * the one checked: its path as compared.
200
+ *
201
+ * ⚠️ AND ONLY A PAGE NAMING THIS ORDER (总线程's review of 0.66.0, 2): through an
202
+ * entry without `{order}`, the order's `unifiedOrderId` or `originalOrderId` must
203
+ * be in the page - a whole path segment, or a whole query value. Neither there,
204
+ * or no order to hold it to: nothing. (`pay.discoverasr.com` until its pages'
205
+ * real form is known - then an exact entry naming `{order}`.)
206
+ *
207
+ * ⚠️ AN ENTRY NAMING THE ORDER (`host/pay/cashier?order={order}`, 总线程
208
+ * 11-11, B) TAKES ONE PAGE: that path exactly, and a query of that one
209
+ * parameter, once, naming `order` - this very order's `unifiedOrderId` - and
210
+ * no fragment. What is handed on is rebuilt from the entry and the order, never
211
+ * the backend's own string. No order to hold it to: nothing.
148
212
  */
149
- export const payPageOf = (raw, hosts) => {
213
+ export const payPageOf = (raw, hosts, order) => {
150
214
  if (!raw)
151
215
  return undefined;
152
216
  let u;
@@ -162,35 +226,193 @@ export const payPageOf = (raw, hosts) => {
162
226
  const segs = pathSegments(u.pathname);
163
227
  if (!segs)
164
228
  return undefined;
165
- const allowed = hosts.some((h) => {
229
+ for (const h of hosts) {
166
230
  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('/') ? '/' : ''}`;
172
- return { url: u.toString(), host };
231
+ if (e.host !== host || !e.under.every((seg, i) => segs[i] === seg))
232
+ continue;
233
+ if (e.order === undefined) {
234
+ if (!namesOrder(u, segs, order))
235
+ continue;
236
+ u.pathname = `/${segs.join('/')}${segs.length && u.pathname.endsWith('/') ? '/' : ''}`;
237
+ return { url: u.toString(), host };
238
+ }
239
+ if (!order?.id || segs.length !== e.under.length || u.hash)
240
+ continue;
241
+ const keys = [...u.searchParams.keys()];
242
+ if (keys.length !== 1 || keys[0] !== e.order || u.searchParams.get(e.order) !== order.id)
243
+ continue;
244
+ return {
245
+ url: `https://${host}/${e.under.join('/')}?${e.order}=${encodeURIComponent(order.id)}`,
246
+ host,
247
+ };
248
+ }
249
+ return undefined;
250
+ };
251
+ /**
252
+ * Whether a page names the order: its `unifiedOrderId` or `originalOrderId` as
253
+ * a whole path segment (as written, or decoded) or a whole query value - never
254
+ * a part of one, never in the fragment (总线程's review of 0.66.0, 2).
255
+ */
256
+ const namesOrder = (u, segs, order) => {
257
+ const ids = [order?.id, order?.code].filter((x) => !!x);
258
+ if (!ids.length)
259
+ return false;
260
+ const decoded = (seg) => {
261
+ try {
262
+ return decodeURIComponent(seg);
263
+ }
264
+ catch {
265
+ return seg;
266
+ }
267
+ };
268
+ return (segs.some((seg) => ids.includes(seg) || ids.includes(decoded(seg))) ||
269
+ [...u.searchParams.values()].some((v) => ids.includes(v)));
270
+ };
271
+ /** Whether a page is on a host the list names - whatever its path. */
272
+ const onListedHost = (raw, hosts) => {
273
+ try {
274
+ const host = new URL(String(raw)).hostname.toLowerCase();
275
+ return hosts.some((h) => checkoutEntryOf(h).host === host);
276
+ }
277
+ catch {
278
+ return false;
279
+ }
173
280
  };
174
- /** The host of a URL for the log - never its path or query (they carry the payment token). */
281
+ /**
282
+ * The host of a page not handed on, for the log - never its path, query or
283
+ * fragment: some payment pages carry their token in the path (总线程's review
284
+ * of 0.66.0, 4).
285
+ */
175
286
  const hostForLog = (raw) => {
176
287
  try {
177
- return forTheLog(new URL(String(raw)).host || '?');
288
+ return forTheLog(new URL(String(raw)).host) || '?';
178
289
  }
179
290
  catch {
180
291
  return 'not a URL';
181
292
  }
182
293
  };
183
- /** The first of `keys` in `o` that is words - the terms' text and token under whatever name the group's tool gave them. */
184
- const firstText = (o, keys) => {
185
- for (const k of keys) {
186
- const v = o?.[k];
187
- if (typeof v === 'string' && v.trim())
188
- return v;
294
+ /** A path segment written on the log as it is: a plain lower-case word - anything else is its length. */
295
+ const PATH_WORD = /^[a-z_-]{1,20}$/;
296
+ /** A query parameter's name written as it is: a plain word, either case. */
297
+ const KEY_WORD = /^[A-Za-z_-]{1,20}$/;
298
+ /** At most this many path segments, and as many parameters, on one shape. */
299
+ const SHAPE_PARTS = 12;
300
+ /**
301
+ * The form of a payment page not handed on, for the log - NO VALUE OF IT
302
+ * (总线程 11-11 late): each path segment a plain word as it is, or its length;
303
+ * each parameter's name (a plain word, or its length) and its value's length;
304
+ * and where this order's `unifiedOrderId` / `originalOrderId` is in it - or
305
+ * that it is not. From the first real page, the exact `{order}` entry can be
306
+ * written; no payment token reaches the log.
307
+ */
308
+ export const pageShape = (raw, order) => {
309
+ let u;
310
+ try {
311
+ u = new URL(String(raw));
189
312
  }
313
+ catch {
314
+ return 'not a URL';
315
+ }
316
+ const segs = pathSegments(u.pathname) ?? u.pathname.split('/').filter(Boolean);
317
+ const pairs = [...u.searchParams.entries()];
318
+ const size = (x) => `<${x.length} chars>`;
319
+ const key = (k) => (KEY_WORD.test(k) ? k : size(k));
320
+ const more = (n) => (n > SHAPE_PARTS ? ` (+${n - SHAPE_PARTS} more)` : '');
321
+ const decoded = (x) => {
322
+ try {
323
+ return decodeURIComponent(x);
324
+ }
325
+ catch {
326
+ return x;
327
+ }
328
+ };
329
+ const path = `/${segs
330
+ .slice(0, SHAPE_PARTS)
331
+ .map((x) => (PATH_WORD.test(x) ? x : size(x)))
332
+ .join('/')}${more(segs.length)}`;
333
+ const query = pairs.length
334
+ ? ` ? ${pairs
335
+ .slice(0, SHAPE_PARTS)
336
+ .map(([k, v]) => `${key(k)}=${size(v)}`)
337
+ .join(' & ')}${more(pairs.length)}`
338
+ : '';
339
+ const hash = u.hash.length > 1 ? ` # ${size(u.hash.slice(1))}` : '';
340
+ const where = [];
341
+ for (const [what, id] of [
342
+ ['unifiedOrderId', order?.id],
343
+ ['originalOrderId', order?.code],
344
+ ]) {
345
+ if (!id)
346
+ continue;
347
+ segs.forEach((x, i) => {
348
+ const d = decoded(x);
349
+ if (x === id || d === id)
350
+ where.push(`${what} is path segment ${i + 1}`);
351
+ else if (x.includes(id) || d.includes(id))
352
+ where.push(`${what} is inside path segment ${i + 1}`);
353
+ });
354
+ for (const [k, v] of pairs) {
355
+ if (v === id)
356
+ where.push(`${what} is the value of ${key(k)}`);
357
+ else if (v.includes(id))
358
+ where.push(`${what} is inside the value of ${key(k)}`);
359
+ if (k.includes(id))
360
+ where.push(`${what} is inside a parameter's name`);
361
+ }
362
+ if (decoded(u.hash.slice(1)).includes(id))
363
+ where.push(`${what} is in the fragment`);
364
+ }
365
+ return `${path}${query}${hash} - ${where.length ? where.join(', ') : 'this order is not in it'}`;
366
+ };
367
+ /**
368
+ * Two terms the same but for spacing and punctuation (总线程 11-11, D): a
369
+ * group's answer formatted a little differently is not new terms to agree to.
370
+ */
371
+ export const termsKey = (s) => s.normalize('NFKC').replace(/[\s\p{P}]/gu, '');
372
+ /** Which step a refusal of 8 - or its status - asks for, or none. */
373
+ export const stepAsked = (said) => {
374
+ const s = String(said ?? '');
375
+ if (/\bterms[ _-]?required\b/i.test(s))
376
+ return 'terms';
377
+ if (/\bconfirm(?:ation)?[ _-]?required\b/i.test(s))
378
+ return 'confirm';
190
379
  return undefined;
191
380
  };
192
381
  /**
193
- * The statuses a cancellation (9 `booking/cancel`, 14 `checkout/cancel`) is
382
+ * What to agree to or confirm, and the token to do it with, as 8 would send
383
+ * them back with `terms_required` / `confirm_required` - both, or nothing.
384
+ * ⚠️ THE NAMES ARE THE ONES ASKED FOR IN QUESTIONS #66 AND #68
385
+ * (`termsText` / `termsToken`, `confirmText` / `confirmToken`, or written with
386
+ * `_`), not yet in 8's document: until the backend answers, an answer naming
387
+ * them otherwise is a refusal, as it is today. An amount or nights beside them
388
+ * are read by 8's own names (`totalAmount`, `currency`, `checkIn`, `checkOut`).
389
+ */
390
+ export const groupStepOf = (step, data) => {
391
+ if (!data || typeof data !== 'object')
392
+ return undefined;
393
+ const d = data;
394
+ const said = step === 'terms' ? (d.termsText ?? d.terms_text) : (d.confirmText ?? d.confirm_text);
395
+ const token = step === 'terms' ? (d.termsToken ?? d.terms_token) : (d.confirmToken ?? d.confirm_token);
396
+ if (typeof said !== 'string' || typeof token !== 'string')
397
+ return undefined;
398
+ const t = said.trim();
399
+ const k = token.trim();
400
+ if (!t || t.length > TERMS_MAX || !/^[\x21-\x7e]{1,512}$/.test(k))
401
+ return undefined;
402
+ const amount = moneyOf(d.totalAmount, d.currency);
403
+ const named = (d.totalAmount ?? d.currency) !== undefined && (d.totalAmount ?? d.currency) !== null;
404
+ const checkIn = text(d.checkIn);
405
+ const checkOut = text(d.checkOut);
406
+ return {
407
+ text: t,
408
+ token: k,
409
+ ...(amount ? { amount } : named ? { amountUnread: true } : {}),
410
+ ...(checkIn ? { checkIn } : {}),
411
+ ...(checkOut ? { checkOut } : {}),
412
+ };
413
+ };
414
+ /**
415
+ * The statuses a cancellation (9 `booking/cancel`; 14 `checkout/cancel` before 11-11) is
194
416
  * taken as DONE by - exactly these, case aside (总线程's review of 0.63.0, 4):
195
417
  * the document's own words ("CANCELLED"; 14's "CANCELLED", "SUCCESS") and
196
418
  * their spelling variants. ⚠️ NOT A PATTERN: /CANCEL|CLOSED|SUCCESS/ took
@@ -219,8 +441,6 @@ export const cancelOutcome = (out) => {
219
441
  return 'unknown';
220
442
  return CANCELLED_STATUSES.has(s) ? 'done' : 'refused';
221
443
  };
222
- const TERMS_TEXT_KEYS = ['terms', 'terms_text', 'termsText', 'terms_content', 'termsContent'];
223
- const TERMS_TOKEN_KEYS = ['terms_token', 'termsToken'];
224
444
  const isCode = (err, code) => err instanceof OtalessError && !(err instanceof OtalessBusy) && err.backendCode === code;
225
445
  /**
226
446
  * Sent, and no answer it could be read by: whether it was done is not known -
@@ -437,8 +657,9 @@ export const createOtalessBookings = (deps) => {
437
657
  if (r.paid)
438
658
  return { method: 'card', amount, status: 'paid' };
439
659
  if (r.status === 'awaiting-payment') {
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;
660
+ // ⚠️ NO LINK PAST ITS TIME: a page that cannot be paid any more is not handed on -
661
+ // nor one held back for terms not agreed to yet (总线程 11-11, D).
662
+ const url = !r.held && now() < payableUntil(r) ? payLinks.get(r.id) : undefined;
442
663
  return {
443
664
  method: 'card',
444
665
  amount,
@@ -492,8 +713,12 @@ export const createOtalessBookings = (deps) => {
492
713
  },
493
714
  ...(r.cancelledAt ? { cancelledAt: r.cancelledAt } : {}),
494
715
  };
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 } : {});
716
+ // Beside the type, for the words (0.63.2): why it is not known - and (11-11,
717
+ // D) an order whose payment page waits for terms the group answered it with.
718
+ return Object.assign(booking, r.unverifiable ? { unverifiable: true } : {}, r.needsPerson ? { needsPerson: r.needsPerson } : {}, r.held ? { termsChanged: true, termsUntil: r.held.until } : {},
719
+ // With a person past its time and the guest told so: no longer holds the stay
720
+ // back (总线程's review of 0.66.0, 6) - the words must not say it does.
721
+ r.needsPerson && r.rebookable ? { rebookable: true } : {});
497
722
  };
498
723
  const failedStay = (a, why, code) => ({
499
724
  hotelId: a.hotel.id,
@@ -504,7 +729,8 @@ export const createOtalessBookings = (deps) => {
504
729
  why,
505
730
  ...(code ? { code } : {}),
506
731
  });
507
- const recordOf = (a, id, code, status) => ({
732
+ const limited = (a, name) => failedStay(a, `Not sent to ${name}: too many requests just now - ask again in a minute.`, 'limited');
733
+ const recordOf = (a, pairs, id, code, status) => ({
508
734
  id,
509
735
  code,
510
736
  group: a.group,
@@ -517,10 +743,10 @@ export const createOtalessBookings = (deps) => {
517
743
  roomName: a.roomName,
518
744
  stay: a.stay,
519
745
  rooms: a.rooms,
520
- quoted: a.pairs.orig,
521
- quotedUsd: a.pairs.usd,
746
+ quoted: pairs.orig,
747
+ ...(pairs.usd ? { quotedUsd: pairs.usd } : {}),
522
748
  status,
523
- ...(a.terms ? { terms: a.terms } : {}),
749
+ ...(a.agreed ? { terms: a.agreed } : {}),
524
750
  guest: {
525
751
  name: a.guest.name,
526
752
  email: maskEmail(a.guest.email) ?? '',
@@ -532,26 +758,203 @@ export const createOtalessBookings = (deps) => {
532
758
  orders.set(r.id, r);
533
759
  save();
534
760
  };
761
+ // ── terms (§15.2; 总线程 11-11, A and D) ──────────────────────────────────
762
+ const view = (p) => ({
763
+ ref: p.ref,
764
+ group: p.group,
765
+ groupName: p.groupName,
766
+ ...(p.groupNames ? { groupNames: p.groupNames } : {}),
767
+ hotelId: p.hotelId,
768
+ hotelName: p.hotelName,
769
+ ...(p.hotelNames ? { hotelNames: p.hotelNames } : {}),
770
+ roomName: p.roomName,
771
+ stay: p.stay,
772
+ rooms: p.rooms,
773
+ total: p.total,
774
+ text: p.text,
775
+ source: p.source,
776
+ more: true,
777
+ ...(p.changed ? { changed: true } : {}),
778
+ ...(p.askedByGroup ? { askedByGroup: p.askedByGroup } : {}),
779
+ ...(p.bookingId ? { bookingId: p.bookingId } : {}),
780
+ ...(p.confirmationCode ? { confirmationCode: p.confirmationCode } : {}),
781
+ until: p.until,
782
+ });
783
+ /** Keeps terms for the guest - a few per account, a bounded number in all. */
784
+ const remember = (p) => {
785
+ const mine = [...pending.values()].filter((x) => x.owner === p.owner);
786
+ for (const x of mine.slice(0, Math.max(0, mine.length - PENDING_PER_ACCOUNT + 1)))
787
+ pending.delete(x.ref);
788
+ pending.set(p.ref, p);
789
+ while (pending.size > PENDING_MAX) {
790
+ const first = pending.keys().next().value;
791
+ if (first === undefined)
792
+ break;
793
+ pending.delete(first);
794
+ }
795
+ counts.termsSent += 1;
796
+ return view(p);
797
+ };
798
+ const groupWords = (code) => {
799
+ const g = deps.groupOf(code);
800
+ return { groupName: g.name, ...(g.names ? { groupNames: g.names } : {}) };
801
+ };
802
+ /** The terms of one stay, for the guest to agree to before it is ordered. */
803
+ const termsBefore = (a) => remember({
804
+ ref: randomBytes(18).toString('base64url'),
805
+ group: a.group,
806
+ ...groupWords(a.group),
807
+ hotelId: a.hotel.id,
808
+ hotelName: a.hotel.name,
809
+ ...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
810
+ roomName: a.roomName,
811
+ stay: a.stay,
812
+ rooms: a.rooms,
813
+ total: a.total,
814
+ text: a.agreed,
815
+ source: a.agreed ? 'room' : 'none',
816
+ more: true,
817
+ until: iso(now() + TERMS_MS),
818
+ owner: a.acct.owner,
819
+ key: a.acct.key,
820
+ ask: { roomId: a.roomId, guest: a.guest },
821
+ });
822
+ /**
823
+ * 8 asked for a second step (`terms_required`, questions #66;
824
+ * `confirm_required`, #68). ⚠️ NEVER AGREED OR CONFIRMED FOR THE GUEST (#52):
825
+ * with what to agree to or confirm and a token - and, where it names an
826
+ * amount or nights, the price and nights the guest was shown - it is the
827
+ * guest's to read and do themselves, nothing ordered; done, 8 is priced again
828
+ * and sent once more with the token. Without both - or asked again after the
829
+ * guest did it - nothing is booked, and the log says which it was.
830
+ */
831
+ const groupAsked = (a, step, data, pairs) => {
832
+ const g = deps.groupOf(a.group);
833
+ const what = `${step}_required`;
834
+ const code = (step === 'terms' ? 'group-terms' : 'group-confirm');
835
+ const asked = groupStepOf(step, data);
836
+ if (asked && !a.groupStep) {
837
+ const amountOff = asked.amountUnread ||
838
+ (asked.amount && !(same(asked.amount, pairs.orig) || same(asked.amount, pairs.usd)));
839
+ const nightsOff = (asked.checkIn !== undefined && asked.checkIn !== a.stay.checkIn) ||
840
+ (asked.checkOut !== undefined && asked.checkOut !== a.stay.checkOut);
841
+ if (amountOff || nightsOff) {
842
+ log(`[otaless] booking at ${a.group} answered ${what} for ${amountOff ? 'another amount' : 'other nights'} than the guest was shown - not shown, not booked`);
843
+ return {
844
+ failed: failedStay(a, `${g.name} asked for ${step === 'terms' ? 'its terms to be agreed to' : 'the booking to be confirmed'} at ${amountOff ? 'another amount' : 'other nights'} than the guest was shown, so nothing was booked or charged.`, code),
845
+ };
846
+ }
847
+ log(`[otaless] booking at ${a.group} answered ${what} with what to ${step === 'terms' ? 'agree to' : 'confirm'} - shown to the guest, nothing ordered`);
848
+ return {
849
+ terms: remember({
850
+ ref: randomBytes(18).toString('base64url'),
851
+ group: a.group,
852
+ ...groupWords(a.group),
853
+ hotelId: a.hotel.id,
854
+ hotelName: a.hotel.name,
855
+ ...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
856
+ roomName: a.roomName,
857
+ stay: a.stay,
858
+ rooms: a.rooms,
859
+ total: a.total,
860
+ text: asked.text,
861
+ source: 'booking',
862
+ more: true,
863
+ askedByGroup: step,
864
+ until: iso(now() + TERMS_MS),
865
+ owner: a.acct.owner,
866
+ key: a.acct.key,
867
+ ask: {
868
+ roomId: a.roomId,
869
+ guest: a.guest,
870
+ roomTerms: a.agreed,
871
+ token: asked.token,
872
+ step,
873
+ },
874
+ }),
875
+ };
876
+ }
877
+ log(a.groupStep
878
+ ? `[otaless] booking at ${a.group} answered ${what} again, after the guest ${step === 'terms' ? 'agreed to its terms' : 'confirmed it'} - not booked`
879
+ : `[otaless] booking at ${a.group} answered ${what} with no ${step === 'terms' ? 'terms' : 'details'} and token to show the guest - not booked (questions #${step === 'terms' ? 66 : 68})`);
880
+ const again = step === 'terms'
881
+ ? `${g.name} asked for its terms to be agreed to again after the guest agreed to them, so nothing was booked or charged.`
882
+ : `${g.name} asked for the booking to be confirmed again after the guest confirmed it, so nothing was booked or charged.`;
883
+ const none = step === 'terms'
884
+ ? `${g.name} asked for terms of its own to be agreed to, which it did not send to be shown here, so nothing was booked or charged.`
885
+ : `${g.name} asked for the booking to be confirmed in a second step, and did not send what to confirm to be shown here, so nothing was booked or charged.`;
886
+ // New codes for the card (酒店平台's next version): until then, these words.
887
+ return { failed: failedStay(a, a.groupStep ? again : none, code) };
888
+ };
535
889
  /**
536
- * Lets an order we will not hand on go at once - 14 while it waits for a
537
- * payment, 9 if it came back confirmed. ⚠️ A FAILURE TO LET IT GO NEEDS A
538
- * PERSON: it is logged as such and kept on the record.
890
+ * The terms an order is held back for (总线程 11-11, D): those kept - or,
891
+ * gone from memory (a restart), the order's own kept again until its time.
539
892
  */
540
- const release = async (a, r, why, confirmed) => {
893
+ const termsOfHeld = (r, acct) => {
894
+ if (!r.held || r.released || !r.terms || now() >= Date.parse(r.held.until))
895
+ return undefined;
896
+ // Seen in this conversation: its time running out is cancelled with this sign-in.
897
+ if (acct.owner === r.owner)
898
+ heldBy.set(r.id, acct.key);
899
+ for (const p of pending.values())
900
+ if (p.orderId === r.id && p.owner === acct.owner && now() <= Date.parse(p.until))
901
+ return view(p);
902
+ return remember({
903
+ ref: randomBytes(18).toString('base64url'),
904
+ group: r.group,
905
+ ...groupWords(r.group),
906
+ hotelId: r.hotelId,
907
+ hotelName: r.hotelName,
908
+ ...(r.hotelNames ? { hotelNames: r.hotelNames } : {}),
909
+ roomName: r.roomName,
910
+ stay: r.stay,
911
+ rooms: r.rooms,
912
+ total: r.quoted,
913
+ text: r.terms,
914
+ source: 'booking',
915
+ more: true,
916
+ changed: true,
917
+ bookingId: r.id,
918
+ confirmationCode: r.code || r.id,
919
+ until: r.held.until,
920
+ owner: r.owner,
921
+ key: acct.key,
922
+ orderId: r.id,
923
+ });
924
+ };
925
+ // ── an order cancelled at once (9; 总线程 11-11) ───────────────────────────
926
+ /** What the group's staff are told an order was cancelled for. */
927
+ const RELEASE_REASON = {
928
+ price: 'amount not as quoted',
929
+ amount: 'no amount given',
930
+ adults: 'guests not as asked',
931
+ address: 'payment page not accepted',
932
+ terms: 'terms not agreed by the guest',
933
+ };
934
+ /** Thrown where there is no sign-in at the order's group to cancel it with. */
935
+ class NotSignedIn extends Error {
936
+ name = 'not signed in there';
937
+ }
938
+ /**
939
+ * Cancels an order we will not hand on, at once - by 9, the only cancel there
940
+ * is now. Its payment page goes first, whatever comes back. ⚠️ ONE THAT DOES
941
+ * NOT CANCEL NEEDS A PERSON: logged as such, kept, listed - never paid. So
942
+ * does one with no sign-in to cancel it with (`acct` none - 总线程's review of
943
+ * 0.66.0, 1).
944
+ */
945
+ const release = async (acct, who, r, why) => {
541
946
  r.released = why;
947
+ r.held = undefined;
948
+ heldBy.delete(r.id);
949
+ payLinks.delete(r.id);
950
+ for (const [ref, p] of pending)
951
+ if (p.orderId === r.id)
952
+ pending.delete(ref);
542
953
  counts.released += 1;
543
954
  try {
544
- const done = await withSession(a.acct, a.who, (cred) => confirmed
545
- ? client.cancelBooking({
546
- unifiedOrderId: r.id,
547
- providerCode: a.group,
548
- reason: 'price or payment page not as quoted',
549
- }, cred, deps.callerOf(a.who))
550
- : client.cancelCheckout({
551
- unifiedOrderId: r.id,
552
- providerCode: a.group,
553
- reason: 'price or payment page not as quoted',
554
- }, cred, deps.callerOf(a.who)));
955
+ if (!acct)
956
+ throw new NotSignedIn();
957
+ const done = await withSession(acct, who, (cred) => client.cancelBooking({ unifiedOrderId: r.id, providerCode: r.group, reason: RELEASE_REASON[why] }, cred, deps.callerOf(who)));
555
958
  // Not said to be done - refused, or not known: a person, as any failure here.
556
959
  if (cancelOutcome(done) !== 'done')
557
960
  throw new Error('not cancelled');
@@ -562,164 +965,294 @@ export const createOtalessBookings = (deps) => {
562
965
  }
563
966
  catch (err) {
564
967
  r.releaseFailed = true;
968
+ r.needsPerson = 'release';
969
+ r.needsPersonAt = iso();
565
970
  counts.releaseFailed += 1;
566
- log(`[otaless] NEEDS A PERSON: order ${forTheLog(r.id)} at ${a.group} (${why}) could not be let go: ${err instanceof Error ? err.name : 'error'}`);
971
+ log(`[otaless] NEEDS A PERSON: order ${forTheLog(r.id)} at ${r.group} (${why}) could not be cancelled: ${err instanceof Error ? err.name : 'error'}`);
567
972
  put(r);
568
973
  return false;
569
974
  }
570
975
  };
571
- /** What 13 answered, settled: terms to agree to, an order to hand on, or none. */
572
- const settle = async (a, w) => {
976
+ const releasedWhy = (g, why) => ({
977
+ price: `${g} asked for a different amount than the price the guest was shown`,
978
+ amount: `${g} did not say what it would charge`,
979
+ adults: `${g} took the order for another number of guests than the guest chose`,
980
+ address: `${g} sent a payment page on an address this connector does not send guests to`,
981
+ terms: `${g} asked for terms of its own to be agreed to when it was ordered, which cannot be shown here`,
982
+ })[why];
983
+ /** An order made that is not the one asked for: cancelled at once, and said as it came out. */
984
+ const letGo = async (a, r, why) => {
985
+ const g = deps.groupOf(a.group).name;
986
+ const gone = await release(a.acct, a.who, r, why);
987
+ if (gone)
988
+ return {
989
+ failed: failedStay(a, `${releasedWhy(g, why)}, so the order was cancelled at once and nothing was charged.${why === 'price' ? ' Price the trip again.' : ''}`,
990
+ // For the card to say in the guest's language (酒店平台 0.66.0, `NoRoomsCode`).
991
+ why === 'price' || why === 'amount' ? 'price-changed' : 'order-cancelled'),
992
+ };
993
+ // ⚠️ SAID AS IT IS: an order stands at the group that is not the one asked
994
+ // for - never "not booked". Listed, with no page to pay it on.
995
+ return {
996
+ failed: failedStay(a, `${releasedWhy(g, why)}, and cancelling the order it made did not go through just now - a person is looking at it. It is in the guest's bookings, with no payment page: it must not be paid.`, 'needs-person'),
997
+ };
998
+ };
999
+ // ── an order held for terms the group answered with (总线程 11-11, D) ──────
1000
+ const later = deps.later ??
1001
+ ((ms, fn) => {
1002
+ const t = setTimeout(fn, ms);
1003
+ t.unref?.();
1004
+ });
1005
+ /**
1006
+ * The conversation each held order was last seen in, by order id - in memory
1007
+ * only: whose sign-in its time running out is cancelled with.
1008
+ */
1009
+ const heldBy = new Map();
1010
+ /** A held order whose time ran out - or is past it already (not a number): due. */
1011
+ const heldOver = (r) => !(now() < Date.parse(r.held?.until ?? ''));
1012
+ /**
1013
+ * A held order's time ran out: cancelled with the guest's sign-in at its
1014
+ * group. ⚠️ NOT LEFT STANDING (总线程's review of 0.66.0, 1): not signed in
1015
+ * there now - or not known in whose conversation, after a restart - it
1016
+ * needs a person, said as such on the log, as any order that did not cancel.
1017
+ */
1018
+ const lapse = async (id) => {
1019
+ const r = orders.get(id);
1020
+ if (!r?.held || r.released || !heldOver(r))
1021
+ return;
1022
+ const key = heldBy.get(id);
1023
+ const who = { sessionId: key ?? '' };
1024
+ const acct = key ? accountFor(who, r.group) : undefined;
1025
+ await release(acct && acct.owner === r.owner ? acct : undefined, who, r, 'terms');
1026
+ };
1027
+ /** A held order's time, kept: `lapse` just after it - for whichever conversation saw it last. */
1028
+ const holdFor = (r, key) => {
1029
+ if (key)
1030
+ heldBy.set(r.id, key);
1031
+ const left = Date.parse(r.held?.until ?? '') - now();
1032
+ later(Number.isFinite(left) && left > 0 ? left + 1_000 : 0, () => {
1033
+ lapse(r.id).catch(() => undefined);
1034
+ });
1035
+ };
1036
+ /** This guest's held orders whose time ran out - before their timer: cancelled now. */
1037
+ const sweep = async (who) => {
1038
+ for (const r of [...orders.values()]) {
1039
+ if (!r.held || r.released || !heldOver(r))
1040
+ continue;
1041
+ const acct = accountFor(who, r.group);
1042
+ if (acct && acct.owner === r.owner)
1043
+ await release(acct, who, r, 'terms');
1044
+ }
1045
+ };
1046
+ // ⚠️ HELD ORDERS KEPT ACROSS A RESTART (总线程's review of 0.66.0, 1): their
1047
+ // timers went with the process. Each gets its own again - one whose time ran
1048
+ // out while it was down, at once - so none is left standing at its group.
1049
+ for (const r of [...orders.values()])
1050
+ if (r.held && !r.released)
1051
+ holdFor(r);
1052
+ /** What 8 answered, settled: an order to hand on, one held for new terms, or none. */
1053
+ const settle = async (a, w, pairs) => {
573
1054
  const g = deps.groupOf(a.group);
574
1055
  const status = String(w?.status ?? '')
575
1056
  .trim()
576
1057
  .toUpperCase();
577
- // ── terms the guest must agree to (§12.4) ──
578
- if (/TERMS/.test(status)) {
579
- const words = firstText(w?.extraData, TERMS_TEXT_KEYS);
580
- const token = firstText(w?.extraData, TERMS_TOKEN_KEYS);
581
- // ⚠️ NEVER TERMS NOBODY SAW: none sent, or none to send the agreement back with - nothing.
582
- if (!words || !token || token.length > 512 || words.length > TERMS_MAX)
583
- return {
584
- failed: failedStay(a, `${g.name} asks for the guest's agreement to terms it did not send in full, so nothing was booked or charged.`),
585
- };
586
- const mine = [...pending.values()].filter((p) => p.owner === a.acct.owner);
587
- for (const p of mine.slice(0, Math.max(0, mine.length - PENDING_PER_ACCOUNT + 1)))
588
- pending.delete(p.ref);
589
- const ref = randomBytes(18).toString('base64url');
590
- const terms = {
591
- ref,
592
- group: a.group,
593
- groupName: g.name,
594
- ...(g.names ? { groupNames: g.names } : {}),
595
- hotelId: a.hotel.id,
596
- hotelName: a.hotel.name,
597
- ...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
598
- roomName: a.roomName,
599
- stay: a.stay,
600
- rooms: a.rooms,
601
- total: a.pairs.orig,
602
- text: words,
603
- until: iso(now() + TERMS_MS),
604
- };
605
- pending.set(ref, {
606
- ...terms,
607
- owner: a.acct.owner,
608
- key: a.acct.key,
609
- tokenOfTerms: token,
610
- body: a.body,
611
- pairs: a.pairs,
612
- roomId: a.roomId,
613
- ...(a.terms ? { terms: a.terms } : {}),
614
- at: now(),
615
- });
616
- while (pending.size > PENDING_MAX) {
617
- const first = pending.keys().next().value;
618
- if (first === undefined)
619
- break;
620
- pending.delete(first);
621
- }
622
- counts.termsSent += 1;
623
- return { terms };
624
- }
1058
+ const id = text(w?.unifiedOrderId);
625
1059
  // ── refused ──
626
- const err = text(w?.errorMessage);
1060
+ const err = text(w?.errorMessage ?? undefined);
627
1061
  if (!w || w.success === false || status === 'FAILED' || err) {
628
1062
  if (err)
629
- log(`[otaless] checkout at ${a.group} refused: "${forTheLog(err, [a.guest.name, a.guest.email, a.guest.phone])}"`);
1063
+ log(`[otaless] booking at ${a.group} refused: "${forTheLog(err, [a.guest.name, a.guest.email, a.guest.phone])}"`);
630
1064
  return {
631
1065
  failed: failedStay(a, `${g.name} did not take the booking, so nothing was booked or charged.`),
632
1066
  };
633
1067
  }
634
- const id = text(w.unifiedOrderId);
635
- const code = text(w.originalOrderId) ?? '';
636
- const page = text(w.checkoutUrl);
637
- // ⚠️ "CONFIRMED" WITH A PAYMENT PAGE IS WAITING FOR ITS PAYMENT (questions #53,
638
- // the document's own example): paid is what 15 says, never this status.
639
- const confirmed = !page && (status === 'CONFIRMED' || status === 'PAID');
640
1068
  if (!id) {
1069
+ // Terms of its own to agree to, and no order (questions #66).
1070
+ const step = /TERMS/.test(status) ? 'terms' : stepAsked(status);
1071
+ if (step)
1072
+ return groupAsked(a, step, w, pairs);
641
1073
  // Something may be held, under a number we were not told: kept to look for (12).
642
- const r = recordOf(a, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
1074
+ const r = recordOf(a, pairs, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
643
1075
  put(r);
644
- log(`[otaless] checkout at ${a.group} answered with no order id (status ${forTheLog(status || '?')})`);
1076
+ log(`[otaless] booking at ${a.group} answered with no order id (status ${forTheLog(status || '?')})`);
645
1077
  return { booked: toBooking(r) };
646
1078
  }
647
- const r = recordOf(a, id, code, confirmed ? 'confirmed' : 'awaiting-payment');
648
- if (w.cancelPolicy && text(w.cancelPolicy))
649
- r.terms = text(w.cancelPolicy);
1079
+ const code = text(w.originalOrderId) ?? '';
1080
+ const page = text(w.checkoutUrl ?? undefined);
1081
+ // ⚠️ "CONFIRMED" WITH A PAYMENT PAGE IS WAITING FOR ITS PAYMENT (questions
1082
+ // #53, #61 (1) - 8's own example): paid is what 15 says, never this status.
1083
+ const confirmed = !page && (status === 'CONFIRMED' || status === 'PAID');
1084
+ const r = recordOf(a, pairs, id, code, confirmed ? 'confirmed' : 'awaiting-payment');
650
1085
  const charged = moneyOf(w.totalAmount, w.currency);
651
1086
  if (charged)
652
1087
  r.charged = charged;
653
- // ── the amount (总线程 11-10: either of the quote's two) ──
654
- if (!charged || !(same(charged, a.pairs.orig) || same(charged, a.pairs.usd))) {
655
- const gone = await release(a, r, charged ? 'price' : 'amount', confirmed);
656
- log(`[otaless] checkout at ${a.group} asked ${charged ? `${charged.currency} ${charged.minor}` : 'no amount'}, quoted ${a.pairs.orig.currency} ${a.pairs.orig.minor} / USD ${a.pairs.usd.minor} - released`);
657
- // ⚠️ CONFIRMED, AND NOT UNDONE: a stay is held at another amount - said
658
- // as that, and listed, never as "not booked" (a person is told: the log).
659
- if (confirmed && !gone)
660
- return {
661
- failed: failedStay(a, `${g.name} confirmed it at a different amount than the price the guest was shown, and it could not be undone here just now - a person is looking at it; it is in the guest's bookings.`, 'price-changed'),
662
- };
663
- return {
664
- failed: failedStay(a, charged
665
- ? `${g.name} asked for a different amount than the price the guest was shown, so it was not booked at it and nothing was charged - price the trip again.`
666
- : `${g.name} did not say what it would charge, so it was not booked and nothing was charged.`, 'price-changed'),
667
- };
1088
+ if (/TERMS/.test(status)) {
1089
+ log(`[otaless] booking at ${a.group} made ${forTheLog(id)} asking for terms - cancelled`);
1090
+ return letGo(a, r, 'terms');
668
1091
  }
669
- // ── the payment page (总线程 11-10, rule 5) ──
1092
+ // ── the amount (总线程 11-10, 12.9 #2): either of this quote's two, to the cent ──
1093
+ if (!charged || !(same(charged, pairs.orig) || same(charged, pairs.usd))) {
1094
+ log(`[otaless] booking at ${a.group} asked ${charged ? `${charged.currency} ${charged.minor}` : 'no amount'}, quoted ${pairs.orig.currency} ${pairs.orig.minor}${pairs.usd ? ` / USD ${pairs.usd.minor}` : ''} - cancelled`);
1095
+ return letGo(a, r, charged ? 'price' : 'amount');
1096
+ }
1097
+ // ── the guests (总线程 11-11, C - questions #62): said, it is the number quoted ──
1098
+ const adults = num(w.adultCount ?? w.adults);
1099
+ if (adults !== undefined && adults !== a.stay.guests) {
1100
+ log(`[otaless] booking at ${a.group} is for ${adults} adult(s), quoted for ${a.stay.guests} - cancelled`);
1101
+ return letGo(a, r, 'adults');
1102
+ }
1103
+ // ── the payment page (总线程 11-10, rule 5; 11-11, B) ──
670
1104
  if (page) {
671
- const ok = payPageOf(page, deps.checkoutHosts);
1105
+ const ok = payPageOf(page, deps.checkoutHosts, { id, code });
672
1106
  if (!ok) {
673
- await release(a, r, 'address', confirmed);
674
- log(`[otaless] checkout at ${a.group} sent a payment page on ${hostForLog(page)}, not on the list - released`);
675
- return {
676
- failed: failedStay(a, `${g.name} sent a payment page on an address this connector does not send guests to, so it was not booked and nothing was charged.`),
677
- };
1107
+ // ⚠️ ITS HOST ALONE ON THE LOG (总线程's review of 0.66.0, 4) - never its
1108
+ // path or query: either may carry a payment token.
1109
+ log(`[otaless] booking at ${a.group} sent a payment page on ${hostForLog(page)}, not on the list or not this order's - cancelled`);
1110
+ // On a host listed: its shape, no value (总线程 11-11 late) - to write
1111
+ // the exact `{order}` entry from the first real one.
1112
+ if (onListedHost(page, deps.checkoutHosts))
1113
+ log(`[otaless] that page's shape: ${pageShape(page, { id, code })}`);
1114
+ return letGo(a, r, 'address');
678
1115
  }
679
1116
  r.payHost = ok.host;
680
1117
  payLinks.set(id, ok.url);
681
- const hold = num(w.extraData?.hold_minutes);
682
- if (hold !== undefined && hold > 0 && hold <= 24 * 60)
683
- r.payBy = iso(now() + hold * 60_000);
684
1118
  }
685
1119
  else if (!confirmed) {
686
1120
  // Waiting, and no page to pay on: nothing to hand on - 15 says when it is paid.
687
- log(`[otaless] checkout at ${a.group} is ${forTheLog(status || '?')} with no payment page`);
1121
+ log(`[otaless] booking at ${a.group} is ${forTheLog(status || '?')} with no payment page`);
688
1122
  }
1123
+ // ── the terms it came with (总线程 11-11, D) ──
1124
+ const said = text(w.cancelPolicy ?? undefined);
1125
+ if (said && said.length > TERMS_MAX) {
1126
+ log(`[otaless] booking at ${a.group} came with terms too long to show - cancelled`);
1127
+ return letGo(a, r, 'terms');
1128
+ }
1129
+ if (said &&
1130
+ termsKey(said) !== termsKey(a.agreed) &&
1131
+ !(a.groupStep?.step === 'terms' && termsKey(said) === termsKey(a.groupStep.text))) {
1132
+ // ⚠️ NOT THE TERMS AGREED TO: the order stands, its payment page is held
1133
+ // back until the guest agrees to these too - not agreed, or not in time,
1134
+ // it is cancelled.
1135
+ r.terms = said;
1136
+ r.held = { until: iso(now() + TERMS_MS) };
1137
+ put(r);
1138
+ log(`[otaless] booking ${forTheLog(id)} at ${a.group} came with other terms than the guest agreed to - its payment page held back`);
1139
+ holdFor(r, a.acct.key);
1140
+ const t = termsOfHeld(r, a.acct);
1141
+ return t ? { terms: t } : { booked: toBooking(r) };
1142
+ }
1143
+ if (said)
1144
+ r.terms = said;
689
1145
  put(r);
690
1146
  return { booked: toBooking(r) };
691
1147
  };
692
- /** Asks 13 for one stay, and settles it. */
693
- const ask = async (a) => {
1148
+ class Moved extends Error {
1149
+ }
1150
+ class NotPriced extends Error {
1151
+ busy;
1152
+ constructor(busy) {
1153
+ super('not priced');
1154
+ this.busy = busy;
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Orders one stay whose terms the guest agreed to: priced again in their own
1159
+ * session, held to the price they were shown - and only then 8, in that same
1160
+ * session (总线程 11-11, C). A 4012 on either is one new handshake and one more
1161
+ * try of both.
1162
+ */
1163
+ const place = async (a) => {
694
1164
  const g = deps.groupOf(a.group);
1165
+ let pairs;
1166
+ /** What 8 itself threw, if it did: only that may have made an order. */
1167
+ let fromBook;
695
1168
  let w;
696
1169
  try {
697
- w = await withSession(a.acct, a.who, (cred) => client.checkout(a.body, cred, deps.callerOf(a.who)));
1170
+ w = await withSession(a.acct, a.who, async (cred) => {
1171
+ fromBook = undefined;
1172
+ let priced;
1173
+ try {
1174
+ priced = await deps.quoteIn(a.hotel, a.roomId, a.stay, a.rooms, cred, a.who);
1175
+ }
1176
+ catch (err) {
1177
+ if (isCode(err, NOT_SIGNED_IN) || isCode(err, CHANNEL_SESSION_EXPIRED))
1178
+ throw err;
1179
+ throw new NotPriced(err instanceof OtalessBusy);
1180
+ }
1181
+ const orig = moneyOf(priced.data?.originalAmount, priced.data?.originalCurrency);
1182
+ // ⚠️ THE PRICE THE GUEST SAW, TO THE CENT, OR 8 IS NOT CALLED.
1183
+ if (!orig || !same(orig, a.total))
1184
+ throw new Moved('moved');
1185
+ const usd = text(priced.data?.settlementCurrency)?.toUpperCase() === 'USD'
1186
+ ? moneyOf(priced.data?.settlementAmount, 'USD')
1187
+ : undefined;
1188
+ pairs = { orig, ...(usd && usd.minor > 0 ? { usd } : {}) };
1189
+ // ⚠️ THE SESSION THE QUOTE RAN IN - as it wrote it back, if it did.
1190
+ const session = priced.session ?? cred.session;
1191
+ const body = {
1192
+ unifiedHotelId: a.hotel.id,
1193
+ // ⚠️ AS /rooms SENT IT, prefix and all (questions #53) - never cut to its tail.
1194
+ unifiedRoomId: a.roomId,
1195
+ guestName: a.guest.name,
1196
+ guestPhone: a.guest.phone ?? '',
1197
+ ...(a.guest.email ? { guestEmail: a.guest.email } : {}),
1198
+ checkIn: a.stay.checkIn,
1199
+ checkOut: a.stay.checkOut,
1200
+ roomCount: a.rooms,
1201
+ // Only after the guest agreed to the terms 8 asked for (questions #66).
1202
+ ...(a.groupStep?.step === 'terms'
1203
+ ? { termsToken: a.groupStep.token, termsAccepted: true }
1204
+ : {}),
1205
+ ...(a.groupStep?.step === 'confirm'
1206
+ ? { confirmToken: a.groupStep.token, confirmed: true }
1207
+ : {}),
1208
+ };
1209
+ let booked;
1210
+ try {
1211
+ booked = await client.book(body, { token: cred.token, ...(session ? { session } : {}) }, deps.callerOf(a.who));
1212
+ }
1213
+ catch (err) {
1214
+ fromBook = err;
1215
+ throw err;
1216
+ }
1217
+ const back = booked.session ?? priced.session;
1218
+ return { data: booked.data, ...(back ? { session: back } : {}) };
1219
+ });
698
1220
  }
699
1221
  catch (err) {
700
- if (err instanceof OtalessBusy)
1222
+ if (err instanceof Moved)
1223
+ return {
1224
+ failed: failedStay(a, `${g.name}'s price moved since the guest saw it, so nothing was booked - price the trip again.`, 'price-changed'),
1225
+ };
1226
+ if (err instanceof NotPriced)
701
1227
  return {
702
- failed: failedStay(a, `Not sent to ${g.name}: too many requests just now - ask again in a minute.`, 'limited'),
1228
+ failed: err.busy
1229
+ ? limited(a, g.name)
1230
+ : failedStay(a, `${g.name} did not price it again just now, so nothing was booked.`, 'unreachable'),
703
1231
  };
704
- // A repeat-submit refusal (10014) of a write: an identical one went in a
705
- // moment ago, and whether it made an order is not known - the same.
706
- if (unanswered(err) || isCode(err, REPEAT_SUBMIT)) {
707
- // ⚠️ NOT SENT AGAIN (§12.1): it may have been made. Kept to look for in
708
- // the group's order list (12), and said as not known.
709
- const r = recordOf(a, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
1232
+ if (err instanceof OtalessBusy)
1233
+ return { failed: limited(a, g.name) };
1234
+ // ⚠️ NOT SENT AGAIN (§12.1): 8 itself not answering - or refusing it as a
1235
+ // repeat of one that went in a moment ago (10014) - may have made it.
1236
+ // Kept to look for in the group's order list (12), said as not known.
1237
+ if (err === fromBook && (unanswered(err) || isCode(err, REPEAT_SUBMIT))) {
1238
+ const r = recordOf(a, pairs ?? { orig: a.total }, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
710
1239
  put(r);
711
1240
  return { booked: toBooking(r) };
712
1241
  }
1242
+ // ⚠️ 8 REFUSED FOR TERMS (robin 11-11 18:30, Ascott: code 500 "terms_required").
1243
+ const step = err === fromBook && err instanceof OtalessError ? stepAsked(err.answer?.msg) : undefined;
1244
+ if (step)
1245
+ return groupAsked(a, step, err instanceof OtalessError ? err.answer?.data : undefined, pairs ?? { orig: a.total });
713
1246
  if (err instanceof OtalessError)
714
1247
  return {
715
1248
  failed: failedStay(a, `${g.name} did not take the booking, so nothing was booked or charged.`),
716
1249
  };
717
1250
  throw err;
718
1251
  }
719
- return settle(a, w);
1252
+ return settle(a, w, pairs ?? { orig: a.total });
720
1253
  };
721
1254
  /**
722
- * An order row that could be an order 13 did not answer for: of the group,
1255
+ * An order row that could be an order 8 did not answer for: of the group,
723
1256
  * for those nights, not one of ours, and holding something (not cancelled,
724
1257
  * failed, refunded or closed).
725
1258
  */
@@ -737,6 +1270,100 @@ export const createOtalessBookings = (deps) => {
737
1270
  .trim()
738
1271
  .toUpperCase());
739
1272
  };
1273
+ const stayGuard = async (acct, who, label, roomRef, rooms, lockKey) => {
1274
+ const group = acct.group;
1275
+ const { hotel, stay } = label;
1276
+ const name = deps.groupOf(group).name;
1277
+ const sameStay = (o) => o.owner === acct.owner &&
1278
+ o.hotelId === hotel.id &&
1279
+ o.roomId === roomRef &&
1280
+ o.stay.checkIn === stay.checkIn &&
1281
+ o.stay.checkOut === stay.checkOut &&
1282
+ o.rooms === rooms;
1283
+ // A person's: said paid at another amount, or cancelled at once and not undone.
1284
+ const people = [...orders.values()].filter((o) => sameStay(o) && o.needsPerson && !o.rebookable);
1285
+ // ⚠️ THE WAY OUT (总线程's review of 0.66.0, 6), as for an order that could
1286
+ // not be verified: with a person this long and still not settled, the stay
1287
+ // is no longer held back. The guest is told first, as it is - it may stand
1288
+ // at the group, check there; asked again, a new booking is made.
1289
+ if (people.length &&
1290
+ people.every((o) => now() - Date.parse(o.needsPersonAt ?? o.createdAt) >= NEEDS_PERSON_GIVE_UP_MS)) {
1291
+ for (const o of people) {
1292
+ o.rebookable = true;
1293
+ put(o);
1294
+ }
1295
+ log(`[otaless] ${people.length} order(s) at ${group} still with a person after ${NEEDS_PERSON_GIVE_UP_MS / 3_600_000}h - the stay is no longer held back`);
1296
+ return {
1297
+ failed: failedStay(label, `An earlier booking of this stay is still with a person to sort out with ${name}, and it may stand there: the guest should check with ${name} before booking it again. Nothing new was booked this time - asked again, a new booking is made.`,
1298
+ // New for the card (酒店平台's next version): until then, these words.
1299
+ 'earlier-needs-person-overdue'),
1300
+ };
1301
+ }
1302
+ const person = people[0];
1303
+ if (person)
1304
+ return {
1305
+ failed: failedStay(label, person.needsPerson === 'release'
1306
+ ? `An earlier booking of this stay could not be cancelled at ${name} and needs a person to check it, so nothing new was booked.`
1307
+ : `An earlier booking of this stay needs a person to check its payment with ${name}, so nothing new was booked.`,
1308
+ // For the card to say in the guest's language (酒店平台 0.63.2, `NoRoomsCode`).
1309
+ 'earlier-needs-person'),
1310
+ };
1311
+ const mine = [...orders.values()].filter((o) => sameStay(o) && !o.released);
1312
+ // Held for terms the group answered with: those terms, again - not a second order.
1313
+ const held = mine.find((o) => o.held);
1314
+ if (held) {
1315
+ const t = termsOfHeld(held, acct);
1316
+ if (t)
1317
+ return { terms: t };
1318
+ }
1319
+ // ⚠️ AN EARLIER ORDER OF THIS STAY THAT MAY HAVE BEEN MADE IS LOOKED FOR
1320
+ // FIRST, HOWEVER OLD (总线程's review of 0.63.0, 5): the group's order list
1321
+ // (12) is read; not found there - or not readable - nothing new is sent.
1322
+ const unknown = mine.filter((o) => o.status === 'unconfirmed' && !o.unverifiable);
1323
+ if (unknown.length) {
1324
+ const rows = await lookAtOrders(acct, who, group, unknown);
1325
+ const still = unknown.filter((o) => o.status === 'unconfirmed');
1326
+ // ⚠️ THE WAY OUT (总线程's re-review of 0.63.1, 1): long enough after it
1327
+ // was asked for - past any hold on an unpaid room - and with nothing in
1328
+ // the group's list that could be it, the stay is no longer held back.
1329
+ // The guest is told first, as it is; asked again, a new booking is made.
1330
+ // (Not by the payment status, 15: an order 8 never named has no id to
1331
+ // ask it by - its list, 12, is all there is.)
1332
+ if (rows &&
1333
+ still.length &&
1334
+ still.every((o) => now() - Date.parse(o.createdAt) >= UNCONFIRMED_GIVE_UP_MS) &&
1335
+ !rows.some((row) => couldBe(row, group, stay))) {
1336
+ for (const o of still) {
1337
+ o.unverifiable = true;
1338
+ put(o);
1339
+ }
1340
+ log(`[otaless] ${still.length} order(s) 8 did not answer for at ${group} could not be verified - the stay is no longer held back`);
1341
+ return {
1342
+ failed: 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'),
1343
+ };
1344
+ }
1345
+ if (!rows || still.length)
1346
+ return {
1347
+ failed: 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.`),
1348
+ };
1349
+ }
1350
+ // A second press, a lost answer, an order found in the list: the order
1351
+ // already made for this stay, while it may still be paid. ⚠️ WITH NO TIME
1352
+ // TO PAY BY, THE PAYMENT STATUS (15) IS ASKED FIRST (总线程's re-review of
1353
+ // 0.63.1, 2): closed, it lapses and its link is not handed on again; not
1354
+ // known, it is held to `ASSUMED_HOLD_MS`.
1355
+ for (const o of mine.filter((x) => x.status === 'awaiting-payment' && !x.held)) {
1356
+ if (!o.payBy)
1357
+ await lookAtPayment(acct, who, o, true);
1358
+ if (o.status === 'awaiting-payment' && !o.needsPerson && now() < payableUntil(o))
1359
+ return { reuse: o };
1360
+ }
1361
+ if (inFlight.has(lockKey))
1362
+ return {
1363
+ failed: failedStay(label, 'This stay is being booked already - look at the bookings in a moment rather than booking it again.'),
1364
+ };
1365
+ return undefined;
1366
+ };
740
1367
  const requestBooking = async (trip, guest, who) => {
741
1368
  // ⚠️ SIGNED IN AT EVERY GROUP OF THE TRIP, OR NOTHING IS SENT (robin 11-10:
742
1369
  // one sign-in per group, the backend's own) - the whole trip is refused
@@ -751,13 +1378,14 @@ export const createOtalessBookings = (deps) => {
751
1378
  const phone = guest.phone?.trim() ?? '';
752
1379
  if (!name)
753
1380
  throw refusal('guest', "Nothing was booked: the guest's name is needed.");
754
- // The backend's `guestPhone` is required (13).
1381
+ // The backend's `guestPhone` is required (8).
755
1382
  if (!phone)
756
1383
  throw refusal('guest', "Nothing was booked: the guest's phone number is needed.");
757
1384
  const long = guestTooLong({ name, email: guest.email ?? '', phone });
758
1385
  if (long.length)
759
1386
  throw refusal('guest', `Nothing was booked: ${long.join(', ')}.`);
760
1387
  const g0 = { ...guest, name, phone, email: guest.email?.trim() ?? '' };
1388
+ await sweep(who);
761
1389
  const failed = [];
762
1390
  for (const l of trip.lines) {
763
1391
  if (l.kind === 'extra') {
@@ -810,154 +1438,38 @@ export const createOtalessBookings = (deps) => {
810
1438
  continue;
811
1439
  }
812
1440
  const lockKey = `${acct.owner}|${hotel.id}|${line.roomRef}|${stay.checkIn}|${stay.checkOut}|${rooms}`;
813
- const sameStay = (o) => o.owner === acct.owner &&
814
- !o.released &&
815
- o.hotelId === hotel.id &&
816
- o.roomId === line.roomRef &&
817
- o.stay.checkIn === stay.checkIn &&
818
- o.stay.checkOut === stay.checkOut &&
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;
1441
+ const guard = await stayGuard(acct, who, label, line.roomRef, rooms, lockKey);
1442
+ if (guard) {
1443
+ if ('failed' in guard)
1444
+ failed.push(guard.failed);
1445
+ else if ('reuse' in guard) {
1446
+ booked.push(toBooking(guard.reuse));
1447
+ reused.push(guard.reuse.id);
856
1448
  }
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
- }
872
- if (before) {
873
- booked.push(toBooking(before));
874
- reused.push(before.id);
1449
+ else
1450
+ terms.push(guard.terms);
875
1451
  continue;
876
1452
  }
877
- if (inFlight.has(lockKey)) {
878
- failed.push(failedStay(label, 'This stay is being booked already - look at the bookings in a moment rather than booking it again.'));
1453
+ const agreed = text(line.terms) ?? '';
1454
+ // ⚠️ WORD FOR WORD OR NOT AT ALL: terms too long to show are not cut.
1455
+ if (agreed.length > TERMS_MAX) {
1456
+ failed.push(failedStay(label, `${deps.groupOf(group).name}'s terms for this room are too long to show in full here, so nothing was booked.`));
879
1457
  continue;
880
1458
  }
881
- inFlight.add(lockKey);
882
- try {
883
- const wire = await deps.quoteWire(hotel, line.roomRef, stay, rooms, who);
884
- const orig = moneyOf(wire.originalAmount, wire.originalCurrency);
885
- const usd = text(wire.settlementCurrency)?.toUpperCase() === 'USD'
886
- ? moneyOf(wire.settlementAmount, 'USD')
887
- : undefined;
888
- if (!orig || !same(orig, line.total)) {
889
- failed.push(failedStay(label, `${deps.groupOf(group).name}'s price moved while it was being booked, so nothing was booked - price the trip again.`, 'price-changed'));
890
- continue;
891
- }
892
- // ⚠️ NO USD FIGURE, NO ORDER: 13 is held to `expectedChargeUsd` (§12.1).
893
- if (!usd || usd.minor <= 0) {
894
- failed.push(failedStay(label, `${deps.groupOf(group).name} gave no USD figure for this price, so it cannot be booked with its price held - nothing was booked.`));
895
- continue;
896
- }
897
- const body = {
898
- unifiedHotelId: hotel.id,
899
- // ⚠️ AS /rooms SENT IT, prefix and all (questions #53: the dictionary says
900
- // `{provider}:{roomId}`, the example has none) - never cut to its tail.
901
- unifiedRoomId: line.roomRef,
902
- providerCode: group,
903
- guestName: g0.name,
904
- guestPhone: phone,
905
- ...(g0.email ? { guestEmail: g0.email } : {}),
906
- checkIn: stay.checkIn,
907
- checkOut: stay.checkOut,
908
- roomCount: rooms,
909
- adults: Math.max(1, stay.guests),
910
- // ⚠️ ALWAYS FALSE (总线程 11-10, rule 3): never the backend's automatic agreement.
911
- termsAccepted: false,
912
- expectedChargeUsd: usd.minor / 100,
913
- };
914
- const out = await ask({
915
- acct,
916
- who,
917
- hotel,
918
- group,
919
- roomId: line.roomRef,
920
- roomName: line.title,
921
- stay,
922
- rooms,
923
- ...(line.terms ? { terms: line.terms } : {}),
924
- guest: g0,
925
- pairs: { orig, usd },
926
- body,
927
- });
928
- if (out.booked)
929
- booked.push(out.booked);
930
- if (out.failed)
931
- failed.push(out.failed);
932
- if (out.terms)
933
- terms.push(out.terms);
934
- }
935
- catch (err) {
936
- const name = deps.groupOf(group).name;
937
- // Its price could not be read again just now: this stay, not the trip.
938
- if (err instanceof OtalessBusy)
939
- failed.push(failedStay(label, `Not sent to ${name}: too many requests just now - ask again in a minute.`, 'limited'));
940
- else if (err instanceof OtalessError)
941
- failed.push(failedStay(label, `${name} did not price it again just now, so nothing was booked.`, 'unreachable'));
942
- // ⚠️ A STAY BOOKED IS NEVER DROPPED FROM THE ANSWER (the seam's rule): a
943
- // refusal on a later stay - a session or a sign-in over - is said for that
944
- // stay. With nothing booked yet, the whole ask is refused as it came.
945
- else if (!booked.length && !terms.length)
946
- throw err;
947
- else
948
- failed.push({
949
- ...failedStay(label, err instanceof Error && 'code' in err
950
- ? err.message
951
- : `${name} did not take it, so nothing was booked.`),
952
- // A later stay's sign-in over: the group to sign in at again, as the refusal names it.
953
- ...(Array.isArray(err.groups)
954
- ? { groups: [...err.groups] }
955
- : {}),
956
- });
957
- }
958
- finally {
959
- inFlight.delete(lockKey);
960
- }
1459
+ // ⚠️ NOTHING IS ORDERED YET (§15.1): the terms first, for the guest to agree to.
1460
+ terms.push(termsBefore({
1461
+ acct,
1462
+ who,
1463
+ hotel,
1464
+ group,
1465
+ roomId: line.roomRef,
1466
+ roomName: line.title,
1467
+ stay,
1468
+ rooms,
1469
+ agreed,
1470
+ guest: g0,
1471
+ total: line.total,
1472
+ }));
961
1473
  }
962
1474
  return {
963
1475
  booked,
@@ -970,8 +1482,8 @@ export const createOtalessBookings = (deps) => {
970
1482
  ...(terms.length ? { terms } : {}),
971
1483
  };
972
1484
  };
973
- // ── terms agreed to (§12.4) ───────────────────────────────────────────────
974
- /** Terms waiting for this guest - signed in now at their group, as the same owner. */
1485
+ // ── terms agreed to (§15.1, 15.2) ─────────────────────────────────────────
1486
+ /** Terms waiting for this guest - signed in now at their group, as the same owner, in time. */
975
1487
  const pendingFor = (ref, who) => {
976
1488
  const p = pending.get(ref);
977
1489
  if (!p)
@@ -979,67 +1491,93 @@ export const createOtalessBookings = (deps) => {
979
1491
  const acct = accountFor(who, p.group);
980
1492
  if (!acct || p.owner !== acct.owner)
981
1493
  return undefined;
982
- if (now() - p.at > TERMS_MS) {
1494
+ if (now() > Date.parse(p.until)) {
983
1495
  pending.delete(ref);
984
1496
  return undefined;
985
1497
  }
986
1498
  return { p, acct };
987
1499
  };
988
- const view = (p) => ({
989
- ref: p.ref,
990
- group: p.group,
991
- groupName: p.groupName,
992
- ...(p.groupNames ? { groupNames: p.groupNames } : {}),
993
- hotelId: p.hotelId,
994
- hotelName: p.hotelName,
995
- ...(p.hotelNames ? { hotelNames: p.hotelNames } : {}),
996
- roomName: p.roomName,
997
- stay: p.stay,
998
- rooms: p.rooms,
999
- total: p.total,
1000
- text: p.text,
1001
- until: p.until,
1002
- });
1500
+ const termsGone = () => refusal('terms-gone', 'Those terms are no longer waiting to be agreed to (they are kept ten minutes, and agreed to once) - nothing more was done; ask to book again.');
1003
1501
  const acceptTerms = async (ref, who) => {
1004
1502
  const found = pendingFor(ref, who);
1005
1503
  if (!found)
1006
- throw refusal('terms-gone', 'Those terms are no longer waiting to be agreed to (they are kept ten minutes, and agreed to once) - nothing was booked; ask to book again.');
1504
+ throw termsGone();
1007
1505
  const { p, acct } = found;
1008
- // ⚠️ ONE USE: gone before it is sent, whatever comes back.
1506
+ // ⚠️ ONE USE: gone before anything is sent, whatever comes back.
1009
1507
  pending.delete(ref);
1010
1508
  counts.termsAgreed += 1;
1509
+ if (p.orderId) {
1510
+ // ── terms the group answered an order with: its payment page, now ──
1511
+ const r = orders.get(p.orderId);
1512
+ if (!r || r.owner !== acct.owner || r.released || !r.held)
1513
+ throw termsGone();
1514
+ r.held = undefined;
1515
+ put(r);
1516
+ log(`[otaless] the guest agreed to the terms ${r.group} answered ${forTheLog(r.id)} with - its payment page handed on`);
1517
+ return { booked: [toBooking(r)], failed: [] };
1518
+ }
1519
+ const ask = p.ask;
1520
+ if (!ask)
1521
+ throw termsGone();
1522
+ await sweep(who);
1011
1523
  const hotel = deps.find(p.hotelId) ??
1012
1524
  {
1013
1525
  id: p.hotelId,
1014
1526
  name: p.hotelName,
1015
1527
  ...(p.hotelNames ? { names: { name: p.hotelNames } } : {}),
1016
1528
  };
1017
- const out = await ask({
1018
- acct,
1019
- who,
1020
- hotel,
1021
- group: p.group,
1022
- roomId: p.roomId,
1023
- roomName: p.roomName,
1024
- stay: p.stay,
1025
- rooms: p.rooms,
1026
- ...(p.terms ? { terms: p.terms } : {}),
1027
- guest: { name: p.body.guestName, email: p.body.guestEmail ?? '', phone: p.body.guestPhone },
1028
- pairs: p.pairs,
1029
- body: {
1030
- ...p.body,
1031
- // ⚠️ STILL FALSE: the agreement goes to the group's own tool, with the
1032
- // token of the terms the guest saw - so terms that changed meanwhile come
1033
- // back to be shown again, never agreed to unseen (questions #52).
1034
- termsAccepted: false,
1035
- extraParams: { terms_token: p.tokenOfTerms, terms_accepted: true },
1036
- },
1037
- });
1038
- return {
1039
- booked: out.booked ? [out.booked] : [],
1040
- failed: out.failed ? [out.failed] : [],
1041
- ...(out.terms ? { terms: [out.terms] } : {}),
1042
- };
1529
+ const label = { hotel, stay: p.stay, roomName: p.roomName };
1530
+ const lockKey = `${acct.owner}|${p.hotelId}|${ask.roomId}|${p.stay.checkIn}|${p.stay.checkOut}|${p.rooms}`;
1531
+ const guard = await stayGuard(acct, who, label, ask.roomId, p.rooms, lockKey);
1532
+ if (guard)
1533
+ return 'failed' in guard
1534
+ ? { booked: [], failed: [guard.failed] }
1535
+ : 'reuse' in guard
1536
+ ? { booked: [toBooking(guard.reuse)], failed: [], repeat: true }
1537
+ : { booked: [], failed: [], terms: [guard.terms] };
1538
+ inFlight.add(lockKey);
1539
+ try {
1540
+ const out = await place({
1541
+ acct,
1542
+ who,
1543
+ hotel,
1544
+ group: p.group,
1545
+ roomId: ask.roomId,
1546
+ roomName: p.roomName,
1547
+ stay: p.stay,
1548
+ rooms: p.rooms,
1549
+ // A step 8 asked for (questions #66, #68): the room's terms were agreed first; this now.
1550
+ agreed: ask.token ? (ask.roomTerms ?? '') : p.text,
1551
+ ...(ask.token
1552
+ ? { groupStep: { step: ask.step ?? 'terms', text: p.text, token: ask.token } }
1553
+ : {}),
1554
+ guest: ask.guest,
1555
+ total: p.total,
1556
+ });
1557
+ return {
1558
+ booked: out.booked ? [out.booked] : [],
1559
+ failed: out.failed ? [out.failed] : [],
1560
+ ...(out.terms ? { terms: [out.terms] } : {}),
1561
+ };
1562
+ }
1563
+ finally {
1564
+ inFlight.delete(lockKey);
1565
+ }
1566
+ };
1567
+ const discardTerms = async (ref, who) => {
1568
+ const found = pendingFor(ref, who);
1569
+ if (!found)
1570
+ return {};
1571
+ const { p, acct } = found;
1572
+ pending.delete(ref);
1573
+ if (!p.orderId)
1574
+ return {};
1575
+ const r = orders.get(p.orderId);
1576
+ if (!r || r.owner !== acct.owner || r.released || !r.held)
1577
+ return {};
1578
+ // ⚠️ NOT AGREED: the order it held back is cancelled (总线程 11-11, D).
1579
+ await release(acct, who, r, 'terms');
1580
+ return { booking: toBooking(r) };
1043
1581
  };
1044
1582
  // ── the bookings, refreshed ───────────────────────────────────────────────
1045
1583
  const statusOfRow = (s) => {
@@ -1083,6 +1621,7 @@ export const createOtalessBookings = (deps) => {
1083
1621
  if (paid) {
1084
1622
  if (amount && !asked(amount, r)) {
1085
1623
  r.needsPerson = 'paid-amount';
1624
+ r.needsPersonAt = iso();
1086
1625
  payLinks.delete(r.id);
1087
1626
  put(r);
1088
1627
  log(`[otaless] NEEDS A PERSON: ${forTheLog(r.id)} at ${r.group} paid ${amount.currency} ${amount.minor}, not what was asked - not taken as paid`);
@@ -1119,7 +1658,7 @@ export const createOtalessBookings = (deps) => {
1119
1658
  };
1120
1659
  /**
1121
1660
  * 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
1661
+ * 8 did not answer for. The rows when the list was read - undefined when it
1123
1662
  * could not be (and nothing changed).
1124
1663
  *
1125
1664
  * ⚠️ WHAT IS LET GO OR STILL BEING LOOKED FOR IS NOT TOUCHED (总线程's review
@@ -1150,6 +1689,7 @@ export const createOtalessBookings = (deps) => {
1150
1689
  const amount = moneyOf(row.totalAmount, row.currency);
1151
1690
  if (!amount || !asked(amount, r)) {
1152
1691
  r.needsPerson = 'paid-amount';
1692
+ r.needsPersonAt = iso();
1153
1693
  payLinks.delete(r.id);
1154
1694
  put(r);
1155
1695
  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`);
@@ -1171,7 +1711,11 @@ export const createOtalessBookings = (deps) => {
1171
1711
  ...(r.refund?.amount ? { amount: r.refund.amount } : {}),
1172
1712
  };
1173
1713
  if (r.status === 'awaiting-payment' && !payLinks.has(r.id)) {
1174
- const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
1714
+ // Held to this order's own page where the list says so (11-11, B).
1715
+ const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts, {
1716
+ id: r.id,
1717
+ code: r.code,
1718
+ });
1175
1719
  if (ok)
1176
1720
  payLinks.set(r.id, ok.url);
1177
1721
  }
@@ -1180,7 +1724,7 @@ export const createOtalessBookings = (deps) => {
1180
1724
  }
1181
1725
  if (known.has(id))
1182
1726
  continue;
1183
- // ── an order 13 did not answer for (总线程's review of 0.63.0, 3) ──
1727
+ // ── an order 8 did not answer for (总线程's review of 0.63.0, 3) ──
1184
1728
  // ⚠️ THE SAME HOTEL, THE SAME ROOM, THE SAME NIGHTS - BY ID: the group and
1185
1729
  // the nights alone would claim another stay of the guest's. The document's
1186
1730
  // order rows carry no hotel or room id; until the backend sends them
@@ -1209,11 +1753,14 @@ export const createOtalessBookings = (deps) => {
1209
1753
  // ⚠️ AT ANOTHER AMOUNT, NOT CLAIMED: the record keeps its own id and stays
1210
1754
  // unconfirmed - for a person.
1211
1755
  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`);
1756
+ log(`[otaless] NEEDS A PERSON: an order 8 did not answer for was found at ${group} at another amount - not claimed`);
1213
1757
  continue;
1214
1758
  }
1215
1759
  const s = statusOfRow(row.status);
1216
- const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
1760
+ const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts, {
1761
+ id,
1762
+ code: text(row.originalOrderId),
1763
+ });
1217
1764
  orders.delete(o.id);
1218
1765
  o.id = id;
1219
1766
  o.code = text(row.originalOrderId) ?? '';
@@ -1267,9 +1814,11 @@ export const createOtalessBookings = (deps) => {
1267
1814
  if (acct)
1268
1815
  signed.set(g, acct);
1269
1816
  }
1270
- // Let go at once, and gone: not the guest's. One that could not be undone stays listed.
1271
- const mine = [...orders.values()].filter((o) => signed.get(o.group)?.owner === o.owner &&
1272
- (!o.released || (o.releaseFailed && o.status === 'confirmed')));
1817
+ await sweep(who);
1818
+ // Cancelled at once, and gone: not the guest's. ⚠️ ONE THAT COULD NOT BE
1819
+ // CANCELLED STAYS LISTED (11-11): it may stand at the group - a person's,
1820
+ // with no page to pay it on.
1821
+ const mine = [...orders.values()].filter((o) => signed.get(o.group)?.owner === o.owner && (!o.released || o.releaseFailed));
1273
1822
  await refresh(who, mine, signed);
1274
1823
  const list = mine
1275
1824
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
@@ -1318,7 +1867,7 @@ export const createOtalessBookings = (deps) => {
1318
1867
  ...base,
1319
1868
  fee: money(0, amount.currency),
1320
1869
  refund: money(0, amount.currency),
1321
- rule: 'Not paid yet: cancelling closes its payment page, and nothing was charged.',
1870
+ rule: 'Not paid yet - nothing has been charged for it.',
1322
1871
  cancellable: true,
1323
1872
  reason: 'unpaid',
1324
1873
  };
@@ -1353,9 +1902,8 @@ export const createOtalessBookings = (deps) => {
1353
1902
  throw refusal('unconfirmed', `${g} has not said yet whether it took this booking, so it cannot be cancelled yet - look at the bookings again in a few minutes.`);
1354
1903
  const unpaid = r.status === 'awaiting-payment' && !r.paid;
1355
1904
  const why = cleanReason(reason);
1356
- const out = await withSession(acct, who, (cred) => unpaid
1357
- ? client.cancelCheckout({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who))
1358
- : client.cancelBooking({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who)));
1905
+ // 9, paid or not: 14 is not called any more (questions #56).
1906
+ const out = await withSession(acct, who, (cred) => client.cancelBooking({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who)));
1359
1907
  const said = cancelOutcome(out);
1360
1908
  // ⚠️ NOTHING SAID IS NOT DONE (总线程's review of 0.63.0, 4): our record
1361
1909
  // stays as it was, and the guest is told it is not known yet.
@@ -1366,6 +1914,11 @@ export const createOtalessBookings = (deps) => {
1366
1914
  r.status = 'cancelled';
1367
1915
  r.cancelledAt = iso();
1368
1916
  payLinks.delete(r.id);
1917
+ // Held for terms: those terms go with it.
1918
+ r.held = undefined;
1919
+ for (const [k, p] of pending)
1920
+ if (p.orderId === r.id)
1921
+ pending.delete(k);
1369
1922
  const back = moneyOf(out?.refundAmount, out?.refundCurrency);
1370
1923
  if (!unpaid && r.paid)
1371
1924
  r.refund = { status: 'requested', ...(back ? { amount: back } : {}) };
@@ -1533,6 +2086,7 @@ export const createOtalessBookings = (deps) => {
1533
2086
  return found ? view(found.p) : undefined;
1534
2087
  },
1535
2088
  acceptTerms,
2089
+ discardTerms,
1536
2090
  previewRefund,
1537
2091
  refund,
1538
2092
  addons,
@@ -1542,6 +2096,7 @@ export const createOtalessBookings = (deps) => {
1542
2096
  ordersAwaitingPayment: [...orders.values()].filter((o) => o.status === 'awaiting-payment')
1543
2097
  .length,
1544
2098
  ordersUnconfirmed: [...orders.values()].filter((o) => o.status === 'unconfirmed').length,
2099
+ ordersHeld: [...orders.values()].filter((o) => o.held && !o.released).length,
1545
2100
  groupSessions: sessions.size,
1546
2101
  termsWaiting: pending.size,
1547
2102
  ...counts,