@curless/hotel-storefront 0.61.1 → 0.62.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.
- package/dist/account/fake-ota.d.ts +69 -0
- package/dist/account/fake-ota.d.ts.map +1 -0
- package/dist/account/fake-ota.js +264 -0
- package/dist/account/fake-ota.js.map +1 -0
- package/dist/account/index.d.ts +32 -22
- package/dist/account/index.d.ts.map +1 -1
- package/dist/account/index.js +194 -195
- package/dist/account/index.js.map +1 -1
- package/dist/account/mask.d.ts +15 -0
- package/dist/account/mask.d.ts.map +1 -0
- package/dist/account/mask.js +51 -0
- package/dist/account/mask.js.map +1 -0
- package/dist/account/ota-member.d.ts +99 -14
- package/dist/account/ota-member.d.ts.map +1 -1
- package/dist/account/ota-member.js +167 -48
- package/dist/account/ota-member.js.map +1 -1
- package/dist/account/pages.d.ts +2 -1
- package/dist/account/pages.d.ts.map +1 -1
- package/dist/account/pages.js +10 -5
- package/dist/account/pages.js.map +1 -1
- package/dist/account/requests.d.ts +1 -1
- package/dist/account/requests.js +2 -2
- package/dist/account/requests.js.map +1 -1
- package/dist/account/said.js +2 -2
- package/dist/account/said.js.map +1 -1
- package/dist/account/store.d.ts +16 -15
- package/dist/account/store.d.ts.map +1 -1
- package/dist/account/store.js +29 -23
- package/dist/account/store.js.map +1 -1
- package/dist/otaless/backend.d.ts +19 -3
- package/dist/otaless/backend.d.ts.map +1 -1
- package/dist/otaless/backend.js +51 -20
- package/dist/otaless/backend.js.map +1 -1
- package/dist/otaless/booking.d.ts +189 -0
- package/dist/otaless/booking.d.ts.map +1 -0
- package/dist/otaless/booking.js +1227 -0
- package/dist/otaless/booking.js.map +1 -0
- package/dist/otaless/client.d.ts +180 -0
- package/dist/otaless/client.d.ts.map +1 -1
- package/dist/otaless/client.js +166 -15
- package/dist/otaless/client.js.map +1 -1
- package/dist/otaless/fake.d.ts +73 -0
- package/dist/otaless/fake.d.ts.map +1 -1
- package/dist/otaless/fake.js +270 -2
- package/dist/otaless/fake.js.map +1 -1
- package/dist/otaless/make.d.ts +2 -0
- package/dist/otaless/make.d.ts.map +1 -1
- package/dist/otaless/make.js +32 -0
- package/dist/otaless/make.js.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +4 -1
- package/dist/server.js.map +1 -1
- package/package.json +1 -1
- package/dist/account/fake-mall.d.ts +0 -61
- package/dist/account/fake-mall.d.ts.map +0 -1
- package/dist/account/fake-mall.js +0 -239
- package/dist/account/fake-mall.js.map +0 -1
- package/dist/account/mall.d.ts +0 -94
- package/dist/account/mall.d.ts.map +0 -1
- package/dist/account/mall.js +0 -255
- package/dist/account/mall.js.map +0 -1
|
@@ -0,0 +1,1227 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { maskEmail, maskMobile } from '../account/mask.js';
|
|
3
|
+
import { guestTooLong } from '../backend.js';
|
|
4
|
+
import { nights as nightsOf } from '../dates.js';
|
|
5
|
+
import { movedSince } from '../huazhu/backend.js';
|
|
6
|
+
import { money, toMinor } from '../money.js';
|
|
7
|
+
import { CHANNEL_SESSION_EXPIRED, NOT_SIGNED_IN, OtalessBusy, OtalessError, REPEAT_SUBMIT, SESSION_ID, forTheLog, } from './client.js';
|
|
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:
|
|
11
|
+
//
|
|
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.
|
|
22
|
+
// - AN ORDER IS ACTED ON ONLY IF IT IS IN OUR OWN RECORD, as this guest's
|
|
23
|
+
// (their sign-in's member id): the id sent to the backend is the record's,
|
|
24
|
+
// never the model's.
|
|
25
|
+
// - BOTH CREDENTIALS FROM THE GUEST'S SIGN-IN AT THE GROUP (robin 11-10: the
|
|
26
|
+
// backend's own `/ota/sign-in`, its `accessToken` and `mcpSessionId` -
|
|
27
|
+
// `bookingAuth`), never kept here; a session this connector opens after a
|
|
28
|
+
// 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.
|
|
30
|
+
//
|
|
31
|
+
// ⚠️ NOTHING HERE IS REACHED WHILE THE DEPLOYMENT IS READ-ONLY: the tools that
|
|
32
|
+
// would call it are not offered (`capabilities.readOnly`, kept on until the
|
|
33
|
+
// backend answers questions #50-#52 and robin agrees - 总线程 11-10).
|
|
34
|
+
/** How long terms sent back for agreement are kept for the guest to agree to (§12.1). */
|
|
35
|
+
export const TERMS_MS = 10 * 60_000;
|
|
36
|
+
/** How long a group's `Mcp-Session-Id` is kept unused (§12.3). */
|
|
37
|
+
export const SESSION_IDLE_MS = 2 * 60 * 60_000;
|
|
38
|
+
/** A payment's status is asked for at most this often per order (§12.1, 15). */
|
|
39
|
+
export const STATUS_EVERY_MS = 10_000;
|
|
40
|
+
/** The same stay for the same account asked for again within this long is the first order (a second press, a lost answer). */
|
|
41
|
+
export const REPEAT_MS = 10 * 60_000;
|
|
42
|
+
/** The longest terms shown word for word - longer is refused rather than cut. */
|
|
43
|
+
export const TERMS_MAX = 50_000;
|
|
44
|
+
/** A guest's reason for cancelling, as the group's staff are sent it. */
|
|
45
|
+
const REASON_MAX = 200;
|
|
46
|
+
const SESSIONS_MAX = 20_000;
|
|
47
|
+
const PENDING_MAX = 2_000;
|
|
48
|
+
const PENDING_PER_ACCOUNT = 5;
|
|
49
|
+
/** The orders checked on one look at the bookings - newest first; the rest wait for the next look. */
|
|
50
|
+
const CHECKED_PER_LOOK = 5;
|
|
51
|
+
/**
|
|
52
|
+
* The payment pages a guest may be sent to, until a deployment says otherwise
|
|
53
|
+
* (总线程 11-10: the two the document's own examples name). Exact host names:
|
|
54
|
+
* no wildcard, no other port.
|
|
55
|
+
*/
|
|
56
|
+
export const DEFAULT_CHECKOUT_HOSTS = ['mcp.curless.ai', 'pay.discoverasr.com'];
|
|
57
|
+
const refusal = (code, message) => Object.assign(new Error(message), { code });
|
|
58
|
+
const num = (v) => {
|
|
59
|
+
const n = typeof v === 'string' && v.trim() ? Number(v) : v;
|
|
60
|
+
return typeof n === 'number' && Number.isFinite(n) ? n : undefined;
|
|
61
|
+
};
|
|
62
|
+
const text = (v) => typeof v === 'string' && v.trim() ? v.trim() : undefined;
|
|
63
|
+
const hash = (s, n = 22) => createHash('sha256').update(s).digest('base64url').slice(0, n);
|
|
64
|
+
/** An amount the backend sent, as money - or nothing, when it sent no usable amount or currency. */
|
|
65
|
+
const moneyOf = (amount, currency) => {
|
|
66
|
+
const a = num(amount);
|
|
67
|
+
const c = text(currency)?.toUpperCase();
|
|
68
|
+
if (a === undefined || !c || !/^[A-Z]{3}$/.test(c) || a < 0)
|
|
69
|
+
return undefined;
|
|
70
|
+
return money(toMinor(a, c), c);
|
|
71
|
+
};
|
|
72
|
+
const same = (a, b) => !!a && !!b && a.currency === b.currency && a.minor === b.minor;
|
|
73
|
+
/**
|
|
74
|
+
* Where a payment page may send the guest: `https:`, an exact host on the
|
|
75
|
+
* list, no other port, no user in it - or nothing (总线程 11-10).
|
|
76
|
+
*/
|
|
77
|
+
export const payPageOf = (raw, hosts) => {
|
|
78
|
+
if (!raw)
|
|
79
|
+
return undefined;
|
|
80
|
+
let u;
|
|
81
|
+
try {
|
|
82
|
+
u = new URL(raw);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
const host = u.hostname.toLowerCase();
|
|
88
|
+
if (u.protocol !== 'https:' || u.username || u.password || u.port)
|
|
89
|
+
return undefined;
|
|
90
|
+
if (!hosts.includes(host))
|
|
91
|
+
return undefined;
|
|
92
|
+
return { url: u.toString(), host };
|
|
93
|
+
};
|
|
94
|
+
/** The host of a URL for the log - never its path or query (they carry the payment token). */
|
|
95
|
+
const hostForLog = (raw) => {
|
|
96
|
+
try {
|
|
97
|
+
return forTheLog(new URL(String(raw)).host || '?');
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return 'not a URL';
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
/** The first of `keys` in `o` that is words - the terms' text and token under whatever name the group's tool gave them. */
|
|
104
|
+
const firstText = (o, keys) => {
|
|
105
|
+
for (const k of keys) {
|
|
106
|
+
const v = o?.[k];
|
|
107
|
+
if (typeof v === 'string' && v.trim())
|
|
108
|
+
return v;
|
|
109
|
+
}
|
|
110
|
+
return undefined;
|
|
111
|
+
};
|
|
112
|
+
const TERMS_TEXT_KEYS = ['terms', 'terms_text', 'termsText', 'terms_content', 'termsContent'];
|
|
113
|
+
const TERMS_TOKEN_KEYS = ['terms_token', 'termsToken'];
|
|
114
|
+
const isCode = (err, code) => err instanceof OtalessError && !(err instanceof OtalessBusy) && err.backendCode === code;
|
|
115
|
+
/**
|
|
116
|
+
* Sent, and no answer it could be read by: whether it was done is not known -
|
|
117
|
+
* no answer, an answer cut off (even on an HTTP 200), an HTTP 5xx with no code
|
|
118
|
+
* of the backend's. Only a 4xx with none is a request that was not taken.
|
|
119
|
+
*/
|
|
120
|
+
const unanswered = (err) => err instanceof OtalessError &&
|
|
121
|
+
!(err instanceof OtalessBusy) &&
|
|
122
|
+
err.backendCode === undefined &&
|
|
123
|
+
!(err.status !== undefined && err.status >= 400 && err.status < 500);
|
|
124
|
+
export const createOtalessBookings = (deps) => {
|
|
125
|
+
const { client, now, log } = deps;
|
|
126
|
+
const iso = (t = now()) => new Date(t).toISOString();
|
|
127
|
+
// ── what is kept ──────────────────────────────────────────────────────────
|
|
128
|
+
const orders = new Map();
|
|
129
|
+
const kept = deps.state?.read();
|
|
130
|
+
for (const r of kept?.orders ?? [])
|
|
131
|
+
if (r && typeof r.id === 'string')
|
|
132
|
+
orders.set(r.id, r);
|
|
133
|
+
deps.state?.bind(() => ({ orders: [...orders.values()] }));
|
|
134
|
+
const save = () => deps.state?.changed();
|
|
135
|
+
/** Payment links, by order id - in memory only (questions #54). */
|
|
136
|
+
const payLinks = new Map();
|
|
137
|
+
/** Group sessions by `owner|group` - in memory only (§12.3). */
|
|
138
|
+
const sessions = new Map();
|
|
139
|
+
const pending = new Map();
|
|
140
|
+
/** Add-ons last listed per order, to book only one of them (11). */
|
|
141
|
+
const listedAddons = new Map();
|
|
142
|
+
/** Orders being asked for now, by owner and stay: the same press twice sends one. */
|
|
143
|
+
const inFlight = new Set();
|
|
144
|
+
/** When each order's payment status was last asked. */
|
|
145
|
+
const checkedAt = new Map();
|
|
146
|
+
const counts = {
|
|
147
|
+
initRefused: 0,
|
|
148
|
+
released: 0,
|
|
149
|
+
releaseFailed: 0,
|
|
150
|
+
termsSent: 0,
|
|
151
|
+
termsAgreed: 0,
|
|
152
|
+
sessionRetried: 0,
|
|
153
|
+
};
|
|
154
|
+
const keyOf = (who) => who.tripOwner ?? who.sessionId;
|
|
155
|
+
const accountFor = (who, group) => {
|
|
156
|
+
const key = keyOf(who);
|
|
157
|
+
const a = deps.auth?.bookingAuth?.(key, group);
|
|
158
|
+
if (!a?.token)
|
|
159
|
+
return undefined;
|
|
160
|
+
const session = text(a.mcpSessionId);
|
|
161
|
+
return {
|
|
162
|
+
owner: a.account ? hash(`otaless-member:${a.account}`) : hash(`otaless-conversation:${key}`),
|
|
163
|
+
token: a.token,
|
|
164
|
+
...(session && SESSION_ID.test(session) ? { session } : {}),
|
|
165
|
+
key,
|
|
166
|
+
group,
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
const signInFirst = (groups) => refusal('sign-in', `Nothing was booked: booking at ${groups.map((g) => deps.groupOf(g).name).join(' and ')} needs the guest signed in there through their ${deps.brand} account - ask them to sign in first.`);
|
|
170
|
+
/**
|
|
171
|
+
* One of this guest's orders, by its id or the code the guest quotes, with
|
|
172
|
+
* their sign-in at its group - never an order of anyone else, and never one
|
|
173
|
+
* at a group they are not signed in to now.
|
|
174
|
+
*/
|
|
175
|
+
const ownOrder = (ref, who) => {
|
|
176
|
+
const id = ref.trim();
|
|
177
|
+
if (!id || id.length > 120)
|
|
178
|
+
return undefined;
|
|
179
|
+
const low = id.toLowerCase();
|
|
180
|
+
const named = orders.has(id)
|
|
181
|
+
? [orders.get(id)]
|
|
182
|
+
: [...orders.values()].filter((o) => !!o.code && o.code.toLowerCase() === low);
|
|
183
|
+
for (const r of named) {
|
|
184
|
+
const acct = accountFor(who, r.group);
|
|
185
|
+
if (acct && acct.owner === r.owner)
|
|
186
|
+
return { r, acct };
|
|
187
|
+
}
|
|
188
|
+
return undefined;
|
|
189
|
+
};
|
|
190
|
+
// ── the group's session (§12.3) ───────────────────────────────────────────
|
|
191
|
+
/**
|
|
192
|
+
* Sessions this connector opened itself (16, after a 4012) or was written
|
|
193
|
+
* back, by the sign-in's token and the group: a new sign-in never runs in an
|
|
194
|
+
* old sign-in's session.
|
|
195
|
+
*/
|
|
196
|
+
const sessionKey = (acct) => `${hash(acct.token)}|${acct.group}`;
|
|
197
|
+
const keep = (acct, id) => {
|
|
198
|
+
if (!id || !SESSION_ID.test(id))
|
|
199
|
+
return;
|
|
200
|
+
const k = sessionKey(acct);
|
|
201
|
+
sessions.delete(k);
|
|
202
|
+
sessions.set(k, { id, at: now() });
|
|
203
|
+
while (sessions.size > SESSIONS_MAX) {
|
|
204
|
+
const first = sessions.keys().next().value;
|
|
205
|
+
if (first === undefined)
|
|
206
|
+
break;
|
|
207
|
+
sessions.delete(first);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
/** A fresh handshake (16) - with the sign-in's token, never anonymous (总线程 11-10). */
|
|
211
|
+
const handshake = async (acct, who) => {
|
|
212
|
+
const group = acct.group;
|
|
213
|
+
let sent;
|
|
214
|
+
try {
|
|
215
|
+
sent = await client.initialize(group, { token: acct.token }, deps.callerOf(who));
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
if (err instanceof OtalessError &&
|
|
219
|
+
!(err instanceof OtalessBusy) &&
|
|
220
|
+
err.backendCode !== undefined) {
|
|
221
|
+
// ⚠️ RECORDED, AND ASKED ABOUT (总线程 11-10): 16 with the member's token refused.
|
|
222
|
+
counts.initRefused += 1;
|
|
223
|
+
log(`[otaless] initialize for ${group} with the member's token was refused (code ${err.backendCode}) - questions, 11-10 evening`);
|
|
224
|
+
}
|
|
225
|
+
throw err;
|
|
226
|
+
}
|
|
227
|
+
const id = text(sent.data?.mcpSessionId) ?? sent.session;
|
|
228
|
+
if (sent.data?.success === false || !id || !SESSION_ID.test(id)) {
|
|
229
|
+
counts.initRefused += 1;
|
|
230
|
+
log(`[otaless] initialize for ${group} gave no usable Mcp-Session-Id`);
|
|
231
|
+
throw new OtalessError('the Otaless hotel backend gave no session', 200);
|
|
232
|
+
}
|
|
233
|
+
keep(acct, id);
|
|
234
|
+
return id;
|
|
235
|
+
};
|
|
236
|
+
/** The session to run in: one opened here since, else the sign-in's own, else a handshake. */
|
|
237
|
+
const sessionFor = async (acct, who) => {
|
|
238
|
+
const k = sessionKey(acct);
|
|
239
|
+
const s = sessions.get(k);
|
|
240
|
+
if (s && now() - s.at < SESSION_IDLE_MS) {
|
|
241
|
+
s.at = now();
|
|
242
|
+
return s.id;
|
|
243
|
+
}
|
|
244
|
+
sessions.delete(k);
|
|
245
|
+
return acct.session ?? (await handshake(acct, who));
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* One call of items 8-15 with both credentials. A 4012 is answered with one
|
|
249
|
+
* new handshake - with the same token - and ONE more try (总线程 11-10, rule
|
|
250
|
+
* 7); a second 4012 ends it: the sign-in at that group goes, and the guest
|
|
251
|
+
* signs in again. A 401 is that sign-in, over.
|
|
252
|
+
*
|
|
253
|
+
* ⚠️ A WRITE IS SENT AGAIN AFTER A 4012 ONLY BECAUSE THE DOCUMENT SAYS 4012 IS
|
|
254
|
+
* THE SESSION CHECK, MADE BEFORE THE GROUP IS ASKED (its 1.4,
|
|
255
|
+
* `requireMemberAndMcpSession`): nothing was made the first time. If the
|
|
256
|
+
* backend ever answers 4012 after asking the group, this is a second order.
|
|
257
|
+
*/
|
|
258
|
+
const withSession = async (acct, who, call) => {
|
|
259
|
+
const first = await sessionFor(acct, who);
|
|
260
|
+
try {
|
|
261
|
+
const r = await call({ token: acct.token, session: first });
|
|
262
|
+
if (r.session && r.session !== first)
|
|
263
|
+
keep(acct, r.session);
|
|
264
|
+
return r.data;
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
if (isCode(err, NOT_SIGNED_IN))
|
|
268
|
+
throw signedOut(acct);
|
|
269
|
+
if (!isCode(err, CHANNEL_SESSION_EXPIRED))
|
|
270
|
+
throw err;
|
|
271
|
+
}
|
|
272
|
+
counts.sessionRetried += 1;
|
|
273
|
+
sessions.delete(sessionKey(acct));
|
|
274
|
+
const again = await handshake(acct, who);
|
|
275
|
+
try {
|
|
276
|
+
const r = await call({ token: acct.token, session: again });
|
|
277
|
+
if (r.session && r.session !== again)
|
|
278
|
+
keep(acct, r.session);
|
|
279
|
+
return r.data;
|
|
280
|
+
}
|
|
281
|
+
catch (err) {
|
|
282
|
+
if (isCode(err, NOT_SIGNED_IN))
|
|
283
|
+
throw signedOut(acct);
|
|
284
|
+
if (!isCode(err, CHANNEL_SESSION_EXPIRED))
|
|
285
|
+
throw err;
|
|
286
|
+
sessions.delete(sessionKey(acct));
|
|
287
|
+
deps.auth?.expired?.(acct.key, acct.group);
|
|
288
|
+
const name = deps.groupOf(acct.group).name;
|
|
289
|
+
throw refusal('session-expired', `${name} says the guest's sign-in there is over, so nothing was done - ask them to sign in to ${name} through their ${deps.brand} account again.`);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
const signedOut = (acct) => {
|
|
293
|
+
sessions.delete(sessionKey(acct));
|
|
294
|
+
deps.auth?.expired?.(acct.key, acct.group);
|
|
295
|
+
const name = deps.groupOf(acct.group).name;
|
|
296
|
+
return refusal('signed-out', `The guest's sign-in at ${name} is over, so nothing was done - ask them to sign in to ${name} through their ${deps.brand} account again.`);
|
|
297
|
+
};
|
|
298
|
+
// ── an order, as a booking ────────────────────────────────────────────────
|
|
299
|
+
const paymentOf = (r) => {
|
|
300
|
+
const amount = r.charged ?? r.quoted;
|
|
301
|
+
if (r.refund)
|
|
302
|
+
return {
|
|
303
|
+
method: 'card',
|
|
304
|
+
amount,
|
|
305
|
+
status: r.refund.status === 'refunded' ? 'refunded' : 'refunding',
|
|
306
|
+
...(r.refund.amount && !same(r.refund.amount, amount)
|
|
307
|
+
? { refundAmount: r.refund.amount }
|
|
308
|
+
: {}),
|
|
309
|
+
};
|
|
310
|
+
if (r.paid)
|
|
311
|
+
return { method: 'card', amount, status: 'paid' };
|
|
312
|
+
if (r.status === 'awaiting-payment') {
|
|
313
|
+
const url = payLinks.get(r.id);
|
|
314
|
+
return {
|
|
315
|
+
method: 'card',
|
|
316
|
+
amount,
|
|
317
|
+
status: 'awaiting',
|
|
318
|
+
...(url ? { url } : {}),
|
|
319
|
+
...(r.payBy ? { payBy: r.payBy } : {}),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
if (r.status === 'expired' || (r.status === 'cancelled' && r.payHost))
|
|
323
|
+
return { method: 'card', amount, status: 'lapsed' };
|
|
324
|
+
return undefined;
|
|
325
|
+
};
|
|
326
|
+
const toBooking = (r) => {
|
|
327
|
+
const n = nightsOf(r.stay.checkIn, r.stay.checkOut);
|
|
328
|
+
const line = {
|
|
329
|
+
kind: 'room',
|
|
330
|
+
hotelId: r.hotelId,
|
|
331
|
+
hotelName: r.hotelName,
|
|
332
|
+
...(r.hotelNames ? { hotelNames: r.hotelNames } : {}),
|
|
333
|
+
roomRef: r.roomId,
|
|
334
|
+
title: r.roomName,
|
|
335
|
+
stay: r.stay,
|
|
336
|
+
nights: n,
|
|
337
|
+
quantity: r.rooms,
|
|
338
|
+
unit: money(Math.round(r.quoted.minor / Math.max(1, n * r.rooms)), r.quoted.currency),
|
|
339
|
+
total: r.quoted,
|
|
340
|
+
terms: r.terms ?? '',
|
|
341
|
+
day: r.stay.checkIn,
|
|
342
|
+
};
|
|
343
|
+
const payment = paymentOf(r);
|
|
344
|
+
return {
|
|
345
|
+
id: r.id,
|
|
346
|
+
supplier: r.group,
|
|
347
|
+
confirmationCode: r.code || r.id,
|
|
348
|
+
status: r.status,
|
|
349
|
+
createdAt: r.createdAt,
|
|
350
|
+
hotelId: r.hotelId,
|
|
351
|
+
hotelName: r.hotelName,
|
|
352
|
+
...(r.hotelNames ? { hotelNames: r.hotelNames } : {}),
|
|
353
|
+
stay: r.stay,
|
|
354
|
+
...(payment ? { payment } : {}),
|
|
355
|
+
guest: r.guest,
|
|
356
|
+
quote: {
|
|
357
|
+
lines: [line],
|
|
358
|
+
subtotal: r.quoted,
|
|
359
|
+
taxesAndFees: money(0, r.quoted.currency),
|
|
360
|
+
taxesIncluded: true,
|
|
361
|
+
total: r.quoted,
|
|
362
|
+
stay: r.stay,
|
|
363
|
+
},
|
|
364
|
+
...(r.cancelledAt ? { cancelledAt: r.cancelledAt } : {}),
|
|
365
|
+
};
|
|
366
|
+
};
|
|
367
|
+
const failedStay = (a, why, code) => ({
|
|
368
|
+
hotelId: a.hotel.id,
|
|
369
|
+
hotelName: a.hotel.name,
|
|
370
|
+
...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
|
|
371
|
+
stay: a.stay,
|
|
372
|
+
roomName: a.roomName,
|
|
373
|
+
why,
|
|
374
|
+
...(code ? { code } : {}),
|
|
375
|
+
});
|
|
376
|
+
const recordOf = (a, id, code, status) => ({
|
|
377
|
+
id,
|
|
378
|
+
code,
|
|
379
|
+
group: a.group,
|
|
380
|
+
owner: a.acct.owner,
|
|
381
|
+
from: hash(`conversation:${a.acct.key}`, 12),
|
|
382
|
+
hotelId: a.hotel.id,
|
|
383
|
+
hotelName: a.hotel.name,
|
|
384
|
+
...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
|
|
385
|
+
roomId: a.roomId,
|
|
386
|
+
roomName: a.roomName,
|
|
387
|
+
stay: a.stay,
|
|
388
|
+
rooms: a.rooms,
|
|
389
|
+
quoted: a.pairs.orig,
|
|
390
|
+
quotedUsd: a.pairs.usd,
|
|
391
|
+
status,
|
|
392
|
+
...(a.terms ? { terms: a.terms } : {}),
|
|
393
|
+
guest: {
|
|
394
|
+
name: a.guest.name,
|
|
395
|
+
email: maskEmail(a.guest.email) ?? '',
|
|
396
|
+
...(a.guest.phone ? { phone: maskMobile(a.guest.phone) ?? '' } : {}),
|
|
397
|
+
},
|
|
398
|
+
createdAt: iso(),
|
|
399
|
+
});
|
|
400
|
+
const put = (r) => {
|
|
401
|
+
orders.set(r.id, r);
|
|
402
|
+
save();
|
|
403
|
+
};
|
|
404
|
+
/**
|
|
405
|
+
* Lets an order we will not hand on go at once - 14 while it waits for a
|
|
406
|
+
* payment, 9 if it came back confirmed. ⚠️ A FAILURE TO LET IT GO NEEDS A
|
|
407
|
+
* PERSON: it is logged as such and kept on the record.
|
|
408
|
+
*/
|
|
409
|
+
const release = async (a, r, why, confirmed) => {
|
|
410
|
+
r.released = why;
|
|
411
|
+
counts.released += 1;
|
|
412
|
+
try {
|
|
413
|
+
const done = await withSession(a.acct, a.who, (cred) => confirmed
|
|
414
|
+
? client.cancelBooking({
|
|
415
|
+
unifiedOrderId: r.id,
|
|
416
|
+
providerCode: a.group,
|
|
417
|
+
reason: 'price or payment page not as quoted',
|
|
418
|
+
}, cred, deps.callerOf(a.who))
|
|
419
|
+
: client.cancelCheckout({
|
|
420
|
+
unifiedOrderId: r.id,
|
|
421
|
+
providerCode: a.group,
|
|
422
|
+
reason: 'price or payment page not as quoted',
|
|
423
|
+
}, cred, deps.callerOf(a.who)));
|
|
424
|
+
if (done?.success === false)
|
|
425
|
+
throw new Error('not cancelled');
|
|
426
|
+
r.status = 'cancelled';
|
|
427
|
+
r.cancelledAt = iso();
|
|
428
|
+
put(r);
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
catch (err) {
|
|
432
|
+
r.releaseFailed = true;
|
|
433
|
+
counts.releaseFailed += 1;
|
|
434
|
+
log(`[otaless] NEEDS A PERSON: order ${forTheLog(r.id)} at ${a.group} (${why}) could not be let go: ${err instanceof Error ? err.name : 'error'}`);
|
|
435
|
+
put(r);
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
/** What 13 answered, settled: terms to agree to, an order to hand on, or none. */
|
|
440
|
+
const settle = async (a, w) => {
|
|
441
|
+
const g = deps.groupOf(a.group);
|
|
442
|
+
const status = String(w?.status ?? '')
|
|
443
|
+
.trim()
|
|
444
|
+
.toUpperCase();
|
|
445
|
+
// ── terms the guest must agree to (§12.4) ──
|
|
446
|
+
if (/TERMS/.test(status)) {
|
|
447
|
+
const words = firstText(w?.extraData, TERMS_TEXT_KEYS);
|
|
448
|
+
const token = firstText(w?.extraData, TERMS_TOKEN_KEYS);
|
|
449
|
+
// ⚠️ NEVER TERMS NOBODY SAW: none sent, or none to send the agreement back with - nothing.
|
|
450
|
+
if (!words || !token || token.length > 512 || words.length > TERMS_MAX)
|
|
451
|
+
return {
|
|
452
|
+
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.`),
|
|
453
|
+
};
|
|
454
|
+
const mine = [...pending.values()].filter((p) => p.owner === a.acct.owner);
|
|
455
|
+
for (const p of mine.slice(0, Math.max(0, mine.length - PENDING_PER_ACCOUNT + 1)))
|
|
456
|
+
pending.delete(p.ref);
|
|
457
|
+
const ref = randomBytes(18).toString('base64url');
|
|
458
|
+
const terms = {
|
|
459
|
+
ref,
|
|
460
|
+
group: a.group,
|
|
461
|
+
groupName: g.name,
|
|
462
|
+
...(g.names ? { groupNames: g.names } : {}),
|
|
463
|
+
hotelId: a.hotel.id,
|
|
464
|
+
hotelName: a.hotel.name,
|
|
465
|
+
...(a.hotel.names?.name ? { hotelNames: a.hotel.names.name } : {}),
|
|
466
|
+
roomName: a.roomName,
|
|
467
|
+
stay: a.stay,
|
|
468
|
+
rooms: a.rooms,
|
|
469
|
+
total: a.pairs.orig,
|
|
470
|
+
text: words,
|
|
471
|
+
until: iso(now() + TERMS_MS),
|
|
472
|
+
};
|
|
473
|
+
pending.set(ref, {
|
|
474
|
+
...terms,
|
|
475
|
+
owner: a.acct.owner,
|
|
476
|
+
key: a.acct.key,
|
|
477
|
+
tokenOfTerms: token,
|
|
478
|
+
body: a.body,
|
|
479
|
+
pairs: a.pairs,
|
|
480
|
+
roomId: a.roomId,
|
|
481
|
+
...(a.terms ? { terms: a.terms } : {}),
|
|
482
|
+
at: now(),
|
|
483
|
+
});
|
|
484
|
+
while (pending.size > PENDING_MAX) {
|
|
485
|
+
const first = pending.keys().next().value;
|
|
486
|
+
if (first === undefined)
|
|
487
|
+
break;
|
|
488
|
+
pending.delete(first);
|
|
489
|
+
}
|
|
490
|
+
counts.termsSent += 1;
|
|
491
|
+
return { terms };
|
|
492
|
+
}
|
|
493
|
+
// ── refused ──
|
|
494
|
+
const err = text(w?.errorMessage);
|
|
495
|
+
if (!w || w.success === false || status === 'FAILED' || err) {
|
|
496
|
+
if (err)
|
|
497
|
+
log(`[otaless] checkout at ${a.group} refused: "${forTheLog(err, [a.guest.name, a.guest.email, a.guest.phone])}"`);
|
|
498
|
+
return {
|
|
499
|
+
failed: failedStay(a, `${g.name} did not take the booking, so nothing was booked or charged.`),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
const id = text(w.unifiedOrderId);
|
|
503
|
+
const code = text(w.originalOrderId) ?? '';
|
|
504
|
+
const page = text(w.checkoutUrl);
|
|
505
|
+
// ⚠️ "CONFIRMED" WITH A PAYMENT PAGE IS WAITING FOR ITS PAYMENT (questions #53,
|
|
506
|
+
// the document's own example): paid is what 15 says, never this status.
|
|
507
|
+
const confirmed = !page && (status === 'CONFIRMED' || status === 'PAID');
|
|
508
|
+
if (!id) {
|
|
509
|
+
// Something may be held, under a number we were not told: kept to look for (12).
|
|
510
|
+
const r = recordOf(a, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
|
|
511
|
+
put(r);
|
|
512
|
+
log(`[otaless] checkout at ${a.group} answered with no order id (status ${forTheLog(status || '?')})`);
|
|
513
|
+
return { booked: toBooking(r) };
|
|
514
|
+
}
|
|
515
|
+
const r = recordOf(a, id, code, confirmed ? 'confirmed' : 'awaiting-payment');
|
|
516
|
+
if (w.cancelPolicy && text(w.cancelPolicy))
|
|
517
|
+
r.terms = text(w.cancelPolicy);
|
|
518
|
+
const charged = moneyOf(w.totalAmount, w.currency);
|
|
519
|
+
if (charged)
|
|
520
|
+
r.charged = charged;
|
|
521
|
+
// ── the amount (总线程 11-10: either of the quote's two) ──
|
|
522
|
+
if (!charged || !(same(charged, a.pairs.orig) || same(charged, a.pairs.usd))) {
|
|
523
|
+
const gone = await release(a, r, charged ? 'price' : 'amount', confirmed);
|
|
524
|
+
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`);
|
|
525
|
+
// ⚠️ CONFIRMED, AND NOT UNDONE: a stay is held at another amount - said
|
|
526
|
+
// as that, and listed, never as "not booked" (a person is told: the log).
|
|
527
|
+
if (confirmed && !gone)
|
|
528
|
+
return {
|
|
529
|
+
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'),
|
|
530
|
+
};
|
|
531
|
+
return {
|
|
532
|
+
failed: failedStay(a, charged
|
|
533
|
+
? `${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.`
|
|
534
|
+
: `${g.name} did not say what it would charge, so it was not booked and nothing was charged.`, 'price-changed'),
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
// ── the payment page (总线程 11-10, rule 5) ──
|
|
538
|
+
if (page) {
|
|
539
|
+
const ok = payPageOf(page, deps.checkoutHosts);
|
|
540
|
+
if (!ok) {
|
|
541
|
+
await release(a, r, 'address', confirmed);
|
|
542
|
+
log(`[otaless] checkout at ${a.group} sent a payment page on ${hostForLog(page)}, not on the list - released`);
|
|
543
|
+
return {
|
|
544
|
+
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.`),
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
r.payHost = ok.host;
|
|
548
|
+
payLinks.set(id, ok.url);
|
|
549
|
+
const hold = num(w.extraData?.hold_minutes);
|
|
550
|
+
if (hold !== undefined && hold > 0 && hold <= 24 * 60)
|
|
551
|
+
r.payBy = iso(now() + hold * 60_000);
|
|
552
|
+
}
|
|
553
|
+
else if (!confirmed) {
|
|
554
|
+
// Waiting, and no page to pay on: nothing to hand on - 15 says when it is paid.
|
|
555
|
+
log(`[otaless] checkout at ${a.group} is ${forTheLog(status || '?')} with no payment page`);
|
|
556
|
+
}
|
|
557
|
+
put(r);
|
|
558
|
+
return { booked: toBooking(r) };
|
|
559
|
+
};
|
|
560
|
+
/** Asks 13 for one stay, and settles it. */
|
|
561
|
+
const ask = async (a) => {
|
|
562
|
+
const g = deps.groupOf(a.group);
|
|
563
|
+
let w;
|
|
564
|
+
try {
|
|
565
|
+
w = await withSession(a.acct, a.who, (cred) => client.checkout(a.body, cred, deps.callerOf(a.who)));
|
|
566
|
+
}
|
|
567
|
+
catch (err) {
|
|
568
|
+
if (err instanceof OtalessBusy)
|
|
569
|
+
return {
|
|
570
|
+
failed: failedStay(a, `Not sent to ${g.name}: too many requests just now - ask again in a minute.`, 'limited'),
|
|
571
|
+
};
|
|
572
|
+
// A repeat-submit refusal (10014) of a write: an identical one went in a
|
|
573
|
+
// moment ago, and whether it made an order is not known - the same.
|
|
574
|
+
if (unanswered(err) || isCode(err, REPEAT_SUBMIT)) {
|
|
575
|
+
// ⚠️ NOT SENT AGAIN (§12.1): it may have been made. Kept to look for in
|
|
576
|
+
// the group's order list (12), and said as not known.
|
|
577
|
+
const r = recordOf(a, `pending:${randomBytes(8).toString('hex')}`, '', 'unconfirmed');
|
|
578
|
+
put(r);
|
|
579
|
+
return { booked: toBooking(r) };
|
|
580
|
+
}
|
|
581
|
+
if (err instanceof OtalessError)
|
|
582
|
+
return {
|
|
583
|
+
failed: failedStay(a, `${g.name} did not take the booking, so nothing was booked or charged.`),
|
|
584
|
+
};
|
|
585
|
+
throw err;
|
|
586
|
+
}
|
|
587
|
+
return settle(a, w);
|
|
588
|
+
};
|
|
589
|
+
const requestBooking = async (trip, guest, who) => {
|
|
590
|
+
// ⚠️ SIGNED IN AT EVERY GROUP OF THE TRIP, OR NOTHING IS SENT (robin 11-10:
|
|
591
|
+
// one sign-in per group, the backend's own) - the whole trip is refused
|
|
592
|
+
// before anything is booked.
|
|
593
|
+
const groups = [
|
|
594
|
+
...new Set(trip.lines.flatMap((l) => l.kind === 'room' ? (deps.find(l.hotelId)?.supplier ?? []) : [])),
|
|
595
|
+
];
|
|
596
|
+
const missing = groups.filter((g) => !accountFor(who, g));
|
|
597
|
+
if (missing.length)
|
|
598
|
+
throw signInFirst(missing);
|
|
599
|
+
const name = guest.name?.trim() ?? '';
|
|
600
|
+
const phone = guest.phone?.trim() ?? '';
|
|
601
|
+
if (!name)
|
|
602
|
+
throw refusal('guest', "Nothing was booked: the guest's name is needed.");
|
|
603
|
+
// The backend's `guestPhone` is required (13).
|
|
604
|
+
if (!phone)
|
|
605
|
+
throw refusal('guest', "Nothing was booked: the guest's phone number is needed.");
|
|
606
|
+
const long = guestTooLong({ name, email: guest.email ?? '', phone });
|
|
607
|
+
if (long.length)
|
|
608
|
+
throw refusal('guest', `Nothing was booked: ${long.join(', ')}.`);
|
|
609
|
+
const g0 = { ...guest, name, phone, email: guest.email?.trim() ?? '' };
|
|
610
|
+
const failed = [];
|
|
611
|
+
for (const l of trip.lines) {
|
|
612
|
+
if (l.kind === 'extra') {
|
|
613
|
+
const h = deps.find(l.hotelId);
|
|
614
|
+
failed.push({
|
|
615
|
+
hotelId: l.hotelId,
|
|
616
|
+
hotelName: h?.name ?? l.hotelId,
|
|
617
|
+
stay: { checkIn: '', checkOut: '', guests: 0 },
|
|
618
|
+
why: 'No add-ons are sold before a booking here.',
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// ⚠️ THE PRICE THE GUEST SAW, OR NOTHING (ShownQuote, 2026-10-05 audit P1-3).
|
|
623
|
+
const q = await deps.quote(trip, who);
|
|
624
|
+
const moved = movedSince(trip.shown, q, !q.dropped?.length);
|
|
625
|
+
if (moved)
|
|
626
|
+
throw refusal('price-changed', `Nothing was booked: ${moved}`);
|
|
627
|
+
for (const d of q.dropped ?? []) {
|
|
628
|
+
failed.push({
|
|
629
|
+
hotelId: d.line?.hotelId ?? '',
|
|
630
|
+
hotelName: d.line?.hotelName ?? d.title,
|
|
631
|
+
stay: d.line?.stay ?? { checkIn: '', checkOut: '', guests: 0 },
|
|
632
|
+
...(d.line?.roomName ? { roomName: d.line.roomName } : {}),
|
|
633
|
+
why: d.why,
|
|
634
|
+
...(d.code ? { code: d.code } : {}),
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
const booked = [];
|
|
638
|
+
const terms = [];
|
|
639
|
+
const reused = [];
|
|
640
|
+
for (const line of q.lines) {
|
|
641
|
+
if (line.kind !== 'room' || !line.stay || !line.roomRef)
|
|
642
|
+
continue;
|
|
643
|
+
const hotel = deps.find(line.hotelId);
|
|
644
|
+
const stay = line.stay;
|
|
645
|
+
const rooms = Math.max(1, line.quantity ?? 1);
|
|
646
|
+
const label = {
|
|
647
|
+
hotel: hotel ?? { id: line.hotelId, name: line.hotelName },
|
|
648
|
+
stay,
|
|
649
|
+
roomName: line.title,
|
|
650
|
+
};
|
|
651
|
+
if (!hotel?.supplier) {
|
|
652
|
+
failed.push(failedStay(label, 'That hotel is not known here any more - search for it again.'));
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
const group = hotel.supplier;
|
|
656
|
+
const acct = accountFor(who, group);
|
|
657
|
+
if (!acct) {
|
|
658
|
+
failed.push(failedStay(label, signInFirst([group]).message));
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
// A second press, a lost answer: the order already made for this stay.
|
|
662
|
+
const lockKey = `${acct.owner}|${hotel.id}|${line.roomRef}|${stay.checkIn}|${stay.checkOut}|${rooms}`;
|
|
663
|
+
const before = [...orders.values()].find((o) => o.owner === acct.owner &&
|
|
664
|
+
o.hotelId === hotel.id &&
|
|
665
|
+
o.roomId === line.roomRef &&
|
|
666
|
+
o.stay.checkIn === stay.checkIn &&
|
|
667
|
+
o.stay.checkOut === stay.checkOut &&
|
|
668
|
+
o.rooms === rooms &&
|
|
669
|
+
(o.status === 'awaiting-payment' || o.status === 'unconfirmed') &&
|
|
670
|
+
now() - Date.parse(o.createdAt) < REPEAT_MS);
|
|
671
|
+
if (before) {
|
|
672
|
+
booked.push(toBooking(before));
|
|
673
|
+
reused.push(before.id);
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
if (inFlight.has(lockKey)) {
|
|
677
|
+
failed.push(failedStay(label, 'This stay is being booked already - look at the bookings in a moment rather than booking it again.'));
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
inFlight.add(lockKey);
|
|
681
|
+
try {
|
|
682
|
+
const wire = await deps.quoteWire(hotel, line.roomRef, stay, rooms, who);
|
|
683
|
+
const orig = moneyOf(wire.originalAmount, wire.originalCurrency);
|
|
684
|
+
const usd = text(wire.settlementCurrency)?.toUpperCase() === 'USD'
|
|
685
|
+
? moneyOf(wire.settlementAmount, 'USD')
|
|
686
|
+
: undefined;
|
|
687
|
+
if (!orig || !same(orig, line.total)) {
|
|
688
|
+
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'));
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
// ⚠️ NO USD FIGURE, NO ORDER: 13 is held to `expectedChargeUsd` (§12.1).
|
|
692
|
+
if (!usd || usd.minor <= 0) {
|
|
693
|
+
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.`));
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
const body = {
|
|
697
|
+
unifiedHotelId: hotel.id,
|
|
698
|
+
// ⚠️ AS /rooms SENT IT, prefix and all (questions #53: the dictionary says
|
|
699
|
+
// `{provider}:{roomId}`, the example has none) - never cut to its tail.
|
|
700
|
+
unifiedRoomId: line.roomRef,
|
|
701
|
+
providerCode: group,
|
|
702
|
+
guestName: g0.name,
|
|
703
|
+
guestPhone: phone,
|
|
704
|
+
...(g0.email ? { guestEmail: g0.email } : {}),
|
|
705
|
+
checkIn: stay.checkIn,
|
|
706
|
+
checkOut: stay.checkOut,
|
|
707
|
+
roomCount: rooms,
|
|
708
|
+
adults: Math.max(1, stay.guests),
|
|
709
|
+
// ⚠️ ALWAYS FALSE (总线程 11-10, rule 3): never the backend's automatic agreement.
|
|
710
|
+
termsAccepted: false,
|
|
711
|
+
expectedChargeUsd: usd.minor / 100,
|
|
712
|
+
};
|
|
713
|
+
const out = await ask({
|
|
714
|
+
acct,
|
|
715
|
+
who,
|
|
716
|
+
hotel,
|
|
717
|
+
group,
|
|
718
|
+
roomId: line.roomRef,
|
|
719
|
+
roomName: line.title,
|
|
720
|
+
stay,
|
|
721
|
+
rooms,
|
|
722
|
+
...(line.terms ? { terms: line.terms } : {}),
|
|
723
|
+
guest: g0,
|
|
724
|
+
pairs: { orig, usd },
|
|
725
|
+
body,
|
|
726
|
+
});
|
|
727
|
+
if (out.booked)
|
|
728
|
+
booked.push(out.booked);
|
|
729
|
+
if (out.failed)
|
|
730
|
+
failed.push(out.failed);
|
|
731
|
+
if (out.terms)
|
|
732
|
+
terms.push(out.terms);
|
|
733
|
+
}
|
|
734
|
+
catch (err) {
|
|
735
|
+
const name = deps.groupOf(group).name;
|
|
736
|
+
// Its price could not be read again just now: this stay, not the trip.
|
|
737
|
+
if (err instanceof OtalessBusy)
|
|
738
|
+
failed.push(failedStay(label, `Not sent to ${name}: too many requests just now - ask again in a minute.`, 'limited'));
|
|
739
|
+
else if (err instanceof OtalessError)
|
|
740
|
+
failed.push(failedStay(label, `${name} did not price it again just now, so nothing was booked.`, 'unreachable'));
|
|
741
|
+
// ⚠️ A STAY BOOKED IS NEVER DROPPED FROM THE ANSWER (the seam's rule): a
|
|
742
|
+
// refusal on a later stay - a session or a sign-in over - is said for that
|
|
743
|
+
// stay. With nothing booked yet, the whole ask is refused as it came.
|
|
744
|
+
else if (!booked.length && !terms.length)
|
|
745
|
+
throw err;
|
|
746
|
+
else
|
|
747
|
+
failed.push(failedStay(label, err instanceof Error && 'code' in err
|
|
748
|
+
? err.message
|
|
749
|
+
: `${name} did not take it, so nothing was booked.`));
|
|
750
|
+
}
|
|
751
|
+
finally {
|
|
752
|
+
inFlight.delete(lockKey);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return {
|
|
756
|
+
booked,
|
|
757
|
+
failed,
|
|
758
|
+
...(reused.length && reused.length === booked.length && !failed.length && !terms.length
|
|
759
|
+
? { repeat: true }
|
|
760
|
+
: reused.length
|
|
761
|
+
? { reused }
|
|
762
|
+
: {}),
|
|
763
|
+
...(terms.length ? { terms } : {}),
|
|
764
|
+
};
|
|
765
|
+
};
|
|
766
|
+
// ── terms agreed to (§12.4) ───────────────────────────────────────────────
|
|
767
|
+
/** Terms waiting for this guest - signed in now at their group, as the same owner. */
|
|
768
|
+
const pendingFor = (ref, who) => {
|
|
769
|
+
const p = pending.get(ref);
|
|
770
|
+
if (!p)
|
|
771
|
+
return undefined;
|
|
772
|
+
const acct = accountFor(who, p.group);
|
|
773
|
+
if (!acct || p.owner !== acct.owner)
|
|
774
|
+
return undefined;
|
|
775
|
+
if (now() - p.at > TERMS_MS) {
|
|
776
|
+
pending.delete(ref);
|
|
777
|
+
return undefined;
|
|
778
|
+
}
|
|
779
|
+
return { p, acct };
|
|
780
|
+
};
|
|
781
|
+
const view = (p) => ({
|
|
782
|
+
ref: p.ref,
|
|
783
|
+
group: p.group,
|
|
784
|
+
groupName: p.groupName,
|
|
785
|
+
...(p.groupNames ? { groupNames: p.groupNames } : {}),
|
|
786
|
+
hotelId: p.hotelId,
|
|
787
|
+
hotelName: p.hotelName,
|
|
788
|
+
...(p.hotelNames ? { hotelNames: p.hotelNames } : {}),
|
|
789
|
+
roomName: p.roomName,
|
|
790
|
+
stay: p.stay,
|
|
791
|
+
rooms: p.rooms,
|
|
792
|
+
total: p.total,
|
|
793
|
+
text: p.text,
|
|
794
|
+
until: p.until,
|
|
795
|
+
});
|
|
796
|
+
const acceptTerms = async (ref, who) => {
|
|
797
|
+
const found = pendingFor(ref, who);
|
|
798
|
+
if (!found)
|
|
799
|
+
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.');
|
|
800
|
+
const { p, acct } = found;
|
|
801
|
+
// ⚠️ ONE USE: gone before it is sent, whatever comes back.
|
|
802
|
+
pending.delete(ref);
|
|
803
|
+
counts.termsAgreed += 1;
|
|
804
|
+
const hotel = deps.find(p.hotelId) ??
|
|
805
|
+
{
|
|
806
|
+
id: p.hotelId,
|
|
807
|
+
name: p.hotelName,
|
|
808
|
+
...(p.hotelNames ? { names: { name: p.hotelNames } } : {}),
|
|
809
|
+
};
|
|
810
|
+
const out = await ask({
|
|
811
|
+
acct,
|
|
812
|
+
who,
|
|
813
|
+
hotel,
|
|
814
|
+
group: p.group,
|
|
815
|
+
roomId: p.roomId,
|
|
816
|
+
roomName: p.roomName,
|
|
817
|
+
stay: p.stay,
|
|
818
|
+
rooms: p.rooms,
|
|
819
|
+
...(p.terms ? { terms: p.terms } : {}),
|
|
820
|
+
guest: { name: p.body.guestName, email: p.body.guestEmail ?? '', phone: p.body.guestPhone },
|
|
821
|
+
pairs: p.pairs,
|
|
822
|
+
body: {
|
|
823
|
+
...p.body,
|
|
824
|
+
// ⚠️ STILL FALSE: the agreement goes to the group's own tool, with the
|
|
825
|
+
// token of the terms the guest saw - so terms that changed meanwhile come
|
|
826
|
+
// back to be shown again, never agreed to unseen (questions #52).
|
|
827
|
+
termsAccepted: false,
|
|
828
|
+
extraParams: { terms_token: p.tokenOfTerms, terms_accepted: true },
|
|
829
|
+
},
|
|
830
|
+
});
|
|
831
|
+
return {
|
|
832
|
+
booked: out.booked ? [out.booked] : [],
|
|
833
|
+
failed: out.failed ? [out.failed] : [],
|
|
834
|
+
...(out.terms ? { terms: [out.terms] } : {}),
|
|
835
|
+
};
|
|
836
|
+
};
|
|
837
|
+
// ── the bookings, refreshed ───────────────────────────────────────────────
|
|
838
|
+
const statusOfRow = (s) => {
|
|
839
|
+
const v = String(s ?? '').toUpperCase();
|
|
840
|
+
if (v === 'PAID')
|
|
841
|
+
return { status: 'confirmed', paid: true };
|
|
842
|
+
if (v === 'CONFIRMED')
|
|
843
|
+
return { status: 'confirmed' };
|
|
844
|
+
if (v === 'CANCELLED' || v === 'CANCELED')
|
|
845
|
+
return { status: 'cancelled' };
|
|
846
|
+
if (v === 'REFUNDED')
|
|
847
|
+
return { status: 'cancelled', refunded: true };
|
|
848
|
+
if (v === 'FAILED')
|
|
849
|
+
return { status: 'failed' };
|
|
850
|
+
return {};
|
|
851
|
+
};
|
|
852
|
+
/** One order's payment, by 15 - at most every `STATUS_EVERY_MS`. */
|
|
853
|
+
const lookAtPayment = async (acct, who, r) => {
|
|
854
|
+
if (r.status !== 'awaiting-payment' || r.id.startsWith('pending:'))
|
|
855
|
+
return;
|
|
856
|
+
const last = checkedAt.get(r.id) ?? 0;
|
|
857
|
+
if (now() - last < STATUS_EVERY_MS)
|
|
858
|
+
return;
|
|
859
|
+
checkedAt.set(r.id, now());
|
|
860
|
+
try {
|
|
861
|
+
const s = await withSession(acct, who, (cred) => client.paymentStatus({ unifiedOrderId: r.id, providerCode: r.group }, cred, deps.callerOf(who)));
|
|
862
|
+
const paid = s?.paid === true || String(s?.status ?? '').toUpperCase() === 'PAID';
|
|
863
|
+
const amount = moneyOf(s?.amount, s?.currency);
|
|
864
|
+
if (paid &&
|
|
865
|
+
amount &&
|
|
866
|
+
!(same(amount, r.charged) || same(amount, r.quoted) || same(amount, r.quotedUsd))) {
|
|
867
|
+
log(`[otaless] NEEDS A PERSON: ${forTheLog(r.id)} at ${r.group} paid ${amount.currency} ${amount.minor}, not what was asked - status left as it was`);
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (paid) {
|
|
871
|
+
r.paid = true;
|
|
872
|
+
r.status = 'confirmed';
|
|
873
|
+
payLinks.delete(r.id);
|
|
874
|
+
put(r);
|
|
875
|
+
}
|
|
876
|
+
else if (r.payBy && now() > Date.parse(r.payBy) && s?.pollAgain !== true) {
|
|
877
|
+
r.status = 'expired';
|
|
878
|
+
payLinks.delete(r.id);
|
|
879
|
+
put(r);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
catch (err) {
|
|
883
|
+
if (err instanceof Error && 'code' in err)
|
|
884
|
+
return; // our own refusal: the list still answers
|
|
885
|
+
log(`[otaless] payment status of an order at ${r.group} not read: ${err instanceof Error ? err.name : 'error'}`);
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
/** The group's order list (12): statuses, a lost payment link, and an order 13 did not answer for. */
|
|
889
|
+
const lookAtOrders = async (acct, who, group, mine) => {
|
|
890
|
+
let rows;
|
|
891
|
+
try {
|
|
892
|
+
rows = await withSession(acct, who, (cred) => client.orders({ providerCode: group }, cred, deps.callerOf(who)));
|
|
893
|
+
}
|
|
894
|
+
catch {
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
const known = new Set(orders.keys());
|
|
898
|
+
for (const row of rows) {
|
|
899
|
+
const id = text(row.unifiedOrderId);
|
|
900
|
+
if (!id)
|
|
901
|
+
continue;
|
|
902
|
+
const r = orders.get(id);
|
|
903
|
+
if (r && r.owner === acct.owner) {
|
|
904
|
+
const s = statusOfRow(row.status);
|
|
905
|
+
// ⚠️ AN UNPAID ORDER STAYS WAITING ("CONFIRMED" is not paid, questions
|
|
906
|
+
// #53): only PAID, a cancellation or a failure moves it.
|
|
907
|
+
if (s.status &&
|
|
908
|
+
r.status !== 'cancelled' &&
|
|
909
|
+
!(r.status === 'awaiting-payment' && s.status === 'confirmed' && !s.paid))
|
|
910
|
+
r.status = s.status;
|
|
911
|
+
if (s.paid)
|
|
912
|
+
r.paid = true;
|
|
913
|
+
if (s.refunded)
|
|
914
|
+
r.refund = {
|
|
915
|
+
status: 'refunded',
|
|
916
|
+
...(r.refund?.amount ? { amount: r.refund.amount } : {}),
|
|
917
|
+
};
|
|
918
|
+
if (r.status === 'awaiting-payment' && !payLinks.has(r.id)) {
|
|
919
|
+
const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
|
|
920
|
+
if (ok)
|
|
921
|
+
payLinks.set(r.id, ok.url);
|
|
922
|
+
}
|
|
923
|
+
put(r);
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
if (known.has(id))
|
|
927
|
+
continue;
|
|
928
|
+
// An order 13 did not answer for: the one unclaimed row of the same group and nights.
|
|
929
|
+
const dates = String(row.dates ?? '');
|
|
930
|
+
const waiting = mine.filter((o) => o.status === 'unconfirmed' &&
|
|
931
|
+
o.id.startsWith('pending:') &&
|
|
932
|
+
o.group === group &&
|
|
933
|
+
dates.includes(o.stay.checkIn) &&
|
|
934
|
+
dates.includes(o.stay.checkOut));
|
|
935
|
+
if (waiting.length !== 1)
|
|
936
|
+
continue;
|
|
937
|
+
const o = waiting[0];
|
|
938
|
+
if (!o)
|
|
939
|
+
continue;
|
|
940
|
+
const charged = moneyOf(row.totalAmount, row.currency);
|
|
941
|
+
orders.delete(o.id);
|
|
942
|
+
o.id = id;
|
|
943
|
+
o.code = text(row.originalOrderId) ?? '';
|
|
944
|
+
if (charged)
|
|
945
|
+
o.charged = charged;
|
|
946
|
+
const s = statusOfRow(row.status);
|
|
947
|
+
if (!charged || !(same(charged, o.quoted) || same(charged, o.quotedUsd))) {
|
|
948
|
+
// Found, at another amount: kept unconfirmed for a person - never handed on.
|
|
949
|
+
log(`[otaless] NEEDS A PERSON: an order 13 did not answer for was found at ${group} at another amount`);
|
|
950
|
+
}
|
|
951
|
+
else if (s.status) {
|
|
952
|
+
o.status =
|
|
953
|
+
s.status === 'confirmed' && !s.paid && text(row.checkoutUrl ?? undefined)
|
|
954
|
+
? 'awaiting-payment'
|
|
955
|
+
: s.status;
|
|
956
|
+
if (s.paid)
|
|
957
|
+
o.paid = true;
|
|
958
|
+
const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
|
|
959
|
+
if (ok && o.status === 'awaiting-payment') {
|
|
960
|
+
o.payHost = ok.host;
|
|
961
|
+
payLinks.set(id, ok.url);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
else if (text(row.checkoutUrl ?? undefined)) {
|
|
965
|
+
const ok = payPageOf(text(row.checkoutUrl ?? undefined), deps.checkoutHosts);
|
|
966
|
+
if (ok) {
|
|
967
|
+
o.status = 'awaiting-payment';
|
|
968
|
+
o.payHost = ok.host;
|
|
969
|
+
payLinks.set(id, ok.url);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
known.add(id);
|
|
973
|
+
put(o);
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
/** The guest's orders brought up to date, each by their sign-in at its group (`signed`). */
|
|
977
|
+
const refresh = async (who, mine, signed) => {
|
|
978
|
+
const newest = [...mine].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
979
|
+
const groups = new Set(newest
|
|
980
|
+
.filter((r) => r.status === 'unconfirmed' || (r.status === 'awaiting-payment' && !payLinks.has(r.id)))
|
|
981
|
+
.map((r) => r.group));
|
|
982
|
+
for (const g of groups) {
|
|
983
|
+
const acct = signed.get(g);
|
|
984
|
+
if (acct)
|
|
985
|
+
await lookAtOrders(acct, who, g, mine.filter((r) => r.group === g));
|
|
986
|
+
}
|
|
987
|
+
for (const r of newest
|
|
988
|
+
.filter((o) => o.status === 'awaiting-payment')
|
|
989
|
+
.slice(0, CHECKED_PER_LOOK)) {
|
|
990
|
+
const acct = signed.get(r.group);
|
|
991
|
+
if (acct)
|
|
992
|
+
await lookAtPayment(acct, who, r);
|
|
993
|
+
}
|
|
994
|
+
};
|
|
995
|
+
const listBookings = async (who, limit) => {
|
|
996
|
+
// ⚠️ BY THE GUEST'S SIGN-IN AT EACH ORDER'S GROUP: an order at a group they
|
|
997
|
+
// are not signed in to now is not listed (robin 11-10: one sign-in per group).
|
|
998
|
+
const signed = new Map();
|
|
999
|
+
for (const g of new Set([...orders.values()].map((o) => o.group))) {
|
|
1000
|
+
const acct = accountFor(who, g);
|
|
1001
|
+
if (acct)
|
|
1002
|
+
signed.set(g, acct);
|
|
1003
|
+
}
|
|
1004
|
+
// Let go at once, and gone: not the guest's. One that could not be undone stays listed.
|
|
1005
|
+
const mine = [...orders.values()].filter((o) => signed.get(o.group)?.owner === o.owner &&
|
|
1006
|
+
(!o.released || (o.releaseFailed && o.status === 'confirmed')));
|
|
1007
|
+
await refresh(who, mine, signed);
|
|
1008
|
+
const list = mine
|
|
1009
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
1010
|
+
.slice(0, Math.max(1, Math.min(limit ?? 20, 50)))
|
|
1011
|
+
.map(toBooking);
|
|
1012
|
+
return list;
|
|
1013
|
+
};
|
|
1014
|
+
const findBooking = async (ref, who) => {
|
|
1015
|
+
const own = ownOrder(ref, who);
|
|
1016
|
+
if (!own)
|
|
1017
|
+
return null;
|
|
1018
|
+
const { r, acct } = own;
|
|
1019
|
+
await refresh(who, [r], new Map([[r.group, acct]]));
|
|
1020
|
+
return toBooking(r);
|
|
1021
|
+
};
|
|
1022
|
+
// ── cancelling (§12.1; 总线程 11-10 rule 5) ────────────────────────────────
|
|
1023
|
+
const previewCancellation = async (ref, who) => {
|
|
1024
|
+
const own = ownOrder(ref, who);
|
|
1025
|
+
if (!own)
|
|
1026
|
+
return null;
|
|
1027
|
+
const { r, acct } = own;
|
|
1028
|
+
await refresh(who, [r], new Map([[r.group, acct]]));
|
|
1029
|
+
const amount = r.charged ?? r.quoted;
|
|
1030
|
+
const base = { bookingId: r.id, supplier: r.group, confirmationCode: r.code || r.id };
|
|
1031
|
+
const g = deps.groupOf(r.group).name;
|
|
1032
|
+
if (r.status === 'cancelled' || r.status === 'expired' || r.status === 'failed')
|
|
1033
|
+
return {
|
|
1034
|
+
...base,
|
|
1035
|
+
fee: money(0, amount.currency),
|
|
1036
|
+
refund: money(0, amount.currency),
|
|
1037
|
+
rule: 'It is no longer active.',
|
|
1038
|
+
cancellable: false,
|
|
1039
|
+
reason: 'not-active',
|
|
1040
|
+
};
|
|
1041
|
+
if (r.status === 'unconfirmed')
|
|
1042
|
+
return {
|
|
1043
|
+
...base,
|
|
1044
|
+
fee: money(0, amount.currency),
|
|
1045
|
+
refund: money(0, amount.currency),
|
|
1046
|
+
rule: `${g} has not said yet whether it took this booking.`,
|
|
1047
|
+
cancellable: false,
|
|
1048
|
+
reason: 'unconfirmed',
|
|
1049
|
+
};
|
|
1050
|
+
if (r.status === 'awaiting-payment' && !r.paid)
|
|
1051
|
+
return {
|
|
1052
|
+
...base,
|
|
1053
|
+
fee: money(0, amount.currency),
|
|
1054
|
+
refund: money(0, amount.currency),
|
|
1055
|
+
rule: 'Not paid yet: cancelling closes its payment page, and nothing was charged.',
|
|
1056
|
+
cancellable: true,
|
|
1057
|
+
reason: 'unpaid',
|
|
1058
|
+
};
|
|
1059
|
+
// ⚠️ THE GROUP'S OWN TERMS, AS THEY CAME; ONLY WITHOUT THEM THE CAP
|
|
1060
|
+
// (总线程 11-10). There is no dry run: what is kept is the group's to say
|
|
1061
|
+
// when it cancels - the fee here is the most it could be.
|
|
1062
|
+
return {
|
|
1063
|
+
...base,
|
|
1064
|
+
fee: amount,
|
|
1065
|
+
refund: money(0, amount.currency),
|
|
1066
|
+
rule: r.terms ??
|
|
1067
|
+
`${g} sent no cancellation terms for this booking: cancelling may cost up to the whole amount - ${g} says what it keeps when it cancels.`,
|
|
1068
|
+
cancellable: true,
|
|
1069
|
+
feeIsCap: true,
|
|
1070
|
+
...(r.terms ? { feeUnknown: true } : {}),
|
|
1071
|
+
};
|
|
1072
|
+
};
|
|
1073
|
+
const cleanReason = (s) => {
|
|
1074
|
+
const t = forTheLog(s ?? '').slice(0, REASON_MAX);
|
|
1075
|
+
return t ? t : undefined;
|
|
1076
|
+
};
|
|
1077
|
+
const cancelBooking = async (ref, who, reason) => {
|
|
1078
|
+
// ⚠️ OURS, THIS GUEST'S, OR NOTHING IS SENT (总线程 11-10, rule 6).
|
|
1079
|
+
const own = ownOrder(ref, who);
|
|
1080
|
+
if (!own)
|
|
1081
|
+
return null;
|
|
1082
|
+
const { r, acct } = own;
|
|
1083
|
+
if (r.status === 'cancelled' || r.status === 'expired' || r.status === 'failed')
|
|
1084
|
+
return toBooking(r);
|
|
1085
|
+
const g = deps.groupOf(r.group).name;
|
|
1086
|
+
if (r.status === 'unconfirmed')
|
|
1087
|
+
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.`);
|
|
1088
|
+
const unpaid = r.status === 'awaiting-payment' && !r.paid;
|
|
1089
|
+
const why = cleanReason(reason);
|
|
1090
|
+
const out = await withSession(acct, who, (cred) => unpaid
|
|
1091
|
+
? client.cancelCheckout({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who))
|
|
1092
|
+
: client.cancelBooking({ unifiedOrderId: r.id, providerCode: r.group, ...(why ? { reason: why } : {}) }, cred, deps.callerOf(who)));
|
|
1093
|
+
const s = String(out?.status ?? '').toUpperCase();
|
|
1094
|
+
if (out?.success === false || (s && !/CANCEL|CLOSED|SUCCESS/.test(s)))
|
|
1095
|
+
throw refusal('not-cancelled', `${g} did not cancel it - it stands as it was.`);
|
|
1096
|
+
r.status = 'cancelled';
|
|
1097
|
+
r.cancelledAt = iso();
|
|
1098
|
+
payLinks.delete(r.id);
|
|
1099
|
+
const back = moneyOf(out?.refundAmount, out?.refundCurrency);
|
|
1100
|
+
if (!unpaid && r.paid)
|
|
1101
|
+
r.refund = { status: 'requested', ...(back ? { amount: back } : {}) };
|
|
1102
|
+
put(r);
|
|
1103
|
+
return toBooking(r);
|
|
1104
|
+
};
|
|
1105
|
+
// ── refund, add-ons (9.1, 10, 11) ─────────────────────────────────────────
|
|
1106
|
+
const refund = async (ref, who, reason) => {
|
|
1107
|
+
const own = ownOrder(ref, who);
|
|
1108
|
+
if (!own)
|
|
1109
|
+
return null;
|
|
1110
|
+
const { r, acct } = own;
|
|
1111
|
+
if (r.refund)
|
|
1112
|
+
return toBooking(r);
|
|
1113
|
+
const g = deps.groupOf(r.group).name;
|
|
1114
|
+
if (!r.paid)
|
|
1115
|
+
throw refusal('not-paid', 'Nothing was paid for this booking, so there is nothing to refund.');
|
|
1116
|
+
const why = cleanReason(reason);
|
|
1117
|
+
// ⚠️ ALL OF IT, NEVER A PART (`amountUsd` is never sent), and no
|
|
1118
|
+
// `sessionToken` (questions #53): the backend takes the guest from the sign-in.
|
|
1119
|
+
const out = await withSession(acct, who, (cred) => client.refund({
|
|
1120
|
+
unifiedOrderId: r.id,
|
|
1121
|
+
...(r.code ? { booking: r.code } : {}),
|
|
1122
|
+
providerCode: r.group,
|
|
1123
|
+
...(why ? { reason: why } : {}),
|
|
1124
|
+
}, cred, deps.callerOf(who)));
|
|
1125
|
+
if (out?.success === false)
|
|
1126
|
+
throw refusal('not-refunded', `${g} did not take the refund request.`);
|
|
1127
|
+
const back = moneyOf(out?.refundAmount, out?.refundCurrency);
|
|
1128
|
+
r.refund = {
|
|
1129
|
+
status: String(out?.status ?? '').toUpperCase() === 'REFUNDED' ? 'refunded' : 'requested',
|
|
1130
|
+
...(back ? { amount: back } : {}),
|
|
1131
|
+
};
|
|
1132
|
+
put(r);
|
|
1133
|
+
return toBooking(r);
|
|
1134
|
+
};
|
|
1135
|
+
const KINDS = { transfer: 'transfer', dining: 'dining' };
|
|
1136
|
+
const PER = {
|
|
1137
|
+
per_trip: 'stay',
|
|
1138
|
+
per_stay: 'stay',
|
|
1139
|
+
per_guest: 'person',
|
|
1140
|
+
per_night: 'night',
|
|
1141
|
+
per_guest_per_day: 'person-night',
|
|
1142
|
+
};
|
|
1143
|
+
const addons = async (ref, who) => {
|
|
1144
|
+
const own = ownOrder(ref, who);
|
|
1145
|
+
if (!own?.r.code)
|
|
1146
|
+
return null;
|
|
1147
|
+
const { r, acct } = own;
|
|
1148
|
+
const list = await withSession(acct, who, (cred) => client.addons({ confirmationCode: r.code, providerCode: r.group }, cred, deps.callerOf(who)));
|
|
1149
|
+
const out = [];
|
|
1150
|
+
for (const a of list) {
|
|
1151
|
+
const id = text(a.catalogId);
|
|
1152
|
+
const name = text(a.name);
|
|
1153
|
+
const price = moneyOf(a.price, a.currency);
|
|
1154
|
+
if (!id || !name || !price || a.booked === true)
|
|
1155
|
+
continue;
|
|
1156
|
+
out.push({
|
|
1157
|
+
id,
|
|
1158
|
+
hotelId: r.hotelId,
|
|
1159
|
+
name,
|
|
1160
|
+
kind: KINDS[String(a.category)] ?? 'experience',
|
|
1161
|
+
description: text(a.description) ?? '',
|
|
1162
|
+
price,
|
|
1163
|
+
per: PER[String(a.unit)] ?? 'stay',
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
listedAddons.set(r.id, { ids: new Set(out.map((e) => e.id)), at: now() });
|
|
1167
|
+
return out;
|
|
1168
|
+
};
|
|
1169
|
+
const bookAddon = async (ref, extraId, details, who) => {
|
|
1170
|
+
const own = ownOrder(ref, who);
|
|
1171
|
+
if (!own?.r.code)
|
|
1172
|
+
return null;
|
|
1173
|
+
const { r, acct } = own;
|
|
1174
|
+
const listed = listedAddons.get(r.id);
|
|
1175
|
+
// Only one the group listed for this booking, a moment ago - never an id from elsewhere.
|
|
1176
|
+
if (!listed || now() - listed.at > TERMS_MS || !listed.ids.has(extraId))
|
|
1177
|
+
throw refusal('unknown-addon', 'That add-on was not among the ones listed for this booking just now - list them again.');
|
|
1178
|
+
if (details.flightNo && !/^[A-Z0-9]{2,8}$/i.test(details.flightNo))
|
|
1179
|
+
throw refusal('addon', 'A flight number is two to eight letters and digits.');
|
|
1180
|
+
if (details.pickupTime && !/^([01]\d|2[0-3]):[0-5]\d$/.test(details.pickupTime))
|
|
1181
|
+
throw refusal('addon', 'A pick-up time is HH:MM.');
|
|
1182
|
+
if (details.date && !/^\d{4}-\d{2}-\d{2}$/.test(details.date))
|
|
1183
|
+
throw refusal('addon', 'A date is YYYY-MM-DD.');
|
|
1184
|
+
const quantity = details.quantity === undefined ? undefined : Math.floor(details.quantity);
|
|
1185
|
+
if (quantity !== undefined && !(quantity >= 1 && quantity <= 20))
|
|
1186
|
+
throw refusal('addon', 'Between 1 and 20 of it.');
|
|
1187
|
+
const out = await withSession(acct, who, (cred) => client.bookAddon({
|
|
1188
|
+
confirmationCode: r.code,
|
|
1189
|
+
catalogId: extraId,
|
|
1190
|
+
providerCode: r.group,
|
|
1191
|
+
...(details.direction ? { direction: details.direction } : {}),
|
|
1192
|
+
...(details.flightNo ? { flightNo: details.flightNo.toUpperCase() } : {}),
|
|
1193
|
+
...(details.pickupTime ? { pickupTime: details.pickupTime } : {}),
|
|
1194
|
+
...(details.date ? { date: details.date } : {}),
|
|
1195
|
+
...(quantity !== undefined ? { quantity } : {}),
|
|
1196
|
+
}, cred, deps.callerOf(who)));
|
|
1197
|
+
if (out?.success === false || !text(out?.addonCode))
|
|
1198
|
+
throw refusal('addon', `${deps.groupOf(r.group).name} did not add it.`);
|
|
1199
|
+
const total = moneyOf(out?.totalAmount, out?.currency);
|
|
1200
|
+
return {
|
|
1201
|
+
code: text(out?.addonCode) ?? '',
|
|
1202
|
+
status: text(out?.status) ?? '',
|
|
1203
|
+
...(total ? { total } : {}),
|
|
1204
|
+
};
|
|
1205
|
+
};
|
|
1206
|
+
const api = {
|
|
1207
|
+
pendingTerms: (ref, who) => {
|
|
1208
|
+
const found = pendingFor(ref, who);
|
|
1209
|
+
return found ? view(found.p) : undefined;
|
|
1210
|
+
},
|
|
1211
|
+
acceptTerms,
|
|
1212
|
+
refund,
|
|
1213
|
+
addons,
|
|
1214
|
+
bookAddon,
|
|
1215
|
+
health: () => ({
|
|
1216
|
+
ordersKept: orders.size,
|
|
1217
|
+
ordersAwaitingPayment: [...orders.values()].filter((o) => o.status === 'awaiting-payment')
|
|
1218
|
+
.length,
|
|
1219
|
+
ordersUnconfirmed: [...orders.values()].filter((o) => o.status === 'unconfirmed').length,
|
|
1220
|
+
groupSessions: sessions.size,
|
|
1221
|
+
termsWaiting: pending.size,
|
|
1222
|
+
...counts,
|
|
1223
|
+
}),
|
|
1224
|
+
};
|
|
1225
|
+
return { requestBooking, listBookings, findBooking, previewCancellation, cancelBooking, api };
|
|
1226
|
+
};
|
|
1227
|
+
//# sourceMappingURL=booking.js.map
|