@curless/hotel-storefront 0.80.2 → 0.81.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 (95) hide show
  1. package/dist/account/index.d.ts +14 -0
  2. package/dist/account/index.d.ts.map +1 -1
  3. package/dist/account/index.js +427 -43
  4. package/dist/account/index.js.map +1 -1
  5. package/dist/account/pages.d.ts +15 -2
  6. package/dist/account/pages.d.ts.map +1 -1
  7. package/dist/account/pages.js +13 -10
  8. package/dist/account/pages.js.map +1 -1
  9. package/dist/account/wallet-pages.d.ts +84 -0
  10. package/dist/account/wallet-pages.d.ts.map +1 -0
  11. package/dist/account/wallet-pages.js +229 -0
  12. package/dist/account/wallet-pages.js.map +1 -0
  13. package/dist/account/wallet.d.ts +163 -0
  14. package/dist/account/wallet.d.ts.map +1 -0
  15. package/dist/account/wallet.js +365 -0
  16. package/dist/account/wallet.js.map +1 -0
  17. package/dist/backend.d.ts +18 -0
  18. package/dist/backend.d.ts.map +1 -1
  19. package/dist/backend.js.map +1 -1
  20. package/dist/card-v168.generated.d.ts +6 -0
  21. package/dist/card-v168.generated.d.ts.map +1 -0
  22. package/dist/card-v168.generated.js +10 -0
  23. package/dist/card-v168.generated.js.map +1 -0
  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 +48 -2
  28. package/dist/config.d.ts.map +1 -1
  29. package/dist/config.js +14 -1
  30. package/dist/config.js.map +1 -1
  31. package/dist/huazhu/ari-sync.d.ts.map +1 -1
  32. package/dist/huazhu/ari-sync.js +15 -4
  33. package/dist/huazhu/ari-sync.js.map +1 -1
  34. package/dist/huazhu/check.d.ts.map +1 -1
  35. package/dist/huazhu/check.js +4 -1
  36. package/dist/huazhu/check.js.map +1 -1
  37. package/dist/huazhu/client.d.ts +48 -2
  38. package/dist/huazhu/client.d.ts.map +1 -1
  39. package/dist/huazhu/client.js +263 -3
  40. package/dist/huazhu/client.js.map +1 -1
  41. package/dist/huazhu/make.d.ts.map +1 -1
  42. package/dist/huazhu/make.js +6 -1
  43. package/dist/huazhu/make.js.map +1 -1
  44. package/dist/legal.d.ts.map +1 -1
  45. package/dist/legal.js +26 -4
  46. package/dist/legal.js.map +1 -1
  47. package/dist/otaless/client.d.ts +109 -0
  48. package/dist/otaless/client.d.ts.map +1 -1
  49. package/dist/otaless/client.js +44 -4
  50. package/dist/otaless/client.js.map +1 -1
  51. package/dist/otaless/fake.d.ts +92 -0
  52. package/dist/otaless/fake.d.ts.map +1 -1
  53. package/dist/otaless/fake.js +265 -0
  54. package/dist/otaless/fake.js.map +1 -1
  55. package/dist/otaless/make.d.ts +40 -1
  56. package/dist/otaless/make.d.ts.map +1 -1
  57. package/dist/otaless/make.js +150 -2
  58. package/dist/otaless/make.js.map +1 -1
  59. package/dist/otaless/shop-answers.d.ts +72 -0
  60. package/dist/otaless/shop-answers.d.ts.map +1 -0
  61. package/dist/otaless/shop-answers.js +344 -0
  62. package/dist/otaless/shop-answers.js.map +1 -0
  63. package/dist/otaless/shop-client.d.ts +133 -0
  64. package/dist/otaless/shop-client.d.ts.map +1 -0
  65. package/dist/otaless/shop-client.js +201 -0
  66. package/dist/otaless/shop-client.js.map +1 -0
  67. package/dist/otaless/shop-fake.d.ts +100 -0
  68. package/dist/otaless/shop-fake.d.ts.map +1 -0
  69. package/dist/otaless/shop-fake.js +259 -0
  70. package/dist/otaless/shop-fake.js.map +1 -0
  71. package/dist/otaless/shop-service.d.ts +105 -0
  72. package/dist/otaless/shop-service.d.ts.map +1 -0
  73. package/dist/otaless/shop-service.js +187 -0
  74. package/dist/otaless/shop-service.js.map +1 -0
  75. package/dist/otaless/shop.d.ts +160 -0
  76. package/dist/otaless/shop.d.ts.map +1 -0
  77. package/dist/otaless/shop.js +715 -0
  78. package/dist/otaless/shop.js.map +1 -0
  79. package/dist/otaless/wallet.d.ts +160 -0
  80. package/dist/otaless/wallet.d.ts.map +1 -0
  81. package/dist/otaless/wallet.js +650 -0
  82. package/dist/otaless/wallet.js.map +1 -0
  83. package/dist/server.d.ts +14 -3
  84. package/dist/server.d.ts.map +1 -1
  85. package/dist/server.js +41 -12
  86. package/dist/server.js.map +1 -1
  87. package/dist/surface.d.ts +7 -0
  88. package/dist/surface.d.ts.map +1 -1
  89. package/dist/surface.js +14 -0
  90. package/dist/surface.js.map +1 -1
  91. package/dist/tools.d.ts +98 -93
  92. package/dist/tools.d.ts.map +1 -1
  93. package/dist/tools.js +239 -1
  94. package/dist/tools.js.map +1 -1
  95. package/package.json +1 -1
@@ -0,0 +1,715 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { checkoutEntryOf, pathSegments } from './booking.js';
3
+ import { NOT_SIGNED_IN, OtalessBusy, OtalessError, imageOf } from './client.js';
4
+ import { ADDON_CODES, ShopSignInRequired, isUnknown, } from './shop-client.js';
5
+ // --- small parsers ------------------------------------------------------------------------
6
+ /**
7
+ * Cents from a backend number or numeric string: whole cents only, finite, not negative. ⚠️ A third
8
+ * decimal is not rounded away - 75.655 is not a price we can compare, it is not taken (an amount
9
+ * half a cent over would otherwise pass as equal).
10
+ */
11
+ export const centsOf = (v) => {
12
+ const n = typeof v === 'number'
13
+ ? v
14
+ : typeof v === 'string' && /^\d+(\.\d+)?$/.test(v.trim())
15
+ ? Number(v)
16
+ : Number.NaN;
17
+ if (!Number.isFinite(n) || n < 0 || n > 1e9)
18
+ return undefined;
19
+ const c = Math.round(n * 100);
20
+ return Math.abs(n * 100 - c) < 1e-6 ? c : undefined;
21
+ };
22
+ const CURRENCY = /^[A-Z]{3}$/;
23
+ const currencyOf = (v) => {
24
+ const c = typeof v === 'string' ? v.trim().toUpperCase() : '';
25
+ return CURRENCY.test(c) ? c : undefined;
26
+ };
27
+ const CONTROLS =
28
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point
29
+ /[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
30
+ /** A backend's text for a guest's eyes: one line, no controls or direction marks, cut short. */
31
+ const textOf = (v, max) => {
32
+ if (typeof v !== 'string')
33
+ return undefined;
34
+ const s = v.replace(CONTROLS, ' ').replace(/\s+/g, ' ').trim().slice(0, max).trim();
35
+ return s || undefined;
36
+ };
37
+ /** Everything in CONTROLS but the line break (a description keeps those). */
38
+ const CONTROLS_NOT_NEWLINE =
39
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: removing them is the point
40
+ /[\u0000-\u0009\u000B-\u001F\u007F-\u009F\u200B-\u200F\u2028-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
41
+ /** A description keeps its paragraphs - but nothing else odd. */
42
+ const paragraphsOf = (v, max) => {
43
+ if (typeof v !== 'string')
44
+ return undefined;
45
+ const s = v
46
+ .replace(/\r\n?/g, '\n')
47
+ .replace(CONTROLS_NOT_NEWLINE, ' ')
48
+ .replace(/[ \t]+/g, ' ')
49
+ .replace(/\n{3,}/g, '\n\n')
50
+ .trim()
51
+ .slice(0, max)
52
+ .trim();
53
+ return s || undefined;
54
+ };
55
+ /** An id the backend made - or a product's: plain, short, nothing a path or a log line could be bent by. */
56
+ const ID = /^[A-Za-z0-9_.:/-]{1,200}$/;
57
+ const idOf = (v) => {
58
+ const s = typeof v === 'string' ? v.trim() : '';
59
+ return ID.test(s) ? s : undefined;
60
+ };
61
+ const STATUS = {
62
+ PENDING: 'awaiting-payment',
63
+ PAID: 'paid',
64
+ CONFIRMED: 'confirmed',
65
+ COMPLETED: 'completed',
66
+ CANCELLED: 'cancelled',
67
+ REFUNDED: 'refunded',
68
+ FAILED: 'failed',
69
+ };
70
+ export const orderStatusOf = (v) => (typeof v === 'string' ? STATUS[v.trim().toUpperCase()] : undefined) ?? 'unknown';
71
+ /** An order the guest has paid for - whoever took the money. */
72
+ const PAID_STATES = new Set(['paid', 'confirmed', 'completed']);
73
+ const lower = (s) => s.replace(/\s+/g, ' ').trim().toLowerCase();
74
+ /** Keys `buy.params` may not carry: they are ours, or they are the very thing we promise not to send. */
75
+ const RESERVED_PARAMS = new Set([
76
+ 'providerCode',
77
+ 'productId',
78
+ 'productName',
79
+ 'unitPrice',
80
+ 'quantity',
81
+ 'vccId',
82
+ 'confirmationCode',
83
+ 'specSelections',
84
+ 'sessionToken',
85
+ 'extraParams',
86
+ 'lang',
87
+ 'customerName',
88
+ 'customerPhone',
89
+ 'customerEmail',
90
+ ]);
91
+ const hashOf = (token) => createHash('sha256').update(token).digest('base64url').slice(0, 16);
92
+ const HOLD_MS = 10 * 60_000;
93
+ export const createOtalessShop = (o) => {
94
+ const { client } = o;
95
+ const log = o.log ?? ((line) => console.error(line));
96
+ const now = o.now ?? Date.now;
97
+ const providers = new Set(o.providers.map((p) => p.trim().toLowerCase()).filter(Boolean));
98
+ const imageHosts = o.imageHosts.map((h) => h.toLowerCase());
99
+ const entries = o.checkoutHosts
100
+ .map((h) => checkoutEntryOf(h))
101
+ .filter((e) => e.order === undefined && !e.tokenPage && e.under.length > 0 && !e.under.includes('\u0000'));
102
+ const params = o.buy && Object.keys(o.buy.params).length > 0 ? { ...o.buy.params } : undefined;
103
+ if (params) {
104
+ for (const [k, v] of Object.entries(params)) {
105
+ if (RESERVED_PARAMS.has(k))
106
+ throw new Error(`otaless shop: buy.params may not carry "${k}"`);
107
+ if (typeof v !== 'string' && typeof v !== 'boolean')
108
+ throw new Error(`otaless shop: buy.params "${k}" must be a string or a boolean`);
109
+ }
110
+ }
111
+ const providerOf = (p) => {
112
+ const c = typeof p === 'string' ? p.trim().toLowerCase() : '';
113
+ return providers.has(c) ? c : undefined;
114
+ };
115
+ const langOf = (l) => (l === 'zh' ? 'zh' : 'en');
116
+ /** What an error means to the caller. */
117
+ const whyOf = (err) => {
118
+ if (err instanceof OtalessBusy)
119
+ return 'busy';
120
+ if (err instanceof ShopSignInRequired)
121
+ return 'shop-sign-in';
122
+ if (err instanceof OtalessError) {
123
+ if (err.backendCode === NOT_SIGNED_IN)
124
+ return 'not-signed-in';
125
+ if (err.backendCode === ADDON_CODES.channelSessionExpired)
126
+ return 'session-expired';
127
+ }
128
+ return 'failed';
129
+ };
130
+ // --- links ------------------------------------------------------------------------------
131
+ /**
132
+ * A checkout page as it may be handed to a guest - or nothing. https, no user, no port, no
133
+ * fragment; the host exactly an entry's, the path under that entry's by whole segments (put the
134
+ * way a server reads it: no `..`, `%2e` or `//` slips past) with at least one segment more - the
135
+ * checkout's own token, plain characters only.
136
+ *
137
+ * ⚠️ WHAT IS HANDED ON IS REBUILT: `https://<host>/<path>`, and the QUERY IS DROPPED. We cannot
138
+ * prove a Shopify checkout needs one (the document's own example, `/checkouts/cn/<token>`, has
139
+ * none; the newer checkouts carry their key in the path), and a query is where tracking
140
+ * parameters and redirects ride. If a live checkout turns out to need one, that is a decision
141
+ * for the main thread - an allowlist of parameter NAMES, not a pass-through.
142
+ */
143
+ const checkoutLinkOf = (raw) => {
144
+ if (typeof raw !== 'string' || !raw || raw.length > 2_048)
145
+ return undefined;
146
+ let u;
147
+ try {
148
+ u = new URL(raw);
149
+ }
150
+ catch {
151
+ return undefined;
152
+ }
153
+ if (u.protocol !== 'https:' || u.username || u.password || u.port || u.hash)
154
+ return undefined;
155
+ const segs = pathSegments(u.pathname);
156
+ if (!segs)
157
+ return undefined;
158
+ const host = u.hostname.toLowerCase();
159
+ for (const e of entries) {
160
+ if (e.host !== host || !e.under.every((seg, i) => segs[i] === seg))
161
+ continue;
162
+ const token = segs.slice(e.under.length);
163
+ if (token.length < 1 || token.length > 4)
164
+ continue;
165
+ if (!token.every((s) => /^[A-Za-z0-9_.~=-]{1,200}$/.test(s) && s !== '.' && s !== '..'))
166
+ continue;
167
+ return `https://${host}/${segs.join('/')}`;
168
+ }
169
+ return undefined;
170
+ };
171
+ // --- parsing ----------------------------------------------------------------------------
172
+ const itemOf = (raw) => {
173
+ if (!raw || typeof raw !== 'object')
174
+ return undefined;
175
+ const id = idOf(raw.productId);
176
+ const name = textOf(raw.name, 200);
177
+ const priceCents = centsOf(raw.price);
178
+ const currency = currencyOf(raw.currency);
179
+ if (!id || !name || priceCents === undefined || !currency)
180
+ return undefined;
181
+ const options = [
182
+ ...new Set((Array.isArray(raw.options) ? raw.options : [])
183
+ .map((x) => textOf(x, 100))
184
+ .filter((x) => !!x)),
185
+ ].slice(0, 50);
186
+ const picture = typeof raw.imageUrl === 'string' && raw.imageUrl.trim().startsWith('https://')
187
+ ? imageOf(raw.imageUrl, imageHosts)
188
+ : undefined;
189
+ const description = paragraphsOf(raw.description, 1_000);
190
+ const category = textOf(raw.category, 60);
191
+ const unit = textOf(raw.unit, 30);
192
+ return {
193
+ id,
194
+ name,
195
+ ...(description ? { description } : {}),
196
+ ...(category ? { category } : {}),
197
+ priceCents,
198
+ currency,
199
+ ...(unit ? { unit } : {}),
200
+ options,
201
+ // Only a plain `true` is stock: "false", 0, null and a missing field are not.
202
+ available: raw.available === true,
203
+ ...(picture ? { imageUrl: picture } : {}),
204
+ };
205
+ };
206
+ const rowOf = (raw) => {
207
+ if (!raw || typeof raw !== 'object')
208
+ return undefined;
209
+ const id = idOf(raw.orderId);
210
+ const totalCents = centsOf(raw.totalAmount);
211
+ const currency = currencyOf(raw.currency);
212
+ if (!id || totalCents === undefined || !currency)
213
+ return undefined;
214
+ const status = orderStatusOf(raw.status);
215
+ const link = status === 'awaiting-payment' ? checkoutLinkOf(raw.checkoutUrl) : undefined;
216
+ // ⚠️ `refundUrl` is not read at all (questions #115).
217
+ return {
218
+ id,
219
+ name: textOf(raw.itemName, 200) ?? '',
220
+ totalCents,
221
+ currency,
222
+ status,
223
+ ...(link ? { checkoutUrl: link } : {}),
224
+ ...(typeof raw.checkoutUrl === 'string' ? { checkoutRaw: raw.checkoutUrl } : {}),
225
+ };
226
+ };
227
+ const publicRow = ({ checkoutRaw: _raw, ...r }) => r;
228
+ /** The member's orders as the backend lists them now - and every id in the answer, parsed or not. */
229
+ const readOrders = async (token, provider, lang) => {
230
+ const raw = await client.orders({ providerCode: provider, limit: 100, lang }, token);
231
+ const ids = new Set();
232
+ const rows = [];
233
+ for (const r of raw) {
234
+ const id = typeof r?.orderId === 'string' ? r.orderId : undefined;
235
+ if (id)
236
+ ids.add(id);
237
+ const row = rowOf(r);
238
+ if (row)
239
+ rows.push(row);
240
+ else
241
+ log('[otaless-shop] an order row was not taken (no id, amount or currency)');
242
+ }
243
+ return { rows, ids };
244
+ };
245
+ // --- in-flight and held ----------------------------------------------------------------------
246
+ /** Writes under way: a second one for the same thing is refused, not queued (no idempotency key). */
247
+ const running = new Set();
248
+ /** Writes whose answer is not known, or that were made a moment ago: not asked again for a while. */
249
+ const held = new Map();
250
+ const holding = (key) => {
251
+ const at = held.get(key);
252
+ if (at === undefined)
253
+ return false;
254
+ if (now() - at < HOLD_MS)
255
+ return true;
256
+ held.delete(key);
257
+ return false;
258
+ };
259
+ /** One write at a time per key - false if one is under way or held. */
260
+ const guarded = async (key, inFlight, checking, work, keepHeld) => {
261
+ if (running.has(key))
262
+ return inFlight();
263
+ if (holding(key))
264
+ return checking();
265
+ running.add(key);
266
+ try {
267
+ const r = await work();
268
+ if (keepHeld(r))
269
+ held.set(key, now());
270
+ return r;
271
+ }
272
+ finally {
273
+ running.delete(key);
274
+ }
275
+ };
276
+ // --- reads ------------------------------------------------------------------------------
277
+ const item = async (provider, id, lang) => {
278
+ const p = providerOf(provider);
279
+ if (!p)
280
+ return { ok: false, why: 'not-enabled' };
281
+ const want = idOf(id);
282
+ if (!want)
283
+ return { ok: false, why: 'not-found' };
284
+ try {
285
+ const raw = await client.productDetail({
286
+ providerCode: p,
287
+ productId: want,
288
+ lang: langOf(lang),
289
+ });
290
+ const it = itemOf(raw);
291
+ // ⚠️ THE ITEM ASKED FOR: a detail answered with another product's id is not this item.
292
+ return it && it.id === want ? { ok: true, item: it } : { ok: false, why: 'not-found' };
293
+ }
294
+ catch (err) {
295
+ log(`[otaless-shop] item read failed: ${err instanceof Error ? err.message : 'error'}`);
296
+ return { ok: false, why: whyOf(err) };
297
+ }
298
+ };
299
+ const items = async (provider, q) => {
300
+ const p = providerOf(provider);
301
+ if (!p)
302
+ return { ok: false, why: 'not-enabled' };
303
+ const limit = Math.min(50, Math.max(1, Math.trunc(Number.isFinite(q.limit) ? q.limit : 20)));
304
+ const keyword = textOf(q.keyword, 100);
305
+ const category = textOf(q.category, 60);
306
+ const max = typeof q.maxPrice === 'number' && Number.isFinite(q.maxPrice) && q.maxPrice >= 0
307
+ ? q.maxPrice
308
+ : undefined;
309
+ try {
310
+ const raw = await client.products({
311
+ providerCode: p,
312
+ ...(keyword ? { keyword } : {}),
313
+ ...(category ? { category } : {}),
314
+ ...(max !== undefined ? { maxPrice: max } : {}),
315
+ limit,
316
+ lang: langOf(q.lang),
317
+ });
318
+ const seen = new Set();
319
+ const out = [];
320
+ for (const r of raw) {
321
+ const it = itemOf(r);
322
+ if (!it || seen.has(it.id))
323
+ continue;
324
+ // The backend's filter is not trusted: a dearer item than asked is not listed.
325
+ if (max !== undefined && it.priceCents > Math.round(max * 100))
326
+ continue;
327
+ seen.add(it.id);
328
+ out.push(it);
329
+ if (out.length >= limit)
330
+ break;
331
+ }
332
+ return { ok: true, items: out };
333
+ }
334
+ catch (err) {
335
+ log(`[otaless-shop] items read failed: ${err instanceof Error ? err.message : 'error'}`);
336
+ return { ok: false, why: whyOf(err) };
337
+ }
338
+ };
339
+ const orders = async (token, provider, opts) => {
340
+ const p = providerOf(provider);
341
+ if (!p)
342
+ return { ok: false, why: 'not-enabled' };
343
+ const lang = langOf(opts?.lang);
344
+ try {
345
+ const { rows } = await readOrders(token, p, lang);
346
+ if (opts?.refresh !== false) {
347
+ // The payment state of an awaiting order, once each (`once: true` is the client's, always).
348
+ let asked = 0;
349
+ for (const r of rows) {
350
+ if (r.status !== 'awaiting-payment' || asked >= 5)
351
+ continue;
352
+ asked += 1;
353
+ try {
354
+ const s = await client.paymentStatus({ providerCode: p, unifiedOrderId: r.id, lang }, token);
355
+ const said = typeof s.status === 'string' ? s.status.toLowerCase() : '';
356
+ if (said === 'paid') {
357
+ r.status = 'paid';
358
+ r.checkoutUrl = undefined;
359
+ }
360
+ else if (said === 'cancelled' || said === 'expired') {
361
+ r.status = 'cancelled';
362
+ r.checkoutUrl = undefined;
363
+ }
364
+ }
365
+ catch {
366
+ // The list stands as it was.
367
+ }
368
+ }
369
+ }
370
+ return {
371
+ ok: true,
372
+ orders: rows
373
+ .map(publicRow)
374
+ .map((r) => (r.checkoutUrl === undefined ? stripUndefined(r) : r)),
375
+ };
376
+ }
377
+ catch (err) {
378
+ log(`[otaless-shop] orders read failed: ${err instanceof Error ? err.message : 'error'}`);
379
+ return { ok: false, why: whyOf(err) };
380
+ }
381
+ };
382
+ const stripUndefined = (r) => {
383
+ const { checkoutUrl: _u, ...rest } = r;
384
+ return rest;
385
+ };
386
+ // --- cancel -----------------------------------------------------------------------------
387
+ /** One `/cancel`, sent once. `cancelled` only on the backend saying so. */
388
+ const sendCancel = async (token, provider, orderId, lang) => {
389
+ try {
390
+ const r = await client.cancel({ providerCode: provider, unifiedOrderId: orderId, reason: 'cancelled by the guest', lang }, token);
391
+ const said = typeof r.status === 'string' ? r.status.toLowerCase() : 'cancelled';
392
+ return r.success === true && said === 'cancelled' ? 'cancelled' : 'refused';
393
+ }
394
+ catch (err) {
395
+ return isUnknown(err) ? 'unknown' : 'refused';
396
+ }
397
+ };
398
+ const cancel = async (token, provider, orderId) => {
399
+ const p = providerOf(provider);
400
+ if (!p)
401
+ return { outcome: 'refused', why: 'not-enabled' };
402
+ const id = idOf(orderId);
403
+ if (!id)
404
+ return { outcome: 'refused', why: 'not-found' };
405
+ return guarded(`${p}:${id}`, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
406
+ // ⚠️ THE ORDERS READ NOW, NOT A LIST FROM BEFORE: the id must be one of THIS member's rows
407
+ // (the backend scopes `/orders` to the signed-in member), still awaiting payment.
408
+ let row;
409
+ try {
410
+ row = (await readOrders(token, p, 'en')).rows.find((r) => r.id === id);
411
+ }
412
+ catch (err) {
413
+ return { outcome: 'refused', why: whyOf(err) };
414
+ }
415
+ if (!row)
416
+ return { outcome: 'refused', why: 'not-found' };
417
+ if (row.status !== 'awaiting-payment')
418
+ return { outcome: 'refused', why: 'not-awaiting' };
419
+ // A guest may have paid a moment ago, and `/orders` not know yet: ask the payment's state once.
420
+ try {
421
+ const s = await client.paymentStatus({ providerCode: p, unifiedOrderId: id, lang: 'en' }, token);
422
+ if (typeof s.status === 'string' && s.status.toLowerCase() === 'paid')
423
+ return { outcome: 'refused', why: 'paid' };
424
+ }
425
+ catch {
426
+ // Not known: the backend's own rule (it cancels what is not paid) stands.
427
+ }
428
+ const r = await sendCancel(token, p, id, 'en');
429
+ if (r === 'cancelled')
430
+ return { outcome: 'cancelled' };
431
+ if (r === 'unknown') {
432
+ log(`[otaless-shop] cancel of ${id} not known - not sent again`);
433
+ return { outcome: 'unknown' };
434
+ }
435
+ return { outcome: 'refused', why: 'failed' };
436
+ }, (r) => r.outcome === 'unknown' || r.outcome === 'cancelled');
437
+ };
438
+ // --- refund -----------------------------------------------------------------------------
439
+ const refund = async (token, provider, orderId) => {
440
+ const p = providerOf(provider);
441
+ if (!p)
442
+ return { outcome: 'refused', why: 'not-enabled' };
443
+ const id = idOf(orderId);
444
+ if (!id)
445
+ return { outcome: 'refused', why: 'not-found' };
446
+ return guarded(`${p}:${id}`, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
447
+ let row;
448
+ try {
449
+ row = (await readOrders(token, p, 'en')).rows.find((r) => r.id === id);
450
+ }
451
+ catch (err) {
452
+ return { outcome: 'refused', why: whyOf(err) };
453
+ }
454
+ if (!row)
455
+ return { outcome: 'refused', why: 'not-found' };
456
+ if (!PAID_STATES.has(row.status))
457
+ return { outcome: 'refused', why: 'not-refundable' };
458
+ try {
459
+ const r = await client.refund({
460
+ providerCode: p,
461
+ unifiedOrderId: id,
462
+ // ⚠️ THE FULL TOTAL, WRITTEN OUT: an empty `amount` is "all" by the document, and
463
+ // what the backend takes to be all is not for us to leave to it.
464
+ amount: row.totalCents / 100,
465
+ reason: 'refund requested by the guest',
466
+ lang: 'en',
467
+ }, token);
468
+ const said = typeof r.status === 'string' ? r.status.toLowerCase() : 'refunded';
469
+ if (r.success !== true || said !== 'refunded')
470
+ return { outcome: 'refused', why: 'failed' };
471
+ const refundCents = centsOf(r.refundAmount);
472
+ if (refundCents !== undefined && refundCents > row.totalCents)
473
+ log(`[otaless-shop] NEEDS A PERSON: refund of ${id} said ${row.currency} ${(refundCents / 100).toFixed(2)}, more than the ${(row.totalCents / 100).toFixed(2)} asked`);
474
+ return { outcome: 'refunded', ...(refundCents !== undefined ? { refundCents } : {}) };
475
+ }
476
+ catch (err) {
477
+ if (isUnknown(err)) {
478
+ log(`[otaless-shop] refund of ${id} not known - not sent again; the orders will say`);
479
+ return { outcome: 'unknown' };
480
+ }
481
+ const code = err instanceof OtalessError ? err.backendCode : undefined;
482
+ if (code === ADDON_CODES.cannotRefund || code === ADDON_CODES.orderNotFound)
483
+ return {
484
+ outcome: 'refused',
485
+ why: code === ADDON_CODES.orderNotFound ? 'not-found' : 'not-refundable',
486
+ };
487
+ return { outcome: 'refused', why: whyOf(err) };
488
+ }
489
+ },
490
+ // A refund made, or not known, is not asked again for ten minutes: `/orders` may lag, and
491
+ // a second one is a second payout.
492
+ (r) => r.outcome === 'unknown' || r.outcome === 'refunded');
493
+ };
494
+ const madeFromAnswer = (a) => {
495
+ const status = orderStatusOf(a.status);
496
+ const id = idOf(a.unifiedOrderId);
497
+ const totalCents = centsOf(a.totalAmount);
498
+ const currency = currencyOf(a.currency);
499
+ return {
500
+ ...(id ? { id } : {}),
501
+ status,
502
+ charged: a.isVccPaid === true || PAID_STATES.has(status),
503
+ failed: a.success === false || status === 'failed',
504
+ ...(totalCents !== undefined ? { totalCents } : {}),
505
+ ...(currency ? { currency } : {}),
506
+ checkoutRaw: a.checkoutUrl,
507
+ };
508
+ };
509
+ const madeFromRow = (r) => ({
510
+ id: r.id,
511
+ status: r.status,
512
+ charged: PAID_STATES.has(r.status),
513
+ failed: r.status === 'failed',
514
+ totalCents: r.totalCents,
515
+ currency: r.currency,
516
+ checkoutRaw: r.checkoutRaw,
517
+ });
518
+ const buy = async (token, provider, req, shown) => {
519
+ // ⚠️ NO PARAMETER, NO BUY (questions #103): not one request is sent.
520
+ if (!params)
521
+ return { outcome: 'off' };
522
+ const p = providerOf(provider);
523
+ if (!p)
524
+ return { outcome: 'off' };
525
+ const qty = req.quantity;
526
+ if (!Number.isInteger(qty) || qty < 1 || qty > 10)
527
+ return { outcome: 'refused', why: 'quantity' };
528
+ const code = typeof req.confirmationCode === 'string' ? req.confirmationCode.trim() : '';
529
+ if (!code || code.length > 64)
530
+ return { outcome: 'refused', why: 'confirmation-code' };
531
+ const shownCurrency = currencyOf(shown?.currency);
532
+ if (!shownCurrency || !Number.isInteger(shown.unitCents) || shown.unitCents <= 0)
533
+ return { outcome: 'refused', why: 'shown' };
534
+ const lang = langOf(req.lang);
535
+ const itemId = idOf(req.itemId);
536
+ if (!itemId)
537
+ return { outcome: 'refused', why: 'not-found' };
538
+ const key = `buy:${hashOf(token)}:${p}:${itemId}`;
539
+ return guarded(key, () => ({ outcome: 'refused', why: 'in-progress' }), () => ({ outcome: 'refused', why: 'checking' }), async () => {
540
+ // 1. The item as it is now: there, in stock, the option one of its own, the price the guest saw.
541
+ const fresh = await item(p, itemId, lang);
542
+ if (!fresh.ok) {
543
+ if (fresh.why === 'not-found')
544
+ return { outcome: 'refused', why: 'not-found' };
545
+ return fresh.why === 'busy' ||
546
+ fresh.why === 'not-signed-in' ||
547
+ fresh.why === 'shop-sign-in' ||
548
+ fresh.why === 'session-expired'
549
+ ? { outcome: fresh.why }
550
+ : { outcome: 'refused', why: 'backend' };
551
+ }
552
+ const it = fresh.item;
553
+ if (!it.available)
554
+ return { outcome: 'refused', why: 'unavailable' };
555
+ const option = typeof req.option === 'string' ? req.option.trim() : '';
556
+ if (it.options.length > 0 ? !it.options.includes(option) : option !== '')
557
+ return { outcome: 'refused', why: 'option' };
558
+ if (it.priceCents !== shown.unitCents || it.currency !== shownCurrency)
559
+ return {
560
+ outcome: 'price-changed',
561
+ now: { unitCents: it.priceCents, currency: it.currency },
562
+ };
563
+ // 2. The orders as they stand: what is new after the request is the request's.
564
+ let before;
565
+ try {
566
+ before = (await readOrders(token, p, lang)).ids;
567
+ }
568
+ catch (err) {
569
+ const why = whyOf(err);
570
+ return why === 'busy' ||
571
+ why === 'not-signed-in' ||
572
+ why === 'shop-sign-in' ||
573
+ why === 'session-expired'
574
+ ? { outcome: why }
575
+ : { outcome: 'refused', why: 'backend' };
576
+ }
577
+ // 3. The request: ONCE. No `vccId`; the checkout-only parameters first, ours over them.
578
+ const guest = req.guest ?? {};
579
+ const name = textOf(guest.name, 100);
580
+ const email = textOf(guest.email, 200);
581
+ const phone = textOf(guest.phone, 40);
582
+ const body = {
583
+ ...params,
584
+ providerCode: p,
585
+ productId: it.id,
586
+ productName: it.name,
587
+ unitPrice: it.priceCents / 100,
588
+ quantity: qty,
589
+ confirmationCode: code,
590
+ ...(option ? { specSelections: { option } } : {}),
591
+ ...(name ? { customerName: name } : {}),
592
+ ...(email ? { customerEmail: email } : {}),
593
+ ...(phone ? { customerPhone: phone } : {}),
594
+ lang,
595
+ };
596
+ let made;
597
+ try {
598
+ made = madeFromAnswer(await client.buy(body, token));
599
+ }
600
+ catch (err) {
601
+ if (err instanceof OtalessBusy)
602
+ return { outcome: 'busy' };
603
+ if (err instanceof ShopSignInRequired)
604
+ return { outcome: 'shop-sign-in' };
605
+ const codeSaid = err instanceof OtalessError ? err.backendCode : undefined;
606
+ if (codeSaid === NOT_SIGNED_IN)
607
+ return { outcome: 'not-signed-in' };
608
+ if (codeSaid === ADDON_CODES.channelSessionExpired)
609
+ return { outcome: 'session-expired' };
610
+ if (!isUnknown(err)) {
611
+ if (codeSaid === ADDON_CODES.vccFailed)
612
+ log('[otaless-shop] buy: the backend TRIED A CARD (4020) - the checkout-only parameter was not honoured');
613
+ return { outcome: 'refused', why: 'backend' };
614
+ }
615
+ // 4. ⚠️ NOT KNOWN WHETHER IT WAS MADE: never sent again. Read the orders once.
616
+ log('[otaless-shop] buy answer not known - not sent again; reading the orders once');
617
+ try {
618
+ const after = await readOrders(token, p, lang);
619
+ // ⚠️ ADOPTED ONLY WHEN IT CAN BE NO OTHER (总线程 11-23): new since the request, the
620
+ // same item name (whole, not one inside the other), the same amount and currency the
621
+ // guest was shown - and EXACTLY ONE such row. None or several: not known, a person
622
+ // looks, no link. A name alone could take another order for this one.
623
+ const mine = after.rows.filter((r) => !before.has(r.id) &&
624
+ sameName(r.name, it.name) &&
625
+ r.totalCents === shown.unitCents * qty &&
626
+ r.currency === shownCurrency);
627
+ if (mine.length !== 1 || !mine[0]) {
628
+ log(`[otaless-shop] NEEDS A PERSON: buy answer not known and ${mine.length === 0 ? 'no' : 'more than one'} new order matches it (name, amount, currency) - none taken, no link`);
629
+ return { outcome: 'unknown', needsPerson: true };
630
+ }
631
+ made = madeFromRow(mine[0]);
632
+ }
633
+ catch {
634
+ log('[otaless-shop] NEEDS A PERSON: buy answer not known and the orders could not be read - no link');
635
+ return { outcome: 'unknown', needsPerson: true };
636
+ }
637
+ }
638
+ return settle(token, p, lang, it, qty, shown, made);
639
+ },
640
+ // An answer not known keeps the same buy shut for ten minutes: the orders say what happened.
641
+ (r) => r.outcome === 'unknown');
642
+ };
643
+ const sameName = (a, b) => {
644
+ const x = lower(a);
645
+ const y = lower(b);
646
+ return !!x && x === y;
647
+ };
648
+ /** What was made, checked against what the guest was shown - and acted on. */
649
+ const settle = async (token, provider, lang, it, qty, shown, made) => {
650
+ const asOrder = (status, link) => ({
651
+ id: made.id ?? '',
652
+ name: it.name,
653
+ totalCents: made.totalCents ?? 0,
654
+ currency: made.currency ?? shown.currency,
655
+ status,
656
+ ...(link ? { checkoutUrl: link } : {}),
657
+ });
658
+ const allowed = shown.unitCents * qty;
659
+ // ⚠️ CHARGED, AND NOT BY THE GUEST (decision D): the order is kept - cancelling or refunding
660
+ // is money moving once more - and a person is told. Said as it is, never as "paid at checkout".
661
+ if (made.charged) {
662
+ log(`[otaless-shop] NEEDS A PERSON: shop order ${made.id ?? '(no id)'} was charged by the backend to a card the guest did not choose${made.totalCents !== undefined ? ` (${made.currency ?? '?'} ${(made.totalCents / 100).toFixed(2)})` : ''}`);
663
+ return {
664
+ outcome: 'charged-without-asking',
665
+ order: asOrder(made.status === 'awaiting-payment' ? 'paid' : made.status),
666
+ ...(made.totalCents !== undefined ? { totalCents: made.totalCents } : {}),
667
+ ...(made.currency ? { currency: made.currency } : {}),
668
+ overShown: made.totalCents !== undefined && made.totalCents > allowed,
669
+ needsPerson: true,
670
+ };
671
+ }
672
+ if (made.failed || made.status === 'cancelled' || made.status === 'refunded')
673
+ return { outcome: 'refused', why: 'backend' };
674
+ // A state we do not know, with or without an order behind it: not guessed at.
675
+ if (made.status !== 'awaiting-payment') {
676
+ log('[otaless-shop] buy answered a state not known - the orders will say');
677
+ return { outcome: 'unknown' };
678
+ }
679
+ const wrongAmount = made.totalCents === undefined ||
680
+ made.totalCents <= 0 ||
681
+ made.totalCents > allowed ||
682
+ made.currency !== shown.currency;
683
+ const link = checkoutLinkOf(made.checkoutRaw);
684
+ const bad = wrongAmount
685
+ ? 'wrong-amount'
686
+ : link
687
+ ? undefined
688
+ : 'bad-link';
689
+ if (bad) {
690
+ // ⚠️ CANCELLED AT ONCE, AND NO LINK EITHER WAY. If the cancel does not work out, the order is
691
+ // still there, awaiting payment: a person looks (the log has its id).
692
+ let cancelled = false;
693
+ if (made.id)
694
+ cancelled = (await sendCancel(token, provider, made.id, lang)) === 'cancelled';
695
+ log(cancelled
696
+ ? `[otaless-shop] buy of order ${made.id}: ${bad === 'wrong-amount' ? 'amount or currency did not match' : 'checkout page not allowed'} - cancelled`
697
+ : `[otaless-shop] NEEDS A PERSON: shop order ${made.id ?? '(no id)'} has ${bad === 'wrong-amount' ? 'an amount or currency that does not match' : 'a checkout page that is not allowed'} and could not be cancelled`);
698
+ return {
699
+ outcome: bad,
700
+ cancelled,
701
+ needsPerson: !cancelled,
702
+ ...(made.id ? { orderId: made.id } : {}),
703
+ };
704
+ }
705
+ if (!made.id)
706
+ return { outcome: 'unknown' };
707
+ return {
708
+ outcome: 'awaiting-payment',
709
+ order: asOrder('awaiting-payment', link),
710
+ checkoutUrl: link,
711
+ };
712
+ };
713
+ return { items, item, orders, cancel, refund, buy };
714
+ };
715
+ //# sourceMappingURL=shop.js.map