@composable-os/client 0.1.0-beta.10 → 0.1.0-beta.13

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.
@@ -0,0 +1,845 @@
1
+ import { packHooks } from "./hooks.js";
2
+ /**
3
+ * What can need a customer's attention (`me.attention`, ADR 0711): a fixed vocabulary in core.
4
+ * A newer host may answer a kind this entry does not know yet; it is shown by its record's title.
5
+ */
6
+ export const ATTENTION_KINDS = [
7
+ "agree",
8
+ "card_failing",
9
+ "confirm_payment",
10
+ "balance_due",
11
+ "finish_paying",
12
+ "pass_expiring",
13
+ "pass_used_up",
14
+ "trial_ending",
15
+ "form_to_fill",
16
+ ];
17
+ /** A channel's name, as a person reads it. */
18
+ export const CONTACT_CHANNEL_WORDS = {
19
+ email: "Email",
20
+ text: "Text message",
21
+ push: "App notification",
22
+ };
23
+ /** Whether a channel's value lets messages go. */
24
+ export function contactAllows(value) {
25
+ return value === "on" || value === "yes";
26
+ }
27
+ /** The words a person is shown when they say yes to news and offers on a channel (kept by the host). */
28
+ export function newsAndOffersWords(channel) {
29
+ return `Yes, send me news and offers by ${CONTACT_CHANNEL_WORDS[channel].toLowerCase()}. I can stop at any time.`;
30
+ }
31
+ /**
32
+ * The change that turns one channel of a line the other way: on and off, or for news and offers
33
+ * yes and no (with the words shown). Null for a channel that cannot change (an essential email).
34
+ */
35
+ export function contactToggle(personId, line, channel) {
36
+ if (channel.fixed)
37
+ return null;
38
+ const yesNo = line.scope === "news_and_offers";
39
+ const on = contactAllows(channel.value);
40
+ const value = yesNo ? (on ? "no" : "yes") : on ? "off" : "on";
41
+ return {
42
+ personId,
43
+ choices: [{ scope: line.scope, channel: channel.channel, value }],
44
+ ...(value === "yes" ? { wording: newsAndOffersWords(channel.channel) } : {}),
45
+ };
46
+ }
47
+ /** A line's channel in words: "Email: on", "Email: always (about something you booked)". */
48
+ export function contactChannelWords(channel) {
49
+ const name = CONTACT_CHANNEL_WORDS[channel.channel];
50
+ if (channel.fixed)
51
+ return `${name}: always`;
52
+ if (channel.stopped)
53
+ return `${name}: stopped`;
54
+ return `${name}: ${contactAllows(channel.value) ? "on" : "off"}`;
55
+ }
56
+ /**
57
+ * The base sections, in the order they show after the packs' (a pack declares 10 to 50): what is
58
+ * the customer's to see and do, then their details and where they are signed in. Deleting the
59
+ * account joins them in a later step.
60
+ */
61
+ export const BASE_SECTIONS = [
62
+ { key: "orders", label: "Orders", order: 60 },
63
+ { key: "agreements", label: "Agreements", order: 70 },
64
+ { key: "family", label: "Family", order: 80 },
65
+ { key: "payment", label: "Payment method", order: 85 },
66
+ { key: "details", label: "Your details", order: 90 },
67
+ { key: "contact", label: "Contact preferences", order: 92 },
68
+ { key: "devices", label: "Sign-in and devices", order: 95 },
69
+ { key: "delete", label: "Delete my account", order: 99 },
70
+ ];
71
+ /**
72
+ * The sections to show, in order: the base ones and the packs' given, less those `hide` names
73
+ * (`payment` for a customer who pays no subscription: `showsPayment`). A pack section whose key
74
+ * is a base one's is left out: the base section is the one the host's reads stand behind.
75
+ */
76
+ export function accountSections(packs = [], hide = []) {
77
+ const base = new Set(BASE_SECTIONS.map((s) => s.key));
78
+ return [...BASE_SECTIONS, ...packs.filter((s) => !base.has(s.key))]
79
+ .filter((s) => !hide.includes(s.key))
80
+ .sort((a, b) => a.order - b.order || a.key.localeCompare(b.key));
81
+ }
82
+ /**
83
+ * The sections to show, as the host listed them (`me.portal`): every base section it lists, and a
84
+ * pack's only when the app has its block (`packs`, from `account-sections.gen.ts`), so a pack
85
+ * installed at the host before the app copied its block shows nothing rather than an empty
86
+ * section. Until the host answers, the base sections without Payment method.
87
+ *
88
+ * A shell passes `base`, the base sections it draws: a base section a newer host lists that the
89
+ * shell has no part for (one added to the platform after the shell was copied, as Contact
90
+ * preferences and Delete my account were) is left out too, rather than shown as a heading with
91
+ * nothing under it. Without `base`, every base section the host lists is kept.
92
+ */
93
+ export function portalSections(portal, packs = [], base) {
94
+ const drawn = (key) => !base || base.includes(key);
95
+ if (!portal)
96
+ return accountSections([], ["payment"]).filter((s) => drawn(s.key));
97
+ const copied = new Set(packs.map((s) => s.key));
98
+ return portal.sections
99
+ .filter((s) => (s.pack === null ? drawn(s.key) : copied.has(s.key)))
100
+ .map((s) => ({ key: s.key, label: s.label, order: s.order }));
101
+ }
102
+ /** The base sections a shell hides for this customer, from what the host answered. */
103
+ export function hiddenSections(subscriptions) {
104
+ return showsPayment(subscriptions) ? [] : ["payment"];
105
+ }
106
+ // --- Words (display only) ----------------------------------------------------------------------------
107
+ /**
108
+ * An amount the host gave in the currency's minor unit, in that currency: `$29.00`. Display only:
109
+ * the minor unit's digits are the currency's own.
110
+ */
111
+ export function formatMinor(minor, currency, locale) {
112
+ try {
113
+ const format = new Intl.NumberFormat(locale, { style: "currency", currency });
114
+ const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
115
+ return format.format(minor / 10 ** digits);
116
+ }
117
+ catch {
118
+ return `${minor} ${currency}`;
119
+ }
120
+ }
121
+ /** The host's ISO timestamp as a reader sees it, or "" for none or one that does not parse. */
122
+ function localWhen(iso, locale, format) {
123
+ if (!iso)
124
+ return "";
125
+ const at = new Date(iso);
126
+ return Number.isNaN(at.getTime()) ? "" : at.toLocaleString(locale, format);
127
+ }
128
+ /** A date as a reader sees it (`3 Dec 2026`), from the host's ISO timestamp. Display only. */
129
+ export function accountDay(iso, locale) {
130
+ return localWhen(iso, locale, { day: "numeric", month: "short", year: "numeric" });
131
+ }
132
+ /** A moment as a reader sees it (`3 Dec 2026, 09:30`). Display only. */
133
+ export function accountTime(iso, locale) {
134
+ return localWhen(iso, locale, {
135
+ day: "numeric",
136
+ month: "short",
137
+ year: "numeric",
138
+ hour: "2-digit",
139
+ minute: "2-digit",
140
+ });
141
+ }
142
+ /** A session in words: what it is, and when it began and was last used. */
143
+ export function sessionWords(session) {
144
+ const what = session.kind === "device" ? (session.deviceName ?? "The app on a device") : "A web browser";
145
+ const title = session.current
146
+ ? `${session.kind === "device" ? "This device" : "This browser"} (${what})`
147
+ : what;
148
+ return {
149
+ title,
150
+ detail: `Signed in ${accountTime(session.createdAt)} · last used ${accountTime(session.lastActiveAt)}`,
151
+ };
152
+ }
153
+ /** The customer's sessions, this one first, then the most recently used. */
154
+ export function orderedSessions(items) {
155
+ return [...items].sort((a, b) => Number(b.current) - Number(a.current) || b.lastActiveAt.localeCompare(a.lastActiveAt));
156
+ }
157
+ /** An order's state in words, from what the host reports. */
158
+ export function orderStateWords(order) {
159
+ switch (order.state) {
160
+ case "pending":
161
+ return order.expiresAt
162
+ ? `Waiting for payment until ${accountTime(order.expiresAt)}`
163
+ : "Waiting for payment";
164
+ case "part_paid":
165
+ return order.balanceDueAt
166
+ ? `Deposit paid: the rest is due by ${accountDay(order.balanceDueAt)}`
167
+ : "Deposit paid: the rest is still to pay";
168
+ case "paid":
169
+ return order.refunded > 0 ? "Paid, part refunded" : "Paid";
170
+ case "refunded":
171
+ return "Refunded";
172
+ case "cancelled":
173
+ return "Cancelled";
174
+ case "expired":
175
+ return "Not paid in time: nothing was charged";
176
+ }
177
+ }
178
+ /**
179
+ * The money lines of an order to show, each the host's own figure: the total and its tax, then
180
+ * what was paid, what is still to pay (by when), the deposit and what was refunded. A figure the
181
+ * order does not have (no deposit, nothing refunded) is left out.
182
+ */
183
+ export function orderMoney(order, locale) {
184
+ const money = (minor) => formatMinor(minor, order.currency, locale);
185
+ const out = [{ key: "total", label: "Total", value: money(order.total) }];
186
+ if (order.taxAmount > 0)
187
+ out.push({ key: "tax", label: "Tax included", value: money(order.taxAmount) });
188
+ if (order.pay === "deposit" && order.deposit !== null) {
189
+ out.push({ key: "deposit", label: "Deposit", value: money(order.deposit) });
190
+ }
191
+ if (order.paid > 0)
192
+ out.push({ key: "paid", label: "Paid", value: money(order.paid) });
193
+ if (order.balance > 0 && order.state !== "cancelled" && order.state !== "expired") {
194
+ out.push({
195
+ key: "balance",
196
+ label: order.balanceDueAt ? `To pay by ${accountDay(order.balanceDueAt, locale)}` : "To pay",
197
+ value: money(order.balance),
198
+ });
199
+ }
200
+ if (order.refunded > 0)
201
+ out.push({ key: "refunded", label: "Refunded", value: money(order.refunded) });
202
+ if (order.taxRefunded > 0) {
203
+ out.push({ key: "taxRefunded", label: "Tax refunded", value: money(order.taxRefunded) });
204
+ }
205
+ return out;
206
+ }
207
+ /**
208
+ * Whether an order's row offers to pay: it waits for payment, or has the rest of a deposit still
209
+ * to pay. Display only: what is charged, and whether it may be paid at all, is the host's
210
+ * (`order.checkout` refuses otherwise and says so).
211
+ */
212
+ export function showsPay(order) {
213
+ return order.state === "pending" || (order.state === "part_paid" && order.balance > 0);
214
+ }
215
+ /** What an order's pay button says: the rest of a deposit, or the whole order. */
216
+ export function payWords(order) {
217
+ return order.state === "part_paid" ? "Pay the rest" : "Pay now";
218
+ }
219
+ /** What an order's row in the app says instead: paying is on the website (ADR 0714). */
220
+ export const PAY_ON_WEBSITE_WORDS = "Pay on the website";
221
+ /**
222
+ * Whether an address the host gave (a provider's page to confirm a payment, a checkout) may be
223
+ * followed: an `https:` address, a path on this site, or a loopback `http:` one (a local
224
+ * development host). Anything else (`javascript:`, `data:`, another `http:`, `//elsewhere`) is
225
+ * not followed.
226
+ */
227
+ export function followableUrl(url) {
228
+ if (!url)
229
+ return false;
230
+ if (/\s/.test(url))
231
+ return false;
232
+ // A loopback `http:` address is a local development host's (its fake provider's page).
233
+ const loopback = /^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i;
234
+ return /^\/(?![/\\])/.test(url) || /^https:\/\/[^/\\?#@]/i.test(url) || loopback.test(url);
235
+ }
236
+ /** What a paid order's row says about its receipt until the host has a receipt document. */
237
+ export const RECEIPT_EMAILED_WORDS = "The payment provider emailed you the receipt.";
238
+ /** Whether the order's row says where its receipt is: a paid order, part or whole. */
239
+ export function showsReceiptNote(order) {
240
+ return order.paid > 0 || order.state === "paid" || order.state === "refunded";
241
+ }
242
+ /** Whether a subscription is still the payer's to cancel, resume or pay (not ended). */
243
+ export function isLive(sub) {
244
+ return sub.state !== "ended" && sub.state !== "expired";
245
+ }
246
+ /**
247
+ * Whether the Payment method section shows: the customer pays a subscription that has not ended
248
+ * (`subscription.list` lists a customer only the ones they pay). The shells take the host's own
249
+ * answer (`me.portal`'s `paysSubscription`, `portalSections`); a plain page may use this.
250
+ */
251
+ export function showsPayment(subscriptions) {
252
+ return !!subscriptions?.some(isLive);
253
+ }
254
+ /** Whether the payer may still cancel it (it does not already end), as the host reported it. */
255
+ export function canCancel(sub) {
256
+ return isLive(sub) && !sub.cancelAtPeriodEnd && sub.cancelAt === null;
257
+ }
258
+ /** Whether the payer may keep it going: cancelled at the period's end, which has not come. */
259
+ export function canResume(sub) {
260
+ return isLive(sub) && sub.cancelAtPeriodEnd;
261
+ }
262
+ /**
263
+ * What a subscription's state means to its payer, in words, from what the host reports. Display
264
+ * only: whether it gives access is the host's (the seam), never worked out from this.
265
+ */
266
+ export function subscriptionStatus(sub, locale) {
267
+ const day = (iso) => accountDay(iso, locale);
268
+ const ends = sub.cancelAtPeriodEnd ? sub.currentPeriodEnd : sub.cancelAt;
269
+ switch (sub.state) {
270
+ case "trialing":
271
+ return ends
272
+ ? `Free, ending on ${day(ends)}: nothing will be charged`
273
+ : `Free until ${day(sub.trialEnd ?? sub.currentPeriodEnd)}, then charged each ${sub.interval}`;
274
+ case "active":
275
+ return ends
276
+ ? `Active until ${day(ends)}, then it ends`
277
+ : `Active: next charge on ${day(sub.currentPeriodEnd)}`;
278
+ case "past_due":
279
+ return sub.actionUrl
280
+ ? "A payment needs you to confirm it"
281
+ : "A payment failed: the payment provider will try again";
282
+ case "unpaid":
283
+ return "Unpaid: update your card to keep it going";
284
+ case "paused":
285
+ return "Paused";
286
+ case "incomplete":
287
+ return sub.actionUrl
288
+ ? "Waiting for you to confirm its first payment with your bank"
289
+ : "Waiting for its first payment";
290
+ case "expired":
291
+ return "Never started: its first payment did not go through";
292
+ case "ended":
293
+ return `Ended${sub.endedAt ? ` on ${day(sub.endedAt)}` : ""}`;
294
+ }
295
+ }
296
+ /** One period's price in words (`$29.00 a month`), as the host gave it. */
297
+ export function subscriptionPrice(sub, locale) {
298
+ return `${formatMinor(sub.amount, sub.currency, locale)} a ${sub.interval}`;
299
+ }
300
+ /** What a native shell says where money is managed on the website (ADR 0714). */
301
+ export const MANAGE_ON_WEBSITE_WORDS = "Manage on the website";
302
+ /** What to tell a customer whose account call did not go through, in plain words. */
303
+ export function accountErrorWords(error) {
304
+ const e = error !== null && typeof error === "object" ? error : null;
305
+ if (e?.name === "NetworkError") {
306
+ return "We could not reach the business just now. Check your connection and try again.";
307
+ }
308
+ if (e?.code === "invalid_input" && typeof e.message === "string")
309
+ return e.message;
310
+ if (e?.code === "not_found")
311
+ return "That is no longer there. Refresh and try again.";
312
+ return "That did not go through. Please try again.";
313
+ }
314
+ /** The longest values the host takes (it checks again). */
315
+ export const DETAILS_MAX = { displayName: 200, givenName: 100, familyName: 100, primaryPhone: 50 };
316
+ export function detailsForm(me) {
317
+ return {
318
+ displayName: me.displayName,
319
+ givenName: me.givenName ?? "",
320
+ familyName: me.familyName ?? "",
321
+ primaryPhone: me.primaryPhone ?? "",
322
+ };
323
+ }
324
+ /** What is wrong before saving, field by field (the host checks again). */
325
+ export function detailsProblems(form) {
326
+ const problems = [];
327
+ if (!form.displayName.trim())
328
+ problems.push({ field: "displayName", message: "Enter your name" });
329
+ for (const field of Object.keys(DETAILS_MAX)) {
330
+ if (form[field].trim().length > DETAILS_MAX[field]) {
331
+ problems.push({ field, message: `At most ${DETAILS_MAX[field]} characters` });
332
+ }
333
+ }
334
+ return problems;
335
+ }
336
+ /** The `me.update` input: only what changed, an emptied field as null. Null when nothing did. */
337
+ export function detailsInput(me, form) {
338
+ const input = {};
339
+ const name = form.displayName.trim();
340
+ if (name !== me.displayName)
341
+ input.displayName = name;
342
+ for (const field of ["givenName", "familyName", "primaryPhone"]) {
343
+ const value = form[field].trim() || null;
344
+ if (value !== (me[field] ?? null))
345
+ input[field] = value;
346
+ }
347
+ return Object.keys(input).length ? input : null;
348
+ }
349
+ /** The most days each month has (29 for February). The host checks again. */
350
+ const DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
351
+ /** The days a month can have, for a day picker: 1 to 31 until a month is chosen. */
352
+ export function birthdayDays(month) {
353
+ const most = DAYS_IN_MONTH[Number(month) - 1] ?? 31;
354
+ return Array.from({ length: most }, (_, i) => i + 1);
355
+ }
356
+ /** The twelve months' names in `locale`, January first, with their numbers. */
357
+ export function birthdayMonths(locale) {
358
+ const format = new Intl.DateTimeFormat(locale, { month: "long", timeZone: "UTC" });
359
+ return DAYS_IN_MONTH.map((_, i) => ({
360
+ value: String(i + 1),
361
+ label: format.format(Date.UTC(2000, i, 1)),
362
+ }));
363
+ }
364
+ export function birthdayForm(birthday) {
365
+ return birthday
366
+ ? { day: String(birthday.day), month: String(birthday.month) }
367
+ : { day: "", month: "" };
368
+ }
369
+ /** What is wrong before saving (the host checks again): both or neither, a day the month has. */
370
+ export function birthdayProblem(form) {
371
+ if (!form.day && !form.month)
372
+ return null;
373
+ if (!form.day || !form.month)
374
+ return "Choose a day and a month, or neither";
375
+ if (!birthdayDays(form.month).includes(Number(form.day)))
376
+ return "That month has no such day";
377
+ return null;
378
+ }
379
+ /** The `me.birthday.set` input when the form changed it (none chosen clears it), else null. */
380
+ export function birthdayInput(current, form) {
381
+ const next = form.day && form.month ? { day: Number(form.day), month: Number(form.month) } : null;
382
+ const same = next?.day === current?.day && next?.month === current?.month;
383
+ return same ? null : { birthday: next };
384
+ }
385
+ // --- Orders ------------------------------------------------------------------------------------------
386
+ /**
387
+ * Orders a page holds. The page's lines are read in one `my.list` whose filter names every order
388
+ * of the page, each a bound variable: kept well under D1's 100 per statement.
389
+ */
390
+ export const ORDERS_PAGE = 20;
391
+ /** Lines read per call, and the most calls for one page's lines. */
392
+ const LINES_PAGE = 200;
393
+ const LINES_CALLS = 5;
394
+ const str = (v) => (typeof v === "string" ? v : null);
395
+ const num = (v) => (typeof v === "number" ? v : 0);
396
+ function toLine(record) {
397
+ const v = record.values;
398
+ return {
399
+ id: record.id,
400
+ position: num(v.position),
401
+ title: str(v.title) ?? "",
402
+ quantity: num(v.quantity),
403
+ unitPrice: num(v.unitPrice),
404
+ total: num(v.total),
405
+ taxAmount: num(v.taxAmount),
406
+ };
407
+ }
408
+ function toOrder(record, lines, currency) {
409
+ const v = record.values;
410
+ return {
411
+ id: record.id,
412
+ state: (str(v.state) ?? "pending"),
413
+ currency: str(v.currency) ?? currency,
414
+ total: num(v.total),
415
+ paid: num(v.paid),
416
+ balance: num(v.balance),
417
+ refunded: num(v.refunded),
418
+ pay: v.pay === "deposit" ? "deposit" : "full",
419
+ deposit: typeof v.deposit === "number" ? v.deposit : null,
420
+ balanceDueAt: str(v.balanceDueAt),
421
+ expiresAt: str(v.expiresAt),
422
+ paidAt: str(v.paidAt),
423
+ createdAt: str(v.createdAt) ?? "",
424
+ taxAmount: num(v.taxAmount),
425
+ taxRefunded: num(v.taxRefunded),
426
+ subscriptionId: str(v.subscriptionId),
427
+ lines: lines.sort((a, b) => a.position - b.position),
428
+ receiptUrl: null,
429
+ };
430
+ }
431
+ /** Reads through the client the entry was given: `query(...).queryFn()` is the client's call. */
432
+ function read(api, name, input) {
433
+ return api.query(name, input).queryFn();
434
+ }
435
+ /**
436
+ * The customer's generated client as this entry's own reads take it (`loadOrders`), for code that
437
+ * does not use the hooks: a plain page, a server function. It must hold `my.list`.
438
+ */
439
+ export function accountClient(client) {
440
+ // The generated client's `query` is typed over all its operations; the entry reads only these.
441
+ return client;
442
+ }
443
+ /**
444
+ * One page of the signed-in customer's orders, newest first, each with its lines: their own
445
+ * only (the seam's `my.list` on `order` and `orderLine`; a child's orders are the child's). Two
446
+ * reads for a page, and a few more only for a page of very many lines.
447
+ */
448
+ export async function loadOrders(api, cursor) {
449
+ const page = await read(api, "my.list", {
450
+ object: "order",
451
+ sort: { field: "createdAt", direction: "desc" },
452
+ limit: ORDERS_PAGE,
453
+ ...(cursor ? { cursor } : {}),
454
+ });
455
+ const currency = page.currency ?? "";
456
+ const ids = page.items.map((o) => o.id);
457
+ const lines = new Map(ids.map((id) => [id, []]));
458
+ let next = null;
459
+ for (let calls = 0; ids.length && calls < LINES_CALLS; calls += 1) {
460
+ const found = await read(api, "my.list", {
461
+ object: "orderLine",
462
+ filter: { field: "orderId", op: "in", value: ids },
463
+ limit: LINES_PAGE,
464
+ ...(next ? { cursor: next } : {}),
465
+ });
466
+ for (const record of found.items)
467
+ lines.get(str(record.values.orderId) ?? "")?.push(toLine(record));
468
+ next = found.nextCursor;
469
+ if (!next)
470
+ break;
471
+ }
472
+ return {
473
+ orders: page.items.map((o) => toOrder(o, lines.get(o.id) ?? [], currency)),
474
+ nextCursor: page.nextCursor,
475
+ };
476
+ }
477
+ // --- A recent sign-in (ADR 0712) ---------------------------------------------------------------------
478
+ /** Whether the host refused because the customer must sign in again first (`sign_in_again`). */
479
+ export function isSignInAgain(error) {
480
+ return (error !== null &&
481
+ typeof error === "object" &&
482
+ error.code === "sign_in_again");
483
+ }
484
+ /** What a block says when the host asks for a fresh sign-in before going on. */
485
+ export const SIGN_IN_AGAIN_WORDS = "For your safety, sign in again first: we email a code to the address you sign in with. Then you carry on here.";
486
+ /**
487
+ * Runs an act the host keeps to a recent sign-in (changing the sign-in address, deleting the
488
+ * account). A `sign_in_again` refusal is its own outcome, never a failure and never done: the block
489
+ * shows the sign-in step, keeps what the customer was doing, and runs the act again after it.
490
+ */
491
+ export async function sensitive(act) {
492
+ try {
493
+ return { kind: "done", value: await act() };
494
+ }
495
+ catch (error) {
496
+ return isSignInAgain(error) ? { kind: "sign_in_again" } : { kind: "failed", error };
497
+ }
498
+ }
499
+ /** The host's `details.rule` on a refusal, wherever the client put it. */
500
+ function refusalRule(error) {
501
+ const details = error?.details;
502
+ const rule = details?.rule ?? details?.details?.rule;
503
+ return typeof rule === "string" ? rule : null;
504
+ }
505
+ // --- Changing the sign-in address (ADR 0712) -----------------------------------------------------------
506
+ /** The longest address the host takes (it checks again). */
507
+ export const EMAIL_MAX = 320;
508
+ /**
509
+ * What is wrong with a new sign-in address before asking (the host checks again), or null. Whether
510
+ * the address can be used is never known here: the host says so only once its code is entered.
511
+ */
512
+ export function emailChangeProblem(email, current) {
513
+ const address = email.trim();
514
+ if (!address)
515
+ return "Enter the new address";
516
+ if (address.length > EMAIL_MAX || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(address)) {
517
+ return "Enter an email address, like name@example.com";
518
+ }
519
+ if (address.toLowerCase() === current.trim().toLowerCase()) {
520
+ return "That is the address you sign in with now";
521
+ }
522
+ return null;
523
+ }
524
+ /** A six-digit code, as typed: spaces taken out (the host checks it). */
525
+ export function codeInput(typed) {
526
+ return typed.replace(/\s+/g, "");
527
+ }
528
+ /** What to tell a customer whose address change was refused: the host's own words where it gave some. */
529
+ export function emailChangeErrorWords(error) {
530
+ const e = error !== null && typeof error === "object" ? error : null;
531
+ if (e?.code === "rate_limited") {
532
+ return "Too many requests just now. Wait a few minutes and try again.";
533
+ }
534
+ if ((e?.code === "conflict" || e?.code === "invalid_input") && typeof e.message === "string") {
535
+ return e.message;
536
+ }
537
+ if (e?.code === "config")
538
+ return "Changing your sign-in address is not available just now.";
539
+ return accountErrorWords(error);
540
+ }
541
+ // --- Deleting the account (ADR 0713) -----------------------------------------------------------------
542
+ /** What a customer types to confirm deleting their account. */
543
+ export const DELETE_WORD = "DELETE";
544
+ /** Whether the host answered the preview (nothing deleted yet). */
545
+ export function isDeletePreview(answer) {
546
+ return answer?.deleted === false;
547
+ }
548
+ /**
549
+ * The confirming call's input: only from a preview the host gave (its `expect`), and only once the
550
+ * customer has typed the word. Null otherwise, and the block does not call: nothing is deleted
551
+ * without the customer having been shown, in full, what it will do.
552
+ */
553
+ export function deleteConfirmInput(preview, typed) {
554
+ if (preview?.deleted !== false || !preview.expect)
555
+ return null;
556
+ if (typed.trim().toUpperCase() !== DELETE_WORD)
557
+ return null;
558
+ return { confirm: true, expect: preview.expect };
559
+ }
560
+ /**
561
+ * Confirms the deletion (`act`: the confirming call) as a sensitive act, and once the host has
562
+ * deleted the account runs `forget` before answering: in the app, ending this device's session
563
+ * and forgetting its stored tokens (`session.signOut`), so a relaunch finds no session even if
564
+ * the person never leaves the screen. A `forget` that fails (offline) is not the deletion's
565
+ * failure: the host has already ended every session.
566
+ */
567
+ export async function confirmDelete(act, forget) {
568
+ const outcome = await sensitive(act);
569
+ if (outcome.kind === "done" && outcome.value.deleted && forget) {
570
+ await forget().catch(() => { });
571
+ }
572
+ return outcome;
573
+ }
574
+ /** Whether a confirm was refused because what deleting does changed since the preview. */
575
+ export function isPreviewChanged(error) {
576
+ return (error?.code === "conflict" &&
577
+ refusalRule(error) === "preview_changed");
578
+ }
579
+ /** The preview in words, every part of it, as the host answered it. Display only. */
580
+ export function deletePreviewWords(preview, locale) {
581
+ const money = (minor, currency) => formatMinor(minor, currency, locale);
582
+ const ends = preview.subscriptions.map((sub) => {
583
+ const what = `${sub.title} (${money(sub.amount, sub.currency)} a ${sub.interval})`;
584
+ const when = sub.endsAt ? ` on ${accountDay(sub.endsAt, locale)}` : "";
585
+ switch (sub.ending) {
586
+ case "period_end":
587
+ return `${what} ends${when}, at the end of the period already paid for. Nothing is refunded and nothing more is charged.`;
588
+ case "already":
589
+ return `${what} is already set to end${when}. Nothing is refunded.`;
590
+ default:
591
+ return `${what} ends with the cooling off you asked for, and its refund.`;
592
+ }
593
+ });
594
+ const cancelled = preview.orders.map((order) => `Your unpaid order of ${accountDay(order.createdAt, locale)} (${order.lines.join(", ") || "an order"}, ${money(order.total, order.currency)}) is cancelled. You were not charged for it.`);
595
+ const left = [];
596
+ const staff = preview.leftForStaff;
597
+ for (const record of staff.records)
598
+ left.push(`${record.label}: ${record.count}`);
599
+ if (staff.partPaidOrders) {
600
+ left.push(`${staff.partPaidOrders} part-paid ${staff.partPaidOrders === 1 ? "order" : "orders"}`);
601
+ }
602
+ if (staff.moreUnpaidOrders) {
603
+ left.push(`${staff.moreUnpaidOrders} more unpaid ${staff.moreUnpaidOrders === 1 ? "order" : "orders"}`);
604
+ }
605
+ for (const sub of staff.subscriptions) {
606
+ left.push(sub.why === "end_date_later"
607
+ ? `${sub.title}: it has an end date set later, and may charge until the business ends it`
608
+ : sub.why === "state"
609
+ ? `${sub.title}: it cannot be ended this way now, and may charge until the business ends it`
610
+ : `${sub.title}: the business ends it, and it may charge until then`);
611
+ }
612
+ if (staff.dependantsWithoutGuardian) {
613
+ left.push(`${staff.dependantsWithoutGuardian} ${staff.dependantsWithoutGuardian === 1 ? "child" : "children"} linked to you will have no other parent or guardian on the account`);
614
+ }
615
+ return {
616
+ ends,
617
+ cancelled,
618
+ left,
619
+ erase: `You are signed out everywhere at once and cannot sign in again. The business erases your personal data, or tells you by email why some of it must be kept, by ${accountDay(preview.eraseDueAt, locale)}.`,
620
+ };
621
+ }
622
+ /** What a customer is told once the account is deleted. */
623
+ export function deletedWords(done, locale) {
624
+ return `Your account is deleted and you are signed out. The business erases your data by ${accountDay(done.eraseRequest.dueAt, locale)}.`;
625
+ }
626
+ // --- Needs your attention (ADR 0711) -------------------------------------------------------------------
627
+ /** An attention item in words: what it is, the detail, and what the button says. Display only. */
628
+ export function attentionWords(item, locale) {
629
+ const day = accountDay(item.at, locale);
630
+ const money = item.amount !== null && item.currency ? formatMinor(item.amount, item.currency, locale) : "";
631
+ const left = item.usesLeft === null ? "" : item.usesLeft === 1 ? "1 left" : `${item.usesLeft} left`;
632
+ const title = item.record.title;
633
+ const whose = item.person.self ? null : `For ${item.person.name}`;
634
+ const words = (t, detail, action) => ({
635
+ title: t,
636
+ detail,
637
+ action,
638
+ whose,
639
+ });
640
+ switch (item.kind) {
641
+ case "agree":
642
+ return words(`Agree to ${title}`, "Read it and agree before the next booking.", "Read and agree");
643
+ case "card_failing":
644
+ return words(`A payment for ${title} failed`, "Update your card so it keeps going.", "Update your card");
645
+ case "confirm_payment":
646
+ return words(`Confirm a payment for ${title}`, "Your bank is waiting for you to confirm it.", "Confirm with your bank");
647
+ case "balance_due":
648
+ return words(`The rest to pay for ${title}`, [money, day ? `due by ${day}` : ""].filter(Boolean).join(", "), "Pay the rest");
649
+ case "finish_paying":
650
+ return words(`Finish paying for ${title}`, item.at ? `Held for you until ${accountTime(item.at, locale)}` : "Held for you for now", "Finish paying");
651
+ case "pass_expiring":
652
+ return words(`${title} expires on ${day}`, left ? `${left} on it` : "Use it before then", "See your passes");
653
+ case "pass_used_up":
654
+ return words(`${title} has none left`, day ? `It would have lasted until ${day}` : "Buy another to keep booking", "See your passes");
655
+ case "trial_ending":
656
+ return words(`Your free trial of ${title} ends on ${day}`, money ? `Then it is ${money} each time it renews, unless you cancel` : "Then it renews", "See it");
657
+ case "form_to_fill":
658
+ return words(`Fill in ${title}`, day ? `Open until ${day}` : "The business asked you to fill it in", "Fill it in");
659
+ default:
660
+ return words(title, "", null);
661
+ }
662
+ }
663
+ /** The pack an object belongs to (`memberships.pass` → `memberships`), or null for a core one. */
664
+ const packOf = (object) => object.includes(".") ? (object.split(".")[0] ?? null) : null;
665
+ /**
666
+ * Where to send the customer for an item, among the sections shown (`shown`, the host's sections
667
+ * the app has): agreements for a document, Payment method for a failed card, the order itself in
668
+ * Orders for money owed on it (where the web pays it), the pack's section for its pass or its plan's trial, the provider's page for a payment
669
+ * the bank waits on (from the subscription the host listed), the form by its link. Null where
670
+ * nothing shown deals with it: the item is still listed. A lookup, never a rule.
671
+ */
672
+ export function attentionTarget(item, shown, subscriptions = []) {
673
+ const has = (key) => shown.some((s) => s.key === key);
674
+ const section = (key) => has(key) ? { kind: "section", key } : null;
675
+ const packSection = (pack) => {
676
+ const found = pack ? shown.find((s) => s.key.startsWith(`${pack}.`)) : undefined;
677
+ return found ? { kind: "section", key: found.key } : null;
678
+ };
679
+ const sub = subscriptions.find((s) => s.id === item.record.id);
680
+ switch (item.kind) {
681
+ case "agree":
682
+ return section("agreements");
683
+ case "card_failing":
684
+ return section("payment");
685
+ case "confirm_payment":
686
+ // The provider's page only at an address that may be followed (`followableUrl`).
687
+ return sub?.actionUrl && followableUrl(sub.actionUrl)
688
+ ? { kind: "page", url: sub.actionUrl }
689
+ : section("payment");
690
+ case "balance_due":
691
+ case "finish_paying":
692
+ return has("orders") ? { kind: "section", key: "orders", order: item.record.id } : null;
693
+ case "pass_expiring":
694
+ case "pass_used_up":
695
+ return packSection(packOf(item.record.object));
696
+ case "trial_ending":
697
+ return packSection(sub ? packOf(sub.planObject) : null) ?? section("payment");
698
+ case "form_to_fill":
699
+ return item.link ? { kind: "form", link: item.link } : null;
700
+ default:
701
+ return null;
702
+ }
703
+ }
704
+ /** The operations each hook calls (ADR 0453). */
705
+ export const ACCOUNT_HOOKS_CALL = {
706
+ usePortal: ["me.portal"],
707
+ useAttention: ["me.attention"],
708
+ useChangeEmail: ["me.email.change"],
709
+ useConfirmEmail: ["me.email.confirm"],
710
+ useDeleteAccount: ["me.deleteAccount"],
711
+ useMe: ["me.get"],
712
+ useUpdateMe: ["me.update"],
713
+ useBirthday: ["me.birthday.get"],
714
+ useSetBirthday: ["me.birthday.set"],
715
+ useSessions: ["me.sessions.list"],
716
+ useRevokeSession: ["me.sessions.revoke"],
717
+ useFamily: ["me.family"],
718
+ useOrders: ["my.list"],
719
+ useSubscriptions: ["subscription.list"],
720
+ useCancelSubscription: ["subscription.cancel"],
721
+ useResumeSubscription: ["subscription.resume"],
722
+ useBillingPortal: ["subscription.portal"],
723
+ useCheckoutOrder: ["order.checkout"],
724
+ useContactChoices: ["me.contact.choices"],
725
+ useSetContactChoices: ["me.contact.setChoices"],
726
+ };
727
+ /**
728
+ * Hooks for a React or React Native app:
729
+ * `const account = createAccountHooks({ useQuery, useMutation, useQueryClient }, api)`, with the
730
+ * customer's generated client. The hooks it cannot back are not there.
731
+ */
732
+ export function createAccountHooks(react, client) {
733
+ return packHooks(client, ACCOUNT_HOOKS_CALL, (api) => allAccountHooks(react, api));
734
+ }
735
+ function allAccountHooks(react, api) {
736
+ const { useQuery, useMutation } = react;
737
+ return {
738
+ /** Which sections of My account they have, in order, and whether they pay a subscription. */
739
+ usePortal() {
740
+ return useQuery(api.query("me.portal", {}));
741
+ },
742
+ /** What needs their attention, or a child's they act for, soonest first. */
743
+ useAttention() {
744
+ return useQuery(api.query("me.attention", {}));
745
+ },
746
+ /**
747
+ * Ask for a code at a new sign-in address (after a recent sign-in, else `sign_in_again`). The
748
+ * address is not kept in the app's cache once the call is over.
749
+ */
750
+ useChangeEmail() {
751
+ return useMutation({ ...api.mutation("me.email.change"), gcTime: 0 });
752
+ },
753
+ /** Finish the change with the code from the new address; the code is not kept either. */
754
+ useConfirmEmail() {
755
+ return useMutation({ ...api.mutation("me.email.confirm"), gcTime: 0 });
756
+ },
757
+ /**
758
+ * Delete the account: with `{}` the host says what it will do; with `deleteConfirmInput`
759
+ * (the preview's `expect`) it does that. After a recent sign-in, else `sign_in_again`. Once
760
+ * the host has deleted it, every query the app's cache holds is forgotten at once (with the
761
+ * app's `useQueryClient` given): nothing of the account stays in memory until the app leaves.
762
+ */
763
+ useDeleteAccount() {
764
+ const cache = react.useQueryClient?.();
765
+ const call = api.mutation("me.deleteAccount");
766
+ return useMutation({
767
+ ...call,
768
+ mutationFn: async (input) => {
769
+ const answer = await call.mutationFn(input);
770
+ if (answer.deleted)
771
+ cache?.removeQueries();
772
+ return answer;
773
+ },
774
+ gcTime: 0,
775
+ });
776
+ },
777
+ /** The signed-in customer's own Person and sign-in address. */
778
+ useMe() {
779
+ return useQuery(api.query("me.get", {}));
780
+ },
781
+ /** Change their name or phone: pass only what changed (`detailsInput`). */
782
+ useUpdateMe() {
783
+ return useMutation(api.mutation("me.update"));
784
+ },
785
+ /** Their birthday, day and month, or null (stage 53). */
786
+ useBirthday() {
787
+ return useQuery(api.query("me.birthday.get", {}));
788
+ },
789
+ /** Give, change or remove their birthday (`birthdayInput`). */
790
+ useSetBirthday() {
791
+ return useMutation(api.mutation("me.birthday.set"));
792
+ },
793
+ /** The places they are signed in. */
794
+ useSessions() {
795
+ return useQuery(api.query("me.sessions.list", {}));
796
+ },
797
+ /** Sign out one of their sessions, by its id. */
798
+ useRevokeSession() {
799
+ return useMutation(api.mutation("me.sessions.revoke"));
800
+ },
801
+ /** Who they act for and who acts for them. */
802
+ useFamily() {
803
+ return useQuery(api.query("me.family", {}));
804
+ },
805
+ /** One page of their orders with lines, newest first: pass a page's `nextCursor` for the next. */
806
+ useOrders(cursor) {
807
+ // Keyed under my.list, so a mutation that makes my.list stale refreshes it too.
808
+ return useQuery({
809
+ queryKey: ["my.list", { object: "order", account: true, cursor: cursor ?? null }],
810
+ queryFn: () => loadOrders(api, cursor),
811
+ });
812
+ },
813
+ /** The subscriptions they pay, newest first (the host lists a customer only those). */
814
+ useSubscriptions() {
815
+ return useQuery(api.query("subscription.list", { limit: 50 }));
816
+ },
817
+ /** End one they pay when its period ends (web only). */
818
+ useCancelSubscription() {
819
+ return useMutation(api.mutation("subscription.cancel"));
820
+ },
821
+ /** Keep going one cancelled at the period's end, before it ends (web only). */
822
+ useResumeSubscription() {
823
+ return useMutation(api.mutation("subscription.resume"));
824
+ },
825
+ /** The provider's page for their card and past invoices (web only, never in a frame). */
826
+ useBillingPortal() {
827
+ return useMutation(api.mutation("subscription.portal"));
828
+ },
829
+ /**
830
+ * Pay one of their own orders on the provider's page (web only, ADR 0714): the host says what
831
+ * is charged (the order, its deposit or the rest) and answers the page's address.
832
+ */
833
+ useCheckoutOrder() {
834
+ return useMutation(api.mutation("order.checkout"));
835
+ },
836
+ /** Their contact preferences, and each child's they act for (stage 30). */
837
+ useContactChoices() {
838
+ return useQuery(api.query("me.contact.choices", {}));
839
+ },
840
+ /** Change one or more of them (`contactToggle` makes the change for one channel). */
841
+ useSetContactChoices() {
842
+ return useMutation(api.mutation("me.contact.setChoices"));
843
+ },
844
+ };
845
+ }