@composable-os/pack-memberships 0.1.0-beta.11 → 0.1.0-beta.14

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.
@@ -1,6 +1,8 @@
1
1
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
- export declare function MyMemberships({ memberships, returnUrl, }: {
3
- memberships: Pick<MembershipsHooks, "useMine" | "useMySubscriptions" | "useCancelSubscription" | "useResumeSubscription" | "useBillingPortal" | "usePlans" | "useChangePlan">;
4
- /** Where the provider's portal's back link goes (one of the host's listed origins). */
5
- returnUrl: string;
2
+ type Hooks = Pick<MembershipsHooks, "useMine" | "useMySubscriptions" | "useCancelSubscription" | "useResumeSubscription" | "usePlans" | "useChangePlan" | "useCoolingOff" | "useCoolOff"> & Partial<Pick<MembershipsHooks, "useFamily">>;
3
+ export declare function MyMemberships({ memberships, }: {
4
+ memberships: Hooks;
5
+ /** Kept for a page that still passes it: the card is My account's Payment method section. */
6
+ returnUrl?: string;
6
7
  }): import("react").JSX.Element;
8
+ export {};
@@ -1,16 +1,18 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { allowsWords, canChangePlan, changeRefusalWords, changeWords, day, formatPrice, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { allowsWords, canChangePlan, changeRefusalWords, changeWords, coolingOffClosedWords, coolingOffWords, coolOffProgressWords, coolOffRefusalWords, day, formatMinor, formatPrice, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
3
3
  import { useState } from "react";
4
4
  import { Button } from "../ui-button/button.js";
5
5
  import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui-card/card.js";
6
- export function MyMemberships({ memberships, returnUrl, }) {
6
+ import { MySubscriptions } from "../web-account-subscriptions/subscriptions.js";
7
+ export function MyMemberships({ memberships, }) {
7
8
  const mine = memberships.useMine();
8
9
  const subs = memberships.useMySubscriptions();
9
- const cancel = memberships.useCancelSubscription();
10
- const resume = memberships.useResumeSubscription();
11
- const portal = memberships.useBillingPortal();
12
10
  const plans = memberships.usePlans();
13
11
  const change = memberships.useChangePlan();
12
+ const coolOff = memberships.useCoolOff();
13
+ const all = subs.data?.items ?? [];
14
+ // The host's answer for each: offered or not, and a cooling off asked for.
15
+ const cooling = memberships.useCoolingOff(all.map((sub) => sub.id));
14
16
  const [choosing, setChoosing] = useState(null);
15
17
  const [planId, setPlanId] = useState("");
16
18
  const [said, setSaid] = useState(null);
@@ -19,30 +21,27 @@ export function MyMemberships({ memberships, returnUrl, }) {
19
21
  return _jsx("p", { "aria-busy": "true", children: "Loading your memberships\u2026" });
20
22
  if (mine.error || !mine.data)
21
23
  return _jsx("p", { role: "alert", children: "We could not load your memberships." });
22
- const live = (subs.data?.items ?? []).filter(isLive);
23
- async function act(run, done) {
24
- setProblem(null);
25
- setSaid(null);
26
- try {
27
- await run();
28
- setSaid(done);
29
- }
30
- catch (e) {
31
- setProblem(e instanceof Error ? e.message : "That did not work");
24
+ const statusOf = (id) => cooling.data?.items.find((c) => c.subscriptionId === id);
25
+ // One ended in its cooling-off period stays shown, with where its refund is.
26
+ const cooledOff = all.filter((sub) => !isLive(sub) && statusOf(sub.id)?.coolOff?.state === "ended");
27
+ const busy = change.isPending || coolOff.isPending;
28
+ async function onCoolOff(sub, status) {
29
+ const refund = formatMinor(status.refund, status.currency);
30
+ if (!window.confirm(`End your membership now, for a full refund of ${refund}? It stops at once; the business approves the refund.`)) {
31
+ return;
32
32
  }
33
- }
34
- async function onPortal() {
35
33
  setProblem(null);
34
+ setSaid(null);
36
35
  try {
37
- const opened = await portal.mutateAsync({ returnUrl });
38
- window.location.assign(opened.url);
36
+ const done = await coolOff.mutateAsync({ id: sub.id });
37
+ setSaid(done.asked === "unknown"
38
+ ? "We asked the payment provider to end it and did not hear back. It shows here once it answers; the business has been told."
39
+ : `Asked to end it now. A full refund of ${formatMinor(done.refund, done.currency)} is owed once the payment provider confirms; the business approves it.`);
39
40
  }
40
41
  catch (e) {
41
- setProblem(e instanceof Error ? e.message : "We could not open your billing");
42
+ setProblem(coolOffRefusalWords(e.details));
42
43
  }
43
44
  }
44
- const ending = (sub) => sub.cancelAtPeriodEnd || sub.cancelAt !== null;
45
- const busy = cancel.isPending || resume.isPending || portal.isPending || change.isPending;
46
45
  async function onChange(sub) {
47
46
  setProblem(null);
48
47
  setSaid(null);
@@ -64,15 +63,48 @@ export function MyMemberships({ memberships, returnUrl, }) {
64
63
  setProblem(changeRefusalWords(details));
65
64
  }
66
65
  }
67
- return (_jsxs("section", { className: "grid gap-4", "aria-label": "My memberships", children: [mine.data.holdings.length ? null : _jsx("p", { children: "You have no membership or pass yet." }), mine.data.holdings.map((h) => (_jsxs(Card, { "data-kind": h.kind, children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: h.title }), _jsx(CardDescription, { children: allowsWords(h) })] }), _jsxs(CardContent, { className: "grid gap-1", children: [_jsx("p", { "data-testid": "holding-left", children: leftWords(h) }), h.until ? (_jsx("p", { className: "text-sm", children: `${h.kind === "pass" ? "Expires" : "Until"} ${day(h.until)}` })) : null] })] }, h.id))), live.map((sub) => (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: sub.planTitle }), _jsx(CardDescription, { children: "Your membership's billing" })] }), _jsxs(CardContent, { className: "grid gap-3", children: [_jsx("p", { "data-testid": "subscription-status", children: subscriptionStatus(sub) }), changeWords(sub) ? _jsx("p", { "data-testid": "subscription-change", children: changeWords(sub) }) : null, sub.change?.actionUrl && sub.change.state === "requested" ? (_jsx(Button, { onClick: () => window.location.assign(sub.change?.actionUrl ?? ""), children: "Confirm the new plan's payment" })) : null, choosing === sub.id ? (_jsxs("div", { className: "grid max-w-sm gap-2", children: [_jsx("label", { htmlFor: `change-plan-${sub.id}`, children: "Move to" }), _jsxs("select", { id: `change-plan-${sub.id}`, className: "rounded-md border px-2 py-1", value: planId, onChange: (e) => setPlanId(e.target.value), children: [_jsx("option", { value: "", children: "Choose a plan" }), (plans.data?.plans ?? [])
68
- .filter((p) => p.id !== sub.planId)
69
- .map((p) => (_jsx("option", { value: p.id, children: `${p.title ?? ""}: ${formatPrice(p.price, plans.data?.currency)} a month` }, p.id)))] }), _jsx("p", { className: "text-sm", children: "A dearer plan starts now and the rest of this month is charged to your card; a cheaper one starts when this month ends." }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { disabled: busy || !planId, onClick: () => void onChange(sub), children: "Change plan" }), _jsx(Button, { variant: "outline", onClick: () => setChoosing(null), children: "Keep this plan" })] })] })) : null, _jsxs("div", { className: "flex flex-wrap gap-2", children: [sub.actionUrl ? (_jsx(Button, { onClick: () => window.location.assign(sub.actionUrl ?? ""), children: "Confirm your payment" })) : null, sub.cancelAtPeriodEnd ? (_jsx(Button, { disabled: busy, onClick: () => void act(() => resume.mutateAsync({ id: sub.id }), "Asked to keep it going. It shows here once the payment provider confirms."), children: "Keep my membership" })) : ending(sub) ? null : (_jsx(Button, { variant: "outline", disabled: busy, onClick: () => {
70
- if (!window.confirm("Cancel? Your membership runs until the period ends.")) {
71
- return;
72
- }
73
- void act(() => cancel.mutateAsync({ id: sub.id, reason: "Cancelled by the member" }), "Asked to cancel. It ends when the period does; it shows here once the payment provider confirms.");
74
- }, children: "Cancel membership" })), canChangePlan(sub) && choosing !== sub.id ? (_jsx(Button, { variant: "outline", disabled: busy, onClick: () => {
75
- setPlanId("");
76
- setChoosing(sub.id);
77
- }, children: "Change plan" })) : null, _jsx(Button, { variant: "outline", disabled: busy, onClick: () => void onPortal(), children: "Card and invoices" })] })] })] }, sub.id))), said ? _jsx("p", { role: "status", children: said }) : null, problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
66
+ /** The membership's own lines: a cooling off, a plan change waiting, the change of plan chooser. */
67
+ const about = (sub) => {
68
+ const status = statusOf(sub.id);
69
+ const cooling = coolingOffWords(status) ?? coolOffProgressWords(status) ?? coolingOffClosedWords(status);
70
+ return (_jsxs(_Fragment, { children: [cooling ? _jsx("p", { "data-testid": "cooling-off", children: cooling }) : null, changeWords(sub) ? _jsx("p", { "data-testid": "subscription-change", children: changeWords(sub) }) : null, sub.change?.actionUrl && sub.change.state === "requested" ? (_jsx("div", { children: _jsx(Button, { onClick: () => window.location.assign(sub.change?.actionUrl ?? ""), children: "Confirm the new plan's payment" }) })) : null, choosing === sub.id ? (_jsxs("div", { className: "grid max-w-sm gap-2", children: [_jsx("label", { htmlFor: `change-plan-${sub.id}`, children: "Move to" }), _jsxs("select", { id: `change-plan-${sub.id}`, className: "rounded-md border px-2 py-1", value: planId, onChange: (e) => setPlanId(e.target.value), children: [_jsx("option", { value: "", children: "Choose a plan" }), (plans.data?.plans ?? [])
71
+ .filter((p) => p.id !== sub.planId)
72
+ .map((p) => (_jsx("option", { value: p.id, children: `${p.title ?? ""}: ${formatPrice(p.price, plans.data?.currency)} a month` }, p.id)))] }), _jsx("p", { className: "text-sm", children: "A dearer plan starts now and the rest of this month is charged to your card; a cheaper one starts when this month ends." }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { disabled: busy || !planId, onClick: () => void onChange(sub), children: "Change plan" }), _jsx(Button, { variant: "outline", onClick: () => setChoosing(null), children: "Keep this plan" })] })] })) : null] }));
73
+ };
74
+ /** The membership's own buttons: cooling off and the change of plan. */
75
+ const buttons = (sub) => {
76
+ const status = statusOf(sub.id);
77
+ return (_jsxs(_Fragment, { children: [status?.offered ? (_jsx(Button, { variant: "outline", disabled: busy, onClick: () => void onCoolOff(sub, status), children: "Cancel for a full refund" })) : status?.coolOff?.askAgain ? (_jsx(Button, { variant: "outline", disabled: busy, onClick: () => void onCoolOff(sub, status), children: "Ask again to end it for a full refund" })) : null, canChangePlan(sub) && !status?.coolOff?.open && choosing !== sub.id ? (_jsx(Button, { variant: "outline", disabled: busy, onClick: () => {
78
+ setPlanId("");
79
+ setChoosing(sub.id);
80
+ }, children: "Change plan" })) : null] }));
81
+ };
82
+ return (_jsxs("section", { className: "grid gap-4", "aria-label": "My memberships", children: [mine.data.holdings.length ? null : _jsx("p", { children: "You have no membership or pass yet." }), _jsx(Holdings, { holdings: mine.data.holdings }), _jsx(MySubscriptions, { account: {
83
+ useSubscriptions: memberships.useMySubscriptions,
84
+ useCancelSubscription: memberships.useCancelSubscription,
85
+ useResumeSubscription: memberships.useResumeSubscription,
86
+ }, label: "Your membership's billing", empty: null, status: subscriptionStatus, about: about, change: buttons,
87
+ // While a cooling off is under way, it ends the membership: no ordinary cancel beside it.
88
+ cancellable: (sub) => !statusOf(sub.id)?.coolOff?.open, words: {
89
+ cancel: "Cancel membership",
90
+ resume: "Keep my membership",
91
+ confirmCancel: "Cancel? Your membership runs until the period ends.",
92
+ description: () => "Your membership's billing",
93
+ } }), cooledOff.map((sub) => (_jsxs(Card, { "data-kind": "cooled-off", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: sub.planTitle }), _jsx(CardDescription, { children: "Your membership's billing" })] }), _jsxs(CardContent, { className: "grid gap-3", children: [_jsx("p", { "data-testid": "subscription-status", children: `Ended${sub.endedAt ? ` on ${day(sub.endedAt)}` : ""}` }), _jsx("p", { "data-testid": "cooling-off", children: coolOffProgressWords(statusOf(sub.id)) })] })] }, sub.id))), memberships.useFamily ? (_jsx(Children, { memberships: { useFamily: memberships.useFamily, useMine: memberships.useMine } })) : null, said ? _jsx("p", { role: "status", children: said }) : null, problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
94
+ }
95
+ function Holdings({ holdings }) {
96
+ return holdings.map((h) => (_jsxs(Card, { "data-kind": h.kind, children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: h.title }), _jsx(CardDescription, { children: allowsWords(h) })] }), _jsxs(CardContent, { className: "grid gap-1", children: [_jsx("p", { "data-testid": "holding-left", children: leftWords(h) }), h.until ? (_jsx("p", { className: "text-sm", children: `${h.kind === "pass" ? "Expires" : "Until"} ${day(h.until)}` })) : null] })] }, h.id)));
97
+ }
98
+ /** Each child the gym linked to the member, with their memberships and passes, under their name. */
99
+ function Children({ memberships, }) {
100
+ const family = memberships.useFamily();
101
+ const children = family.data?.dependants ?? [];
102
+ return children.map((child) => (_jsx(Child, { child: child, memberships: memberships }, child.personId)));
103
+ }
104
+ function Child({ child, memberships, }) {
105
+ const theirs = memberships.useMine(child.personId);
106
+ // A child with nothing here, or whose records the host does not show a guardian, shows nothing.
107
+ if (!theirs.data?.holdings.length)
108
+ return null;
109
+ return (_jsxs("section", { className: "grid gap-3", "aria-label": `${child.name}'s memberships and passes`, "data-person": child.personId, children: [_jsx("h3", { className: "font-medium", children: `${child.name}'s memberships and passes` }), _jsx(Holdings, { holdings: theirs.data.holdings })] }));
78
110
  }
@@ -1,4 +1,8 @@
1
1
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
- export declare function MyMembershipsScreen({ memberships, }: {
3
- memberships: Pick<MembershipsHooks, "useMine" | "useMySubscriptions">;
2
+ type Hooks = Pick<MembershipsHooks, "useMine" | "useMySubscriptions" | "useCoolingOff"> & Partial<Pick<MembershipsHooks, "useFamily">>;
3
+ export declare function MyMembershipsScreen({ memberships, onManage, }: {
4
+ memberships: Hooks;
5
+ /** Opens the business's website account page (the account shell gives it). */
6
+ onManage?: () => void;
4
7
  }): import("react").JSX.Element;
8
+ export {};
@@ -1,12 +1,36 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { allowsWords, changeWords, day, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
3
- import { Text } from "react-native";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { allowsWords, changeWords, coolingOffClosedWords, coolOffProgressWords, day, isLive, leftWords, localDay, subscriptionStatus, } from "@composable-os/pack-memberships/client";
3
+ import { MySubscriptions } from "../native-account-subscriptions/subscriptions.js";
4
4
  import { List } from "../native-base/list.js";
5
5
  import { Row } from "../native-base/row.js";
6
6
  import { Screen } from "../native-base/screen.js";
7
- export function MyMembershipsScreen({ memberships, }) {
7
+ import { Text } from "../native-base/text.js";
8
+ export function MyMembershipsScreen({ memberships, onManage, }) {
8
9
  const { data, isPending, error } = memberships.useMine();
9
10
  const subs = memberships.useMySubscriptions();
10
- const live = subs.data?.items.filter(isLive) ?? [];
11
- return (_jsxs(Screen, { title: "My memberships", children: [isPending ? _jsx(Text, { accessibilityRole: "progressbar", children: "Loading your memberships\u2026" }) : null, error ? _jsx(Text, { accessibilityRole: "alert", children: "We could not load your memberships." }) : null, data ? (_jsx(List, { empty: "You have no membership or pass yet.", children: data.holdings.map((h) => (_jsx(Row, { title: h.title ?? "", detail: `${leftWords(h)} · ${allowsWords(h)}${h.until ? ` · until ${day(h.until)}` : ""}` }, h.id))) })) : null, live.map((sub) => (_jsx(Text, { children: `${sub.planTitle}: ${subscriptionStatus(sub)}${changeWords(sub) ? `. ${changeWords(sub)}` : ""}` }, sub.id))), live.length ? _jsx(Text, { children: "Manage your membership on the gym's website." }) : null] }));
11
+ const all = subs.data?.items ?? [];
12
+ const cooling = memberships.useCoolingOff(all.map((sub) => sub.id));
13
+ const statusOf = (id) => cooling.data?.items.find((c) => c.subscriptionId === id);
14
+ const cooledOff = all.filter((sub) => !isLive(sub) && statusOf(sub.id)?.coolOff?.state === "ended");
15
+ return (_jsxs(Screen, { title: "My memberships", children: [isPending ? (_jsx(Text, { tone: "muted", accessibilityRole: "progressbar", children: "Loading your memberships\u2026" })) : null, error ? _jsx(Text, { accessibilityRole: "alert", children: "We could not load your memberships." }) : null, data ? (_jsx(List, { empty: "You have no membership or pass yet.", children: holdingRows(data.holdings) })) : null, _jsx(MySubscriptions, { account: { useSubscriptions: memberships.useMySubscriptions }, onManage: onManage, empty: null, status: subscriptionStatus, manageWords: "Manage your membership on the gym's website.", about: (sub) => {
16
+ const status = statusOf(sub.id);
17
+ const words = status?.offered
18
+ ? `You can cancel for a full refund until the end of ${localDay(status.until)}, on the gym's website.`
19
+ : (coolOffProgressWords(status, { amounts: false }) ?? coolingOffClosedWords(status));
20
+ return [changeWords(sub), words].filter(Boolean).join(" ") || null;
21
+ } }), cooledOff.map((sub) => (_jsx(Text, { children: `${sub.planTitle}: ${coolOffProgressWords(statusOf(sub.id), { amounts: false }) ?? "Ended"}` }, sub.id))), memberships.useFamily ? (_jsx(Children, { memberships: { useFamily: memberships.useFamily, useMine: memberships.useMine } })) : null] }));
22
+ }
23
+ function holdingRows(holdings) {
24
+ return holdings.map((h) => (_jsx(Row, { title: h.title ?? "", detail: `${leftWords(h)} · ${allowsWords(h)}${h.until ? ` · until ${day(h.until)}` : ""}` }, h.id)));
25
+ }
26
+ /** Each child the gym linked to the member, with their memberships and passes, under their name. */
27
+ function Children({ memberships, }) {
28
+ const family = memberships.useFamily();
29
+ return (family.data?.dependants ?? []).map((child) => (_jsx(Child, { child: child, memberships: memberships }, child.personId)));
30
+ }
31
+ function Child({ child, memberships, }) {
32
+ const theirs = memberships.useMine(child.personId);
33
+ if (!theirs.data?.holdings.length)
34
+ return null;
35
+ return (_jsxs(_Fragment, { children: [_jsx(Text, { children: `${child.name}'s memberships and passes` }), _jsx(List, { children: holdingRows(theirs.data.holdings) })] }));
12
36
  }
@@ -1,6 +1,11 @@
1
+ import { type AgreementsHooks } from "@composable-os/client";
1
2
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
- export declare function Passes({ memberships, returnUrl, signedIn, signInUrl, }: {
3
+ /** The agreements hooks the inline step uses: a member's (due, accept) and a visitor's (words). */
4
+ export type PassesAgreements = Pick<AgreementsHooks, "useDue" | "useAccept" | "useGuestVersions">;
5
+ export declare function Passes({ memberships, agreements, returnUrl, signedIn, signInUrl, }: {
3
6
  memberships: Pick<MembershipsHooks, "usePassTypes" | "useBuyPass">;
7
+ /** For what must be agreed to first, shown inline. Without it, the refusal is only named. */
8
+ agreements?: PassesAgreements;
4
9
  /** Where the provider's page sends the buyer back to (one of the host's listed origins). */
5
10
  returnUrl: string;
6
11
  /** A signed-in customer buys as themselves; a guest gives their email. */
@@ -1,29 +1,74 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // Buying a pass on a gym's site (stage 32b): the pass types on sale (class packs, drop-ins, an
3
+ // intro offer) with the host's price, what each gives and how long it is valid, and a button that
4
+ // starts the order and opens the payment provider's page. The price, whether it is on sale, and
5
+ // the intro offer's one per person are the host's (`x.memberships.buy`, the host's order): a guest is
6
+ // refused an intro offer and told to sign in, and a second one is refused, whatever this shows.
7
+ // The pass is granted by the host once the provider confirms the payment. Web only.
8
+ //
9
+ // What must be agreed to first (stage 44: the terms, a waiver) is the host's answer too: when
10
+ // "Buy" is refused with it, the documents are shown inline (the web-agree block's step) and "Buy"
11
+ // is tried again. A visitor's agreements travel in the buying call, held in memory until then; a
12
+ // member's are recorded as they agree. A minor is told a parent or guardian buys it.
13
+ import { agreementRefusal, forgetAfter, purchaseErrorWords, withAgreements, } from "@composable-os/client";
2
14
  import { allowsWords, formatPrice, refusalWords } from "@composable-os/pack-memberships/client";
3
15
  import { useState } from "react";
4
16
  import { Button } from "../ui-button/button.js";
5
17
  import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui-card/card.js";
6
18
  import { Input } from "../ui-input/input.js";
7
19
  import { Label } from "../ui-label/label.js";
8
- export function Passes({ memberships, returnUrl, signedIn, signInUrl, }) {
20
+ import { useForgetOnLeave } from "../web-agree/agree.js";
21
+ import { GuestAgreementStep, MemberAgreementStep } from "../web-agree/agreement-step.js";
22
+ export function Passes({ memberships, agreements, returnUrl, signedIn, signInUrl, }) {
9
23
  const { data, isPending, error } = memberships.usePassTypes();
10
24
  const { start, checkout } = memberships.useBuyPass();
11
25
  const [email, setEmail] = useState("");
12
26
  const [problem, setProblem] = useState(null);
27
+ // What the host said must be agreed to first, for which pass.
28
+ const [due, setDue] = useState(null);
29
+ // A visitor's agreements for one pass: this component's state only, kept if the purchase does
30
+ // not start (nothing typed twice), forgotten once it starts and when they leave the page.
31
+ const [agreed, setAgreed] = useState(null);
32
+ // A member's "a copy is on its way", for the pass they agreed for.
33
+ const [said, setSaid] = useState(null);
34
+ const [busy, setBusy] = useState(false);
35
+ useForgetOnLeave(() => setAgreed(null));
13
36
  if (isPending)
14
37
  return _jsx("p", { "aria-busy": "true", children: "Loading the passes\u2026" });
15
38
  if (error || !data)
16
39
  return _jsx("p", { role: "alert", children: "We could not load the passes." });
17
40
  if (!data.passTypes.length)
18
41
  return _jsx("p", { children: "No passes are on sale yet." });
19
- async function onBuy(passTypeId) {
42
+ async function onBuy(passTypeId, given = agreed?.id === passTypeId ? agreed.given : null) {
20
43
  setProblem(null);
44
+ setBusy(true);
21
45
  try {
22
- const order = await start.mutateAsync({
46
+ const outcome = await withAgreements((previous) => forgetAfter(start, {
23
47
  passTypeId,
24
48
  ...(signedIn ? {} : { email }),
25
- });
26
- const page = await checkout.mutateAsync({
49
+ ...(!signedIn && given && previous?.kind !== "read_again" ? { agreements: given } : {}),
50
+ }));
51
+ if (outcome.kind !== "done")
52
+ setAgreed(null);
53
+ if (outcome.kind === "due") {
54
+ if (agreements)
55
+ setDue({ id: passTypeId, documents: outcome.documents });
56
+ else {
57
+ setProblem({
58
+ id: passTypeId,
59
+ words: `Something must be agreed to first: ${outcome.documents.map((d) => d.title).join(", ")}.`,
60
+ });
61
+ }
62
+ return;
63
+ }
64
+ if (outcome.kind === "minor_payer") {
65
+ setProblem({ id: passTypeId, words: outcome.message });
66
+ return;
67
+ }
68
+ const order = outcome.value;
69
+ // Recorded with the order: nothing of it is kept here any more.
70
+ setAgreed(null);
71
+ const page = await forgetAfter(checkout, {
27
72
  id: order.id,
28
73
  ...(order.token ? { token: order.token } : {}),
29
74
  returnUrl,
@@ -31,13 +76,35 @@ export function Passes({ memberships, returnUrl, signedIn, signInUrl, }) {
31
76
  window.location.assign(page.url);
32
77
  }
33
78
  catch (e) {
79
+ const refusal = agreementRefusal(e);
80
+ if (refusal)
81
+ setAgreed(null);
34
82
  const details = e.details;
35
- setProblem({ id: passTypeId, words: refusalWords(details) });
83
+ setProblem({
84
+ id: passTypeId,
85
+ words: purchaseErrorWords(e) ?? (refusal ? refusal.message : refusalWords(details)),
86
+ });
36
87
  }
88
+ finally {
89
+ setBusy(false);
90
+ }
91
+ }
92
+ if (due && agreements) {
93
+ const back = () => setDue(null);
94
+ const passTypeId = due.id;
95
+ return signedIn ? (_jsx(MemberAgreementStep, { agreements: agreements, documents: due.documents, continueLabel: "Agree and buy", onCancel: back, onAgreed: (copy) => {
96
+ setDue(null);
97
+ if (copy)
98
+ setSaid({ id: passTypeId, words: copy });
99
+ void onBuy(passTypeId, null);
100
+ } })) : (_jsx(GuestAgreementStep, { agreements: agreements, documents: due.documents, continueLabel: "Agree and buy", onCancel: back, onAgreed: (given) => {
101
+ setDue(null);
102
+ setAgreed({ id: passTypeId, given });
103
+ void onBuy(passTypeId, given);
104
+ } }));
37
105
  }
38
- const busy = start.isPending || checkout.isPending;
39
106
  return (_jsx("section", { className: "grid gap-4", "aria-label": "Passes", children: data.passTypes.map((type) => (_jsxs(Card, { "data-intro": type.onePerPerson ? "true" : undefined, children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: type.title }), _jsx(CardDescription, { children: `${formatPrice(type.price, data.currency)} · ${type.summary ?? allowsWords({ ...type, per: "total" })}${type.validDays ? ` · valid ${type.validDays} days` : ""}` })] }), _jsxs(CardContent, { children: [type.description ? _jsx("p", { children: type.description }) : null, type.onePerPerson ? (_jsxs("p", { className: "text-sm", children: [signedIn ? "One per person." : "One per person: sign in to buy it.", !signedIn && signInUrl ? (_jsxs(_Fragment, { children: [" ", _jsx("a", { href: signInUrl, className: "underline", children: "Sign in" })] })) : null] })) : null, _jsxs("form", { className: "grid max-w-sm gap-2", onSubmit: (e) => {
40
107
  e.preventDefault();
41
108
  void onBuy(type.id);
42
- }, children: [signedIn ? null : (_jsxs(_Fragment, { children: [_jsx(Label, { htmlFor: `pass-email-${type.id}`, children: "Your email" }), _jsx(Input, { id: `pass-email-${type.id}`, type: "email", required: true, value: email, onChange: (e) => setEmail(e.target.value) })] })), _jsx(Button, { type: "submit", disabled: busy, children: "Buy" }), problem?.id === type.id ? _jsx("p", { role: "alert", children: problem.words }) : null] })] })] }, type.id))) }));
109
+ }, children: [signedIn ? null : (_jsxs(_Fragment, { children: [_jsx(Label, { htmlFor: `pass-email-${type.id}`, children: "Your email" }), _jsx(Input, { id: `pass-email-${type.id}`, type: "email", required: true, value: email, onChange: (e) => setEmail(e.target.value) })] })), _jsx(Button, { type: "submit", disabled: busy, children: "Buy" }), said?.id === type.id ? _jsx("p", { role: "status", children: said.words }) : null, agreed?.id === type.id ? (_jsx("p", { className: "text-sm", children: "What you agreed to is kept for this purchase: press Buy to try again." })) : null, problem?.id === type.id ? _jsx("p", { role: "alert", children: problem.words }) : null] })] })] }, type.id))) }));
43
110
  }
@@ -1,11 +1,16 @@
1
+ import { type AgreementsHooks } from "@composable-os/client";
1
2
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
3
+ /** The agreements hooks the inline step uses: a member's (due, accept) and a visitor's (words). */
4
+ export type PlansAgreements = Pick<AgreementsHooks, "useDue" | "useAccept" | "useGuestVersions">;
2
5
  /** Signing a guest in by an emailed code, as the app does it (the web sign-in block's calls). */
3
6
  export interface PlansSignIn {
4
7
  requestCode: (email: string) => Promise<boolean>;
5
8
  confirm: (email: string, code: string) => Promise<"ready" | "needs_attention" | null>;
6
9
  }
7
- export declare function Plans({ memberships, returnUrl, signedIn, signIn, }: {
10
+ export declare function Plans({ memberships, agreements, returnUrl, signedIn, signIn, }: {
8
11
  memberships: Pick<MembershipsHooks, "usePlans" | "useSubscribe">;
12
+ /** For what must be agreed to first, shown inline. Without it, the refusal is only named. */
13
+ agreements?: PlansAgreements;
9
14
  /** Where the provider's page sends the member back to (one of the host's listed origins). */
10
15
  returnUrl: string;
11
16
  /** A signed-in customer subscribes as themselves; a guest gives their email. */
@@ -1,10 +1,28 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // Joining a gym on its site (stage 32b): the membership plans on sale with the host's price per
3
+ // month, what each allows and its trial, and a button that opens the payment provider's page. The
4
+ // price is the host's (`usePlans`); whether the trial is given, and the page, are the host's
5
+ // (`useSubscribe`, `subscription.start`): one trial per person per plan object, signed in. The
6
+ // membership itself is granted by the host once the provider confirms the subscription. Web only.
7
+ //
8
+ // A guest who wants the trial confirms their address with a code here, on the plan, when the app
9
+ // passes `signIn` (the web sign-in block's two calls), and goes on to the provider's page signed
10
+ // in, with the trial (ADR 0459). Whether a new address gets a code is the host's.
11
+ //
12
+ // What must be agreed to first (stage 44: the membership terms, a waiver) is the host's answer
13
+ // too: when "Join" is refused with it, the documents are shown inline (the web-agree block's
14
+ // step) and "Join" is tried again. A visitor's agreements travel in subscription.start, held in
15
+ // memory until then; a member's are recorded as they agree. A minor is told a parent or guardian
16
+ // buys it.
17
+ import { agreementRefusal, forgetAfter, purchaseErrorWords, withAgreements, } from "@composable-os/client";
2
18
  import { allowsWords, formatPrice, PLAN } from "@composable-os/pack-memberships/client";
3
19
  import { useState } from "react";
4
20
  import { Button } from "../ui-button/button.js";
5
21
  import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui-card/card.js";
6
22
  import { Input } from "../ui-input/input.js";
7
23
  import { Label } from "../ui-label/label.js";
24
+ import { useForgetOnLeave } from "../web-agree/agree.js";
25
+ import { GuestAgreementStep, MemberAgreementStep } from "../web-agree/agreement-step.js";
8
26
  /** Why the host gave no trial, in words. Display only. */
9
27
  function noTrialWords(reason) {
10
28
  switch (reason) {
@@ -22,7 +40,7 @@ function noTrialWords(reason) {
22
40
  return "You have free time with us on a continuing membership: this one is paid from today.";
23
41
  }
24
42
  }
25
- export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
43
+ export function Plans({ memberships, agreements, returnUrl, signedIn, signIn, }) {
26
44
  const { data, isPending, error } = memberships.usePlans();
27
45
  const subscribe = memberships.useSubscribe();
28
46
  const [email, setEmail] = useState("");
@@ -32,6 +50,14 @@ export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
32
50
  const [codeSent, setCodeSent] = useState(false);
33
51
  const [code, setCode] = useState("");
34
52
  const [busy, setBusy] = useState(false);
53
+ // What the host said must be agreed to first, for which plan, and as whom.
54
+ const [due, setDue] = useState(null);
55
+ // A visitor's agreements for one plan: this component's state only, kept if the membership does
56
+ // not start (nothing typed twice), forgotten once it starts and when they leave the page.
57
+ const [agreed, setAgreed] = useState(null);
58
+ // A member's "a copy is on its way".
59
+ const [said, setSaid] = useState(null);
60
+ useForgetOnLeave(() => setAgreed(null));
35
61
  const asCustomer = signedIn || confirmed;
36
62
  if (isPending)
37
63
  return _jsx("p", { "aria-busy": "true", children: "Loading the memberships\u2026" });
@@ -39,15 +65,33 @@ export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
39
65
  return _jsx("p", { role: "alert", children: "We could not load the memberships." });
40
66
  if (!data.plans.length)
41
67
  return _jsx("p", { children: "No memberships are on sale yet." });
42
- async function onSubscribe(planId, hasTrial, customer = asCustomer) {
68
+ async function onSubscribe(planId, hasTrial, customer = asCustomer, given = agreed?.planId === planId ? agreed.given : null) {
43
69
  setProblem(null);
44
70
  setNoTrial(null);
45
71
  try {
46
- const started = await subscribe.mutateAsync({
72
+ const outcome = await withAgreements((previous) => forgetAfter(subscribe, {
47
73
  plan: { object: PLAN, id: planId },
48
74
  returnUrl,
49
75
  ...(customer ? {} : { email }),
50
- });
76
+ ...(!customer && given && previous?.kind !== "read_again" ? { agreements: given } : {}),
77
+ }));
78
+ if (outcome.kind !== "done")
79
+ setAgreed(null);
80
+ if (outcome.kind === "due") {
81
+ if (agreements)
82
+ setDue({ planId, hasTrial, customer, documents: outcome.documents });
83
+ else {
84
+ setProblem(`Something must be agreed to first: ${outcome.documents.map((d) => d.title).join(", ")}.`);
85
+ }
86
+ return;
87
+ }
88
+ if (outcome.kind === "minor_payer") {
89
+ setProblem(outcome.message);
90
+ return;
91
+ }
92
+ const started = outcome.value;
93
+ // Recorded with the checkout: nothing of it is kept here any more.
94
+ setAgreed(null);
51
95
  // Never sent to a page that charges today without a word: the host's reason for no trial.
52
96
  if (hasTrial && started.noTrial)
53
97
  setNoTrial({ planId, started });
@@ -55,7 +99,15 @@ export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
55
99
  window.location.assign(started.url);
56
100
  }
57
101
  catch (e) {
58
- setProblem(e instanceof Error ? e.message : "We could not start your membership");
102
+ const refusal = agreementRefusal(e);
103
+ if (refusal)
104
+ setAgreed(null);
105
+ setProblem(purchaseErrorWords(e) ??
106
+ (refusal
107
+ ? refusal.message
108
+ : e instanceof Error
109
+ ? e.message
110
+ : "We could not start your membership"));
59
111
  }
60
112
  }
61
113
  async function onCode(event, planId) {
@@ -91,6 +143,19 @@ export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
91
143
  setBusy(false);
92
144
  }
93
145
  }
146
+ if (due && agreements) {
147
+ const { planId, hasTrial, customer } = due;
148
+ const back = () => setDue(null);
149
+ return customer ? (_jsx(MemberAgreementStep, { agreements: agreements, documents: due.documents, continueLabel: "Agree and join", onCancel: back, onAgreed: (copy) => {
150
+ setDue(null);
151
+ setSaid(copy);
152
+ void onSubscribe(planId, hasTrial, true, null);
153
+ } })) : (_jsx(GuestAgreementStep, { agreements: agreements, documents: due.documents, continueLabel: "Agree and join", onCancel: back, onAgreed: (given) => {
154
+ setDue(null);
155
+ setAgreed({ planId, given });
156
+ void onSubscribe(planId, hasTrial, false, given);
157
+ } }));
158
+ }
94
159
  const reason = noTrial?.started.noTrial;
95
160
  if (noTrial && reason) {
96
161
  const { planId, started } = noTrial;
@@ -102,5 +167,5 @@ export function Plans({ memberships, returnUrl, signedIn, signIn, }) {
102
167
  e.preventDefault();
103
168
  void onSubscribe(plan.id, trial !== null);
104
169
  }, children: [asCustomer ? null : (_jsxs(_Fragment, { children: [trial ? (_jsx("p", { children: `Sign in for your ${trial}-day free trial, or join now and pay from today.` })) : null, _jsx(Label, { htmlFor: `member-email-${plan.id}`, children: "Your email" }), _jsx(Input, { id: `member-email-${plan.id}`, type: "email", required: true, value: email, onChange: (e) => setEmail(e.target.value) })] })), _jsx(Button, { type: "submit", disabled: subscribe.isPending, children: asCustomer && trial ? `Start your ${trial}-day free trial` : "Join" }), asCustomer && trial ? (_jsx("p", { className: "text-sm", children: "Your card is taken now and charged when the trial ends, unless you cancel. One free trial per person." })) : null] })] })] }, plan.id));
105
- }), problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
170
+ }), said ? _jsx("p", { role: "status", children: said }) : null, agreed ? (_jsx("p", { className: "text-sm", children: "What you agreed to is kept for this membership: press Join to try again." })) : null, problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
106
171
  }
@@ -1,4 +1,13 @@
1
1
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
+ /**
3
+ * The staff screen as the product's admin shows it on a Person (stage 47): `PersonHoldings` with
4
+ * the pass types staff may give read from the host (the staff client's record list), so the
5
+ * admin passes it the person's id and nothing else.
6
+ */
7
+ export declare function PersonMemberships({ memberships, personId, }: {
8
+ memberships: Parameters<typeof PersonHoldings>[0]["memberships"] & Pick<MembershipsHooks, "useStaffPassTypes">;
9
+ personId: string;
10
+ }): import("react").JSX.Element;
2
11
  export declare function PersonHoldings({ memberships, personId, passTypes, }: {
3
12
  memberships: Pick<MembershipsHooks, "useHoldings" | "useGivePass" | "useVoidPass" | "useSubscriptionsOf" | "usePauseSubscription" | "useUnpauseSubscription">;
4
13
  personId: string;
@@ -5,6 +5,21 @@ import { Button } from "../ui-button/button.js";
5
5
  import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui-card/card.js";
6
6
  import { Input } from "../ui-input/input.js";
7
7
  import { Label } from "../ui-label/label.js";
8
+ /**
9
+ * The staff screen as the product's admin shows it on a Person (stage 47): `PersonHoldings` with
10
+ * the pass types staff may give read from the host (the staff client's record list), so the
11
+ * admin passes it the person's id and nothing else.
12
+ */
13
+ export function PersonMemberships({ memberships, personId, }) {
14
+ const types = memberships.useStaffPassTypes();
15
+ if (types.isPending)
16
+ return _jsx("p", { "aria-busy": "true", children: "Loading\u2026" });
17
+ const passTypes = (types.data?.items ?? []).map((t) => ({
18
+ id: t.id,
19
+ title: typeof t.values.title === "string" ? t.values.title : "Pass",
20
+ }));
21
+ return _jsx(PersonHoldings, { memberships: memberships, personId: personId, passTypes: passTypes });
22
+ }
8
23
  export function PersonHoldings({ memberships, personId, passTypes, }) {
9
24
  const held = memberships.useHoldings(personId);
10
25
  const give = memberships.useGivePass();