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

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,6 @@
1
1
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
2
  export declare function MyMemberships({ memberships, returnUrl, }: {
3
- memberships: Pick<MembershipsHooks, "useMine" | "useMySubscriptions" | "useCancelSubscription" | "useResumeSubscription" | "useBillingPortal">;
3
+ memberships: Pick<MembershipsHooks, "useMine" | "useMySubscriptions" | "useCancelSubscription" | "useResumeSubscription" | "useBillingPortal" | "usePlans" | "useChangePlan">;
4
4
  /** Where the provider's portal's back link goes (one of the host's listed origins). */
5
5
  returnUrl: string;
6
6
  }): import("react").JSX.Element;
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { allowsWords, day, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
2
+ import { allowsWords, canChangePlan, changeRefusalWords, changeWords, day, 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";
@@ -9,6 +9,10 @@ export function MyMemberships({ memberships, returnUrl, }) {
9
9
  const cancel = memberships.useCancelSubscription();
10
10
  const resume = memberships.useResumeSubscription();
11
11
  const portal = memberships.useBillingPortal();
12
+ const plans = memberships.usePlans();
13
+ const change = memberships.useChangePlan();
14
+ const [choosing, setChoosing] = useState(null);
15
+ const [planId, setPlanId] = useState("");
12
16
  const [said, setSaid] = useState(null);
13
17
  const [problem, setProblem] = useState(null);
14
18
  if (mine.isPending)
@@ -38,11 +42,37 @@ export function MyMemberships({ memberships, returnUrl, }) {
38
42
  }
39
43
  }
40
44
  const ending = (sub) => sub.cancelAtPeriodEnd || sub.cancelAt !== null;
41
- const busy = cancel.isPending || resume.isPending || portal.isPending;
42
- 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) }), _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: () => {
45
+ const busy = cancel.isPending || resume.isPending || portal.isPending || change.isPending;
46
+ async function onChange(sub) {
47
+ setProblem(null);
48
+ setSaid(null);
49
+ try {
50
+ const asked = await change.mutateAsync({
51
+ id: sub.id,
52
+ planId,
53
+ reason: "Changed by the member",
54
+ });
55
+ setChoosing(null);
56
+ setSaid(asked.asked === "unknown"
57
+ ? "We asked the payment provider and did not hear back. Your plan shows here once it answers."
58
+ : asked.kind === "upgrade"
59
+ ? "Asked to change now. The rest of this period is charged to your card; the new plan shows here once the payment provider confirms it."
60
+ : `Your plan changes on ${day(asked.effectiveAt)}, when this period ends. Nothing is refunded; the new price is charged from then.`);
61
+ }
62
+ catch (e) {
63
+ const details = e.details;
64
+ setProblem(changeRefusalWords(details));
65
+ }
66
+ }
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: () => {
43
70
  if (!window.confirm("Cancel? Your membership runs until the period ends.")) {
44
71
  return;
45
72
  }
46
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.");
47
- }, children: "Cancel membership" })), _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] }));
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] }));
48
78
  }
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { allowsWords, day, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
2
+ import { allowsWords, changeWords, day, isLive, leftWords, subscriptionStatus, } from "@composable-os/pack-memberships/client";
3
3
  import { Text } from "react-native";
4
4
  import { List } from "../native-base/list.js";
5
5
  import { Row } from "../native-base/row.js";
@@ -8,5 +8,5 @@ export function MyMembershipsScreen({ memberships, }) {
8
8
  const { data, isPending, error } = memberships.useMine();
9
9
  const subs = memberships.useMySubscriptions();
10
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)}` }, sub.id))), live.length ? _jsx(Text, { children: "Manage your membership on the gym's website." }) : null] }));
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] }));
12
12
  }
@@ -1,6 +1,6 @@
1
1
  import type { MembershipsHooks } from "@composable-os/pack-memberships/client";
2
2
  export declare function PersonHoldings({ memberships, personId, passTypes, }: {
3
- memberships: Pick<MembershipsHooks, "useHoldings" | "useGivePass" | "useVoidPass">;
3
+ memberships: Pick<MembershipsHooks, "useHoldings" | "useGivePass" | "useVoidPass" | "useSubscriptionsOf" | "usePauseSubscription" | "useUnpauseSubscription">;
4
4
  personId: string;
5
5
  /** The pass types staff may give, as the admin lists them (id and title). */
6
6
  passTypes: readonly {
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { allowsWords, day, leftWords } from "@composable-os/pack-memberships/client";
2
+ import { allowsWords, changeWords, day, 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";
@@ -9,6 +9,10 @@ export function PersonHoldings({ memberships, personId, passTypes, }) {
9
9
  const held = memberships.useHoldings(personId);
10
10
  const give = memberships.useGivePass();
11
11
  const voided = memberships.useVoidPass();
12
+ const subs = memberships.useSubscriptionsOf(personId);
13
+ const pause = memberships.usePauseSubscription();
14
+ const unpause = memberships.useUnpauseSubscription();
15
+ const [until, setUntil] = useState("");
12
16
  const [type, setType] = useState(passTypes[0]?.id ?? "");
13
17
  const [reason, setReason] = useState("");
14
18
  const [said, setSaid] = useState(null);
@@ -28,8 +32,17 @@ export function PersonHoldings({ memberships, personId, passTypes, }) {
28
32
  setProblem(e instanceof Error ? e.message : "That did not work");
29
33
  }
30
34
  }
31
- return (_jsxs("section", { className: "grid gap-4", "aria-label": "Memberships and passes", children: [held.data.holdings.map((h) => (_jsxs(Card, { "data-kind": h.kind, children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: h.title }), _jsx(CardDescription, { children: `${h.status} · ${allowsWords(h)}` })] }), _jsxs(CardContent, { className: "grid gap-2", children: [_jsx("p", { children: leftWords(h) }), h.until ? _jsx("p", { className: "text-sm", children: `Until ${day(h.until)}` }) : null, h.kind === "pass" && h.status === "active" ? (_jsx(Button, { variant: "outline", disabled: voided.isPending || reason.trim().length < 3, onClick: () => void act(() => voided.mutateAsync({ passId: h.id, reason }), "The pass is void."), children: "Void this pass" })) : null] })] }, h.id))), _jsxs("form", { className: "grid max-w-sm gap-2", onSubmit: (e) => {
35
+ return (_jsxs("section", { className: "grid gap-4", "aria-label": "Memberships and passes", children: [held.data.holdings.map((h) => (_jsxs(Card, { "data-kind": h.kind, children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: h.title }), _jsx(CardDescription, { children: `${h.status} · ${allowsWords(h)}` })] }), _jsxs(CardContent, { className: "grid gap-2", children: [_jsx("p", { children: leftWords(h) }), h.until ? _jsx("p", { className: "text-sm", children: `Until ${day(h.until)}` }) : null, h.kind === "pass" && h.status === "active" ? (_jsx(Button, { variant: "outline", disabled: voided.isPending || reason.trim().length < 3, onClick: () => void act(() => voided.mutateAsync({ passId: h.id, reason }), "The pass is void."), children: "Void this pass" })) : null] })] }, h.id))), (subs.data?.items ?? [])
36
+ .filter((s) => s.state !== "ended" && s.state !== "expired")
37
+ .map((s) => (_jsxs(Card, { "data-kind": "subscription", children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: s.planTitle }), _jsx(CardDescription, { children: subscriptionStatus(s) })] }), _jsxs(CardContent, { className: "grid gap-2", children: [changeWords(s) ? _jsx("p", { children: changeWords(s) }) : null, s.state === "paused" || s.change?.kind === "pause" ? (_jsx(Button, { variant: "outline", disabled: unpause.isPending || reason.trim().length < 3, onClick: () => void act(() => unpause.mutateAsync({ id: s.id, reason }), "Asked to end the pause. It shows here once the payment provider confirms."), children: s.state === "paused" ? "End the pause now" : "Withdraw the pause" })) : s.state === "active" ? (_jsxs("form", { className: "flex flex-wrap items-end gap-2", onSubmit: (e) => {
38
+ e.preventDefault();
39
+ void act(() => pause.mutateAsync({
40
+ id: s.id,
41
+ until: new Date(`${until}T00:00:00`).toISOString(),
42
+ reason,
43
+ }), "Asked to pause it. It shows paused once the payment provider confirms.");
44
+ }, children: [_jsxs("div", { className: "grid gap-1", children: [_jsx(Label, { htmlFor: `pause-until-${s.id}`, children: "Pause until" }), _jsx(Input, { id: `pause-until-${s.id}`, type: "date", required: true, value: until, onChange: (e) => setUntil(e.target.value) })] }), _jsx(Button, { type: "submit", variant: "outline", disabled: pause.isPending || !until || reason.trim().length < 3, children: "Pause membership" })] })) : null] })] }, s.id))), _jsxs("form", { className: "grid max-w-sm gap-2", onSubmit: (e) => {
32
45
  e.preventDefault();
33
46
  void act(() => give.mutateAsync({ personId, passTypeId: type, reason }), "The pass is given.");
34
- }, children: [_jsx(Label, { htmlFor: "give-pass-type", children: "Pass to give" }), _jsx("select", { id: "give-pass-type", className: "rounded-md border px-2 py-1", value: type, onChange: (e) => setType(e.target.value), children: passTypes.map((t) => (_jsx("option", { value: t.id, children: t.title }, t.id))) }), _jsx(Label, { htmlFor: "give-pass-reason", children: "Why (kept on the pass)" }), _jsx(Input, { id: "give-pass-reason", required: true, minLength: 3, value: reason, onChange: (e) => setReason(e.target.value) }), _jsx(Button, { type: "submit", disabled: give.isPending || !type, children: "Give pass" })] }), said ? _jsx("p", { role: "status", children: said }) : null, problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
47
+ }, children: [_jsx(Label, { htmlFor: "give-pass-type", children: "Pass to give" }), _jsx("select", { id: "give-pass-type", className: "rounded-md border px-2 py-1", value: type, onChange: (e) => setType(e.target.value), children: passTypes.map((t) => (_jsx("option", { value: t.id, children: t.title }, t.id))) }), _jsx(Label, { htmlFor: "give-pass-reason", children: "Why (kept on the pass, or the pause)" }), _jsx(Input, { id: "give-pass-reason", required: true, minLength: 3, value: reason, onChange: (e) => setReason(e.target.value) }), _jsx(Button, { type: "submit", disabled: give.isPending || !type, children: "Give pass" })] }), said ? _jsx("p", { role: "status", children: said }) : null, problem ? _jsx("p", { role: "alert", children: problem }) : null] }));
35
48
  }
@@ -29,6 +29,39 @@ export interface MembershipSubscription {
29
29
  endedAt: string | null;
30
30
  actionUrl: string | null;
31
31
  createdAt: string;
32
+ /** A plan change or a pause asked for and not over, or the pause it is in (stage 32b). */
33
+ change?: SubscriptionChange | null;
34
+ holderPersonId?: string | null;
35
+ }
36
+ /** A plan change or a pause, as the host shows it on the subscription (ADRs 0530, 0531). */
37
+ export interface SubscriptionChange {
38
+ id: string;
39
+ kind: "upgrade" | "downgrade" | "pause";
40
+ state: "requested" | "waiting" | "applied" | "lapsed" | "withdrawn";
41
+ toPlanId: string | null;
42
+ toPlanTitle: string | null;
43
+ toAmount: number | null;
44
+ pauseFrom: string | null;
45
+ pauseUntil: string | null;
46
+ effectiveAt: string | null;
47
+ requestedAt: string;
48
+ /** What came of asking the provider; `unknown`: its next event decides. */
49
+ callOutcome?: "sent" | "pending" | "unknown" | "refused" | null;
50
+ /** The provider's page to confirm an upgrade's charge (3D Secure), while it waits. */
51
+ actionUrl?: string | null;
52
+ /** What came of ending a pause early: refused or unknown, staff ask again. */
53
+ endOutcome?: "sent" | "pending" | "unknown" | "refused" | null;
54
+ }
55
+ /** What subscription.change answers. */
56
+ export interface RequestedChange {
57
+ id: string;
58
+ changeId: string;
59
+ kind: "upgrade" | "downgrade";
60
+ effectiveAt: string | null;
61
+ amount: number;
62
+ currency: string;
63
+ asked: "sent" | "pending" | "unknown" | "not_needed";
64
+ requested: true;
32
65
  }
33
66
  /** Why the host gave no free trial (subscription.start's `noTrial`). */
34
67
  export type NoTrial = "sign_in" | "used" | "permission" | "held" | "unconfirmed" | "continuation";
@@ -132,6 +165,44 @@ export type MembershipsOperations = {
132
165
  url: string;
133
166
  };
134
167
  };
168
+ "subscription.change": {
169
+ kind: "mutation";
170
+ input: {
171
+ id: string;
172
+ planId: string;
173
+ reason?: string;
174
+ };
175
+ output: RequestedChange;
176
+ };
177
+ "subscription.pause": {
178
+ kind: "mutation";
179
+ input: {
180
+ id: string;
181
+ from?: string;
182
+ until: string;
183
+ reason: string;
184
+ };
185
+ output: {
186
+ id: string;
187
+ changeId: string;
188
+ from: string | null;
189
+ until: string;
190
+ asked: "sent" | "pending" | "unknown";
191
+ requested: true;
192
+ };
193
+ };
194
+ "subscription.unpause": {
195
+ kind: "mutation";
196
+ input: {
197
+ id: string;
198
+ reason?: string;
199
+ };
200
+ output: {
201
+ id: string;
202
+ asked: "sent" | "pending" | "unknown";
203
+ requested: true;
204
+ };
205
+ };
135
206
  };
136
207
  export type MembershipsClient = PackClient<MembershipsOperations>;
137
208
  type Out<N extends keyof MembershipsOperations> = MembershipsOperations[N]["output"];
@@ -160,6 +231,18 @@ export declare function allowsWords(item: {
160
231
  export declare function leftWords(h: Holding): string;
161
232
  /** What a membership's subscription means to its payer, in words. Display only. */
162
233
  export declare function subscriptionStatus(sub: MembershipSubscription): string;
234
+ /**
235
+ * A plan change or a pause waiting, in words, from the host's record: `Changing to Unlimited once
236
+ * its charge is paid`, `Changes to One a week on 3 Dec 2026`, `Paused from 1 Dec to 21 Dec`.
237
+ * Display only: null when nothing waits.
238
+ */
239
+ export declare function changeWords(sub: MembershipSubscription): string | null;
240
+ /** Whether the payer may ask for a plan change now: active, not ending, nothing else waiting. */
241
+ export declare const canChangePlan: (sub: MembershipSubscription) => boolean;
242
+ /** What a member is told when the host refuses a plan change (its `rule`). Display only. */
243
+ export declare function changeRefusalWords(details: {
244
+ rule?: unknown;
245
+ } | undefined): string;
163
246
  /** Whether a subscription is still the payer's to cancel, resume or pay (not ended). */
164
247
  export declare const isLive: (sub: MembershipSubscription) => boolean;
165
248
  /** What a member is told when the host refuses a pass (its `rule` and `reason`). Display only. */
@@ -206,6 +289,10 @@ export declare const MEMBERSHIPS_HOOKS_CALL: {
206
289
  readonly useCancelSubscription: readonly ["subscription.cancel"];
207
290
  readonly useResumeSubscription: readonly ["subscription.resume"];
208
291
  readonly useBillingPortal: readonly ["subscription.portal"];
292
+ readonly useChangePlan: readonly ["subscription.change"];
293
+ readonly usePauseSubscription: readonly ["subscription.pause"];
294
+ readonly useUnpauseSubscription: readonly ["subscription.unpause"];
295
+ readonly useSubscriptionsOf: readonly ["subscription.list"];
209
296
  };
210
297
  /**
211
298
  * Hooks for a React or React Native app:
@@ -500,6 +587,88 @@ export declare function createMembershipsHooks<C extends ClientHolding>(react: {
500
587
  isPending: boolean;
501
588
  error: unknown;
502
589
  };
590
+ /**
591
+ * Move their own membership to another plan (web only): the host decides an upgrade (now,
592
+ * prorated, applied once paid) or a downgrade (from the next period).
593
+ */
594
+ useChangePlan(): {
595
+ mutate(input: {
596
+ id: string;
597
+ planId: string;
598
+ reason?: string;
599
+ }): void;
600
+ mutateAsync(input: {
601
+ id: string;
602
+ planId: string;
603
+ reason?: string;
604
+ }): Promise<RequestedChange>;
605
+ data: RequestedChange | undefined;
606
+ isPending: boolean;
607
+ error: unknown;
608
+ };
609
+ /** Staff (a person): pause a membership from now or a date until a date, with a reason. */
610
+ usePauseSubscription(): {
611
+ mutate(input: {
612
+ id: string;
613
+ from?: string;
614
+ until: string;
615
+ reason: string;
616
+ }): void;
617
+ mutateAsync(input: {
618
+ id: string;
619
+ from?: string;
620
+ until: string;
621
+ reason: string;
622
+ }): Promise<{
623
+ id: string;
624
+ changeId: string;
625
+ from: string | null;
626
+ until: string;
627
+ asked: "sent" | "pending" | "unknown";
628
+ requested: true;
629
+ }>;
630
+ data: {
631
+ id: string;
632
+ changeId: string;
633
+ from: string | null;
634
+ until: string;
635
+ asked: "sent" | "pending" | "unknown";
636
+ requested: true;
637
+ } | undefined;
638
+ isPending: boolean;
639
+ error: unknown;
640
+ };
641
+ /** Staff (a person): end a pause now, or withdraw one not yet started. */
642
+ useUnpauseSubscription(): {
643
+ mutate(input: {
644
+ id: string;
645
+ reason?: string;
646
+ }): void;
647
+ mutateAsync(input: {
648
+ id: string;
649
+ reason?: string;
650
+ }): Promise<{
651
+ id: string;
652
+ asked: "sent" | "pending" | "unknown";
653
+ requested: true;
654
+ }>;
655
+ data: {
656
+ id: string;
657
+ asked: "sent" | "pending" | "unknown";
658
+ requested: true;
659
+ } | undefined;
660
+ isPending: boolean;
661
+ error: unknown;
662
+ };
663
+ /** Staff: the membership subscriptions one person holds. */
664
+ useSubscriptionsOf(personId: string): {
665
+ data: {
666
+ items: MembershipSubscription[];
667
+ nextCursor: string | null;
668
+ } | undefined;
669
+ isPending: boolean;
670
+ error: unknown;
671
+ };
503
672
  }, {
504
673
  readonly usePlans: readonly ["x.memberships.plans"];
505
674
  readonly usePassTypes: readonly ["x.memberships.passTypes"];
@@ -513,6 +682,10 @@ export declare function createMembershipsHooks<C extends ClientHolding>(react: {
513
682
  readonly useCancelSubscription: readonly ["subscription.cancel"];
514
683
  readonly useResumeSubscription: readonly ["subscription.resume"];
515
684
  readonly useBillingPortal: readonly ["subscription.portal"];
685
+ readonly useChangePlan: readonly ["subscription.change"];
686
+ readonly usePauseSubscription: readonly ["subscription.pause"];
687
+ readonly useUnpauseSubscription: readonly ["subscription.unpause"];
688
+ readonly useSubscriptionsOf: readonly ["subscription.list"];
516
689
  }, import("@composable-os/client").OperationsOf<C>>;
517
690
  declare function allMembershipsHooks(react: {
518
691
  useQuery: UseQuery;
@@ -802,6 +975,88 @@ declare function allMembershipsHooks(react: {
802
975
  isPending: boolean;
803
976
  error: unknown;
804
977
  };
978
+ /**
979
+ * Move their own membership to another plan (web only): the host decides an upgrade (now,
980
+ * prorated, applied once paid) or a downgrade (from the next period).
981
+ */
982
+ useChangePlan(): {
983
+ mutate(input: {
984
+ id: string;
985
+ planId: string;
986
+ reason?: string;
987
+ }): void;
988
+ mutateAsync(input: {
989
+ id: string;
990
+ planId: string;
991
+ reason?: string;
992
+ }): Promise<RequestedChange>;
993
+ data: RequestedChange | undefined;
994
+ isPending: boolean;
995
+ error: unknown;
996
+ };
997
+ /** Staff (a person): pause a membership from now or a date until a date, with a reason. */
998
+ usePauseSubscription(): {
999
+ mutate(input: {
1000
+ id: string;
1001
+ from?: string;
1002
+ until: string;
1003
+ reason: string;
1004
+ }): void;
1005
+ mutateAsync(input: {
1006
+ id: string;
1007
+ from?: string;
1008
+ until: string;
1009
+ reason: string;
1010
+ }): Promise<{
1011
+ id: string;
1012
+ changeId: string;
1013
+ from: string | null;
1014
+ until: string;
1015
+ asked: "sent" | "pending" | "unknown";
1016
+ requested: true;
1017
+ }>;
1018
+ data: {
1019
+ id: string;
1020
+ changeId: string;
1021
+ from: string | null;
1022
+ until: string;
1023
+ asked: "sent" | "pending" | "unknown";
1024
+ requested: true;
1025
+ } | undefined;
1026
+ isPending: boolean;
1027
+ error: unknown;
1028
+ };
1029
+ /** Staff (a person): end a pause now, or withdraw one not yet started. */
1030
+ useUnpauseSubscription(): {
1031
+ mutate(input: {
1032
+ id: string;
1033
+ reason?: string;
1034
+ }): void;
1035
+ mutateAsync(input: {
1036
+ id: string;
1037
+ reason?: string;
1038
+ }): Promise<{
1039
+ id: string;
1040
+ asked: "sent" | "pending" | "unknown";
1041
+ requested: true;
1042
+ }>;
1043
+ data: {
1044
+ id: string;
1045
+ asked: "sent" | "pending" | "unknown";
1046
+ requested: true;
1047
+ } | undefined;
1048
+ isPending: boolean;
1049
+ error: unknown;
1050
+ };
1051
+ /** Staff: the membership subscriptions one person holds. */
1052
+ useSubscriptionsOf(personId: string): {
1053
+ data: {
1054
+ items: MembershipSubscription[];
1055
+ nextCursor: string | null;
1056
+ } | undefined;
1057
+ isPending: boolean;
1058
+ error: unknown;
1059
+ };
805
1060
  };
806
1061
  /** Every hook of this entry. A block takes the ones it calls: `Pick<MembershipsHooks, "useMine">`. */
807
1062
  export type MembershipsHooks = ReturnType<typeof allMembershipsHooks>;
@@ -4,8 +4,9 @@
4
4
  //
5
5
  // Nothing here decides a price, a trial, whether an intro offer may be bought, or how many classes
6
6
  // are left: the host does (`sellable`, the one-trial rule, `onePerPerson`, `allowance.get`). The
7
- // billing actions (subscribe, cancel, resume, the provider's portal, buying a pass) are the web's;
8
- // a native block reads only (the block lint).
7
+ // billing actions (subscribe, cancel, resume, change plan, the provider's portal, buying a pass)
8
+ // are the web's; a native block reads only (the block lint). Pausing is staff's (decision 10).
9
+ // Whether a change is an upgrade (now, prorated) or a downgrade (next period) is the host's.
9
10
  import { packHooks } from "@composable-os/client";
10
11
  export const PLAN = "memberships.plan";
11
12
  export const MEMBERSHIP = "memberships.membership";
@@ -92,7 +93,9 @@ export function subscriptionStatus(sub) {
92
93
  case "unpaid":
93
94
  return "Unpaid: update your card to keep booking";
94
95
  case "paused":
95
- return "Paused";
96
+ return sub.change?.kind === "pause" && sub.change.pauseUntil
97
+ ? `Paused until ${day(sub.change.pauseUntil)}: nothing is charged meanwhile`
98
+ : "Paused";
96
99
  case "incomplete":
97
100
  return "Waiting for its first payment";
98
101
  case "expired":
@@ -101,6 +104,55 @@ export function subscriptionStatus(sub) {
101
104
  return `Ended${sub.endedAt ? ` on ${day(sub.endedAt)}` : ""}`;
102
105
  }
103
106
  }
107
+ /**
108
+ * A plan change or a pause waiting, in words, from the host's record: `Changing to Unlimited once
109
+ * its charge is paid`, `Changes to One a week on 3 Dec 2026`, `Paused from 1 Dec to 21 Dec`.
110
+ * Display only: null when nothing waits.
111
+ */
112
+ export function changeWords(sub) {
113
+ const c = sub.change;
114
+ if (!c)
115
+ return null;
116
+ if (c.kind === "pause") {
117
+ if (c.endOutcome === "refused" || c.endOutcome === "unknown") {
118
+ return "Ending the pause did not finish: ask again";
119
+ }
120
+ if (c.state === "applied")
121
+ return null;
122
+ return `Pause asked: ${c.pauseFrom ? `from ${day(c.pauseFrom)}` : "from now"} until ${day(c.pauseUntil)}`;
123
+ }
124
+ if (c.state === "lapsed")
125
+ return `The change to ${c.toPlanTitle} was not paid, so it did not happen`;
126
+ if (c.endOutcome === "refused" || c.endOutcome === "unknown") {
127
+ return `Withdrawing the change to ${c.toPlanTitle} did not finish: staff are asking again`;
128
+ }
129
+ if (c.kind === "upgrade") {
130
+ return c.actionUrl
131
+ ? `Changing to ${c.toPlanTitle}: confirm its payment to finish`
132
+ : `Changing to ${c.toPlanTitle} once its charge is paid`;
133
+ }
134
+ return `Changes to ${c.toPlanTitle} on ${day(c.effectiveAt)}`;
135
+ }
136
+ /** Whether the payer may ask for a plan change now: active, not ending, nothing else waiting. */
137
+ export const canChangePlan = (sub) => sub.state === "active" &&
138
+ !sub.cancelAtPeriodEnd &&
139
+ sub.cancelAt === null &&
140
+ (!sub.change || sub.change.state === "lapsed" || sub.change.state === "applied");
141
+ /** What a member is told when the host refuses a plan change (its `rule`). Display only. */
142
+ export function changeRefusalWords(details) {
143
+ switch (details?.rule) {
144
+ case "change_open":
145
+ return "A change is already waiting on your membership.";
146
+ case "ending":
147
+ return "Your membership is set to end: keep it going first.";
148
+ case "state":
149
+ return "Your membership cannot be changed just now.";
150
+ case "same_plan":
151
+ return "That is the plan you are on.";
152
+ default:
153
+ return "We could not change your plan.";
154
+ }
155
+ }
104
156
  /** Whether a subscription is still the payer's to cancel, resume or pay (not ended). */
105
157
  export const isLive = (sub) => sub.state !== "ended" && sub.state !== "expired";
106
158
  /** What a member is told when the host refuses a pass (its `rule` and `reason`). Display only. */
@@ -142,6 +194,12 @@ export const MEMBERSHIPS_HOOKS_CALL = {
142
194
  useCancelSubscription: ["subscription.cancel"],
143
195
  useResumeSubscription: ["subscription.resume"],
144
196
  useBillingPortal: ["subscription.portal"],
197
+ // Stage 32b (ADRs 0530, 0531): a member's plan change (web only); staff pause and end a pause,
198
+ // and read a person's membership subscriptions.
199
+ useChangePlan: ["subscription.change"],
200
+ usePauseSubscription: ["subscription.pause"],
201
+ useUnpauseSubscription: ["subscription.unpause"],
202
+ useSubscriptionsOf: ["subscription.list"],
145
203
  };
146
204
  /**
147
205
  * Hooks for a React or React Native app:
@@ -208,5 +266,32 @@ function allMembershipsHooks(react, api) {
208
266
  useBillingPortal() {
209
267
  return useMutation(api.mutation("subscription.portal"));
210
268
  },
269
+ /**
270
+ * Move their own membership to another plan (web only): the host decides an upgrade (now,
271
+ * prorated, applied once paid) or a downgrade (from the next period).
272
+ */
273
+ useChangePlan() {
274
+ return useMutation(api.mutation("subscription.change"));
275
+ },
276
+ /** Staff (a person): pause a membership from now or a date until a date, with a reason. */
277
+ usePauseSubscription() {
278
+ return useMutation(api.mutation("subscription.pause"));
279
+ },
280
+ /** Staff (a person): end a pause now, or withdraw one not yet started. */
281
+ useUnpauseSubscription() {
282
+ return useMutation(api.mutation("subscription.unpause"));
283
+ },
284
+ /** Staff: the membership subscriptions one person holds. */
285
+ useSubscriptionsOf(personId) {
286
+ return useQuery(api.query("subscription.list", {
287
+ filter: {
288
+ and: [
289
+ { field: "planObject", op: "eq", value: PLAN },
290
+ { field: "holderPersonId", op: "eq", value: personId },
291
+ ],
292
+ },
293
+ limit: 20,
294
+ }));
295
+ },
211
296
  };
212
297
  }
@@ -0,0 +1,5 @@
1
+ import type { DashboardDeclaration } from "@composable-os/sdk";
2
+ export declare const memberships: DashboardDeclaration;
3
+ export declare const membershipsDashboards: {
4
+ memberships: DashboardDeclaration;
5
+ };
@@ -0,0 +1,165 @@
1
+ const PLAN = "'memberships.plan'";
2
+ const IN = (column) => `${column} >= :dates_from AND ${column} < :dates_to`;
3
+ const WEEK = (column) => `date(${column}, '-' || ((strftime('%w', ${column}) + 6) % 7) || ' days')`;
4
+ const MEMBERS = (states) => `SELECT count(*) AS value FROM rec_x_memberships_membership m WHERE m.status IN (${states})`;
5
+ const statusIs = (values) => ({
6
+ object: "memberships.membership",
7
+ filter: { field: "status", op: "in", value: values },
8
+ });
9
+ export const memberships = {
10
+ title: "Memberships",
11
+ description: "Members now (active, on trial, paused, failing), trials that became paid, cancellations by " +
12
+ "month and reason, recurring revenue by month net of tax, and classes taken per week.",
13
+ filters: [{ type: "dateRange", id: "dates", label: "Dates", default: "this_quarter" }],
14
+ widgets: [
15
+ {
16
+ id: "active",
17
+ type: "kpi",
18
+ title: "Active members",
19
+ description: "Memberships active now (paid up), whatever the dates.",
20
+ sql: MEMBERS("'active'"),
21
+ mapping: { value: "value" },
22
+ options: { compare: false },
23
+ clickThrough: statusIs(["active"]),
24
+ layout: { w: 3, h: 1 },
25
+ },
26
+ {
27
+ id: "trialing",
28
+ type: "kpi",
29
+ title: "On trial",
30
+ description: "Memberships on their free trial now.",
31
+ sql: MEMBERS("'trialing'"),
32
+ mapping: { value: "value" },
33
+ options: { compare: false },
34
+ clickThrough: statusIs(["trialing"]),
35
+ layout: { w: 3, h: 1 },
36
+ },
37
+ {
38
+ id: "paused",
39
+ type: "kpi",
40
+ title: "Paused",
41
+ description: "Memberships paused by staff now: nothing charged, no classes.",
42
+ sql: MEMBERS("'paused'"),
43
+ mapping: { value: "value" },
44
+ options: { compare: false },
45
+ clickThrough: statusIs(["paused"]),
46
+ layout: { w: 3, h: 1 },
47
+ },
48
+ {
49
+ id: "failing",
50
+ type: "kpi",
51
+ title: "Payments failing",
52
+ description: "Memberships whose renewal failed: past due while the provider retries, or unpaid.",
53
+ sql: MEMBERS("'past_due', 'unpaid'"),
54
+ mapping: { value: "value" },
55
+ options: { compare: false },
56
+ clickThrough: statusIs(["past_due", "unpaid"]),
57
+ layout: { w: 3, h: 1 },
58
+ },
59
+ {
60
+ id: "trials-ended",
61
+ type: "kpi",
62
+ title: "Trials ended",
63
+ description: "Membership trials that ended in the period.",
64
+ sql: `SELECT count(*) AS value FROM rec_subscription s
65
+ WHERE s.plan_object = ${PLAN} AND s.trial_end IS NOT NULL AND s.trial_end <= :now
66
+ AND ${IN("s.trial_end")}`,
67
+ mapping: { value: "value" },
68
+ options: { compare: true },
69
+ layout: { w: 3, h: 1 },
70
+ },
71
+ {
72
+ id: "trials-paid",
73
+ type: "kpi",
74
+ title: "Trials that became paid",
75
+ description: "Of the trials that ended in the period, those with a paid period after the trial.",
76
+ sql: `SELECT count(*) AS value FROM rec_subscription s
77
+ WHERE s.plan_object = ${PLAN} AND s.trial_end IS NOT NULL AND s.trial_end <= :now
78
+ AND ${IN("s.trial_end")} AND EXISTS (
79
+ SELECT 1 FROM rec_order o WHERE o.subscription_id = s.id
80
+ AND o.state IN ('paid', 'part_paid', 'refunded') AND o.period_start >= s.trial_end)`,
81
+ mapping: { value: "value" },
82
+ options: { compare: true },
83
+ layout: { w: 3, h: 1 },
84
+ },
85
+ {
86
+ id: "revenue",
87
+ type: "kpi",
88
+ title: "Recurring revenue, net of tax",
89
+ description: "What membership periods paid in the period brought in, less refunds and the tax inside it.",
90
+ sql: `SELECT coalesce(sum(o.net), 0) / 100.0 AS value FROM rec_order o
91
+ JOIN rec_subscription s ON s.id = o.subscription_id
92
+ WHERE s.plan_object = ${PLAN} AND o.state IN ('paid', 'part_paid', 'refunded') AND ${IN("o.paid_at")}`,
93
+ mapping: { value: "value" },
94
+ options: { compare: true, format: "currency" },
95
+ layout: { w: 3, h: 1 },
96
+ },
97
+ {
98
+ id: "uses",
99
+ type: "kpi",
100
+ title: "Classes taken",
101
+ description: "Uses of memberships and passes for classes in the period, not given back.",
102
+ sql: `SELECT count(*) AS value FROM rec_allowance_use u
103
+ WHERE u.object_type IN ('memberships.membership', 'memberships.pass') AND u.returned_at IS NULL
104
+ AND ${IN("u.at")}`,
105
+ mapping: { value: "value" },
106
+ options: { compare: true },
107
+ layout: { w: 3, h: 1 },
108
+ },
109
+ {
110
+ id: "revenue-by-month",
111
+ type: "bar",
112
+ title: "Recurring revenue by month, net of tax",
113
+ description: "Membership periods paid per month, less refunds and tax.",
114
+ sql: `SELECT substr(o.paid_at, 1, 7) AS month, sum(o.net) / 100.0 AS revenue FROM rec_order o
115
+ JOIN rec_subscription s ON s.id = o.subscription_id
116
+ WHERE s.plan_object = ${PLAN} AND o.state IN ('paid', 'part_paid', 'refunded') AND ${IN("o.paid_at")}
117
+ GROUP BY month ORDER BY month`,
118
+ mapping: { x: "month", y: ["revenue"] },
119
+ layout: { w: 6, h: 2 },
120
+ },
121
+ {
122
+ id: "cancellations-by-month",
123
+ type: "bar",
124
+ title: "Cancellations by month",
125
+ description: "Memberships cancelled per month, by the provider's reason: asked for (by the member or " +
126
+ "staff) or payments failed.",
127
+ sql: `SELECT substr(s.canceled_at, 1, 7) AS month,
128
+ CASE coalesce(s.end_reason, '') WHEN 'payment_failed' THEN 'Payments failed'
129
+ WHEN 'cancellation_requested' THEN 'Asked for' ELSE 'Other' END AS reason,
130
+ count(*) AS cancelled
131
+ FROM rec_subscription s WHERE s.plan_object = ${PLAN} AND s.canceled_at IS NOT NULL
132
+ AND ${IN("s.canceled_at")} GROUP BY month, reason ORDER BY month, reason`,
133
+ mapping: { x: "month", y: ["cancelled"], series: "reason" },
134
+ layout: { w: 6, h: 2 },
135
+ },
136
+ {
137
+ id: "uses-by-week",
138
+ type: "line",
139
+ title: "Classes taken by week",
140
+ description: "Uses of memberships and passes per week of the classes, not given back.",
141
+ sql: `SELECT ${WEEK("u.at")} AS week, count(*) AS uses FROM rec_allowance_use u
142
+ WHERE u.object_type IN ('memberships.membership', 'memberships.pass') AND u.returned_at IS NULL
143
+ AND ${IN("u.at")} GROUP BY week ORDER BY week`,
144
+ mapping: { x: "week", y: ["uses"] },
145
+ layout: { w: 6, h: 2 },
146
+ },
147
+ {
148
+ id: "failing-members",
149
+ type: "table",
150
+ title: "Failing payments",
151
+ description: "Memberships past due or unpaid, the longest failing first.",
152
+ sql: `SELECT m.id AS id, p.display_name AS member, m.title AS plan, m.status AS status,
153
+ m.until AS until
154
+ FROM rec_x_memberships_membership m JOIN rec_person p ON p.id = m.person
155
+ WHERE m.status IN ('past_due', 'unpaid') ORDER BY m.until, member LIMIT 50`,
156
+ mapping: { columns: ["member", "plan", "status", "until"] },
157
+ clickThrough: {
158
+ object: "memberships.membership",
159
+ filter: { field: "id", op: "eq", value: { $row: "id" } },
160
+ },
161
+ layout: { w: 6, h: 2 },
162
+ },
163
+ ],
164
+ };
165
+ export const membershipsDashboards = { memberships };
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ declare const _default: import("@composable-os/sdk").Extension<{
7
7
  readonly requires: readonly ["programs"];
8
8
  readonly permissions: {
9
9
  readonly read: ["person", "programs.classtype"];
10
- readonly operations: ["public.list", "public.get", "my.list", "my.get", "record.create", "record.update", "record.get", "record.list", "allowance.get", "allowance.list", "order.start"];
10
+ readonly operations: ["public.list", "public.get", "my.list", "my.get", "record.create", "record.update", "record.get", "record.list", "allowance.get", "allowance.list", "order.start", "me.family"];
11
11
  readonly modules: ["ops"];
12
12
  };
13
13
  readonly objects: {
@@ -28,6 +28,22 @@ declare const _default: import("@composable-os/sdk").Extension<{
28
28
  readonly step: 1;
29
29
  readonly description: "Empty or 0: charged from the start. A person gets one trial on any plan.";
30
30
  };
31
+ readonly pauseMinDays: {
32
+ readonly type: "number";
33
+ readonly label: "Shortest pause (days)";
34
+ readonly min: 1;
35
+ readonly max: 366;
36
+ readonly step: 1;
37
+ readonly description: "Staff pause a membership for at least this long. Empty: 1 day.";
38
+ };
39
+ readonly pauseMaxDays: {
40
+ readonly type: "number";
41
+ readonly label: "Longest pause (days)";
42
+ readonly min: 1;
43
+ readonly max: 366;
44
+ readonly step: 1;
45
+ readonly description: "And at most this long. Empty: a year.";
46
+ };
31
47
  readonly status: {
32
48
  readonly type: "select";
33
49
  readonly label: "Status";
@@ -129,6 +145,10 @@ declare const _default: import("@composable-os/sdk").Extension<{
129
145
  readonly recurring: {
130
146
  readonly interval: "month";
131
147
  readonly trialDays: "trialDays";
148
+ readonly pause: {
149
+ readonly minDays: "pauseMinDays";
150
+ readonly maxDays: "pauseMaxDays";
151
+ };
132
152
  readonly grants: {
133
153
  readonly object: "membership";
134
154
  readonly set: {
@@ -301,7 +321,8 @@ declare const _default: import("@composable-os/sdk").Extension<{
301
321
  };
302
322
  readonly customer: {
303
323
  readonly field: "person";
304
- readonly read: readonly ["title", "plan", "uses", "per", "classTypes", "weekdays", "fromMinute", "untilMinute", "from", "until", "status"];
324
+ readonly guardians: {};
325
+ readonly read: readonly ["person", "title", "plan", "uses", "per", "classTypes", "weekdays", "fromMinute", "untilMinute", "from", "until", "status"];
305
326
  readonly write: readonly [];
306
327
  };
307
328
  readonly allowance: {
@@ -594,7 +615,8 @@ declare const _default: import("@composable-os/sdk").Extension<{
594
615
  };
595
616
  readonly customer: {
596
617
  readonly field: "person";
597
- readonly read: readonly ["title", "passtype", "uses", "classTypes", "weekdays", "fromMinute", "untilMinute", "from", "until", "source", "status"];
618
+ readonly guardians: {};
619
+ readonly read: readonly ["person", "title", "passtype", "uses", "classTypes", "weekdays", "fromMinute", "untilMinute", "from", "until", "source", "status"];
598
620
  readonly write: readonly [];
599
621
  };
600
622
  readonly allowance: {
@@ -673,6 +695,20 @@ declare const _default: import("@composable-os/sdk").Extension<{
673
695
  };
674
696
  readonly columns: ["person", "title", "payer", "until"];
675
697
  };
698
+ readonly paused: {
699
+ readonly label: "Paused";
700
+ readonly object: "memberships.membership";
701
+ readonly filter: {
702
+ readonly field: "status";
703
+ readonly op: "eq";
704
+ readonly value: "paused";
705
+ };
706
+ readonly sort: {
707
+ readonly field: "from";
708
+ readonly direction: "desc";
709
+ };
710
+ readonly columns: ["person", "title", "payer", "from"];
711
+ };
676
712
  readonly endingThisMonth: {
677
713
  readonly label: "Ending this month";
678
714
  readonly object: "memberships.membership";
@@ -697,6 +733,34 @@ declare const _default: import("@composable-os/sdk").Extension<{
697
733
  };
698
734
  readonly columns: ["person", "title", "status", "until"];
699
735
  };
736
+ readonly passesExpiringThisWeek: {
737
+ readonly label: "Passes expiring this week";
738
+ readonly object: "memberships.pass";
739
+ readonly filter: {
740
+ readonly and: [{
741
+ readonly field: "status";
742
+ readonly op: "eq";
743
+ readonly value: "active";
744
+ }, {
745
+ readonly field: "until";
746
+ readonly op: "gte";
747
+ readonly value: {
748
+ readonly $relative: "now";
749
+ };
750
+ }, {
751
+ readonly field: "until";
752
+ readonly op: "lt";
753
+ readonly value: {
754
+ readonly $relative: "startOfNextWeek";
755
+ };
756
+ }];
757
+ };
758
+ readonly sort: {
759
+ readonly field: "until";
760
+ readonly direction: "asc";
761
+ };
762
+ readonly columns: ["person", "title", "uses", "until"];
763
+ };
700
764
  readonly passesExpiringThisMonth: {
701
765
  readonly label: "Passes expiring this month";
702
766
  readonly object: "memberships.pass";
@@ -807,7 +871,9 @@ declare const _default: import("@composable-os/sdk").Extension<{
807
871
  total: import("zod").ZodNumber;
808
872
  token: import("zod").ZodNullable<import("zod").ZodString>;
809
873
  }, import("zod/v4/core").$strip>>;
810
- readonly mine: import("@composable-os/sdk").ToolSpec<import("zod").ZodObject<{}, import("zod/v4/core").$strip>, import("zod").ZodObject<{
874
+ readonly mine: import("@composable-os/sdk").ToolSpec<import("zod").ZodObject<{
875
+ personId: import("zod").ZodOptional<import("zod").ZodString>;
876
+ }, import("zod/v4/core").$strip>, import("zod").ZodObject<{
811
877
  holdings: import("zod").ZodArray<import("zod").ZodObject<{
812
878
  classTypes: import("zod").ZodArray<import("zod").ZodString>;
813
879
  weekdays: import("zod").ZodArray<import("zod").ZodString>;
@@ -890,5 +956,8 @@ declare const _default: import("@composable-os/sdk").Extension<{
890
956
  source: import("zod").ZodString;
891
957
  }, import("zod/v4/core").$strip>>;
892
958
  };
959
+ readonly dashboards: {
960
+ memberships: import("@composable-os/sdk").DashboardDeclaration;
961
+ };
893
962
  }>;
894
963
  export default _default;
package/dist/index.js CHANGED
@@ -16,10 +16,16 @@
16
16
  // - a membership and a pass hold an `allowance` (ADRs 0493, 0494): uses per week, month or in
17
17
  // all, the class types, weekdays and times of day they pay for, spent by a booking of their own
18
18
  // Person, refused past the limit by the database for every actor;
19
+ // - a member changes plan on the web (an upgrade now, prorated, applied once paid; a downgrade from
20
+ // the next period) and staff pause a membership for a set time within the plan's bounds
21
+ // (`recurring.pause`): the host's `subscription.change` and `subscription.pause`, asked of the
22
+ // provider, followed from its verified events (ADRs 0530, 0531). The membership's terms follow
23
+ // the plan when the change takes effect; while paused it gives and spends nothing;
19
24
  // - every term of a membership or a pass is read-only: only the host (and this pack's own staff
20
25
  // tools, which a person calls) writes it, never a caller of the generic record operations.
21
26
  // The tools in tools.ts compose the host's operations and hold no rule of their own.
22
27
  import { defineExtension } from "@composable-os/sdk";
28
+ import { membershipsDashboards } from "./dashboards.js";
23
29
  import { buy, givePass, holdings, mine, passTypes, plans, voidPass } from "./tools.js";
24
30
  /** Weekdays as the host's local time numbers them (ISO: 1 is Monday), for an off-peak limit. */
25
31
  const WEEKDAYS = [
@@ -122,6 +128,8 @@ export default defineExtension({
122
128
  "allowance.get",
123
129
  "allowance.list",
124
130
  "order.start",
131
+ // The member's own id and the children staff linked to them (ADR 0540).
132
+ "me.family",
125
133
  ],
126
134
  modules: ["ops"],
127
135
  },
@@ -171,6 +179,22 @@ export default defineExtension({
171
179
  step: 1,
172
180
  description: "Empty or 0: charged from the start. A person gets one trial on any plan.",
173
181
  },
182
+ pauseMinDays: {
183
+ type: "number",
184
+ label: "Shortest pause (days)",
185
+ min: 1,
186
+ max: 366,
187
+ step: 1,
188
+ description: "Staff pause a membership for at least this long. Empty: 1 day.",
189
+ },
190
+ pauseMaxDays: {
191
+ type: "number",
192
+ label: "Longest pause (days)",
193
+ min: 1,
194
+ max: 366,
195
+ step: 1,
196
+ description: "And at most this long. Empty: a year.",
197
+ },
174
198
  status: { type: "select", label: "Status", default: "draft", options: ON_SALE },
175
199
  },
176
200
  public: {
@@ -198,6 +222,9 @@ export default defineExtension({
198
222
  recurring: {
199
223
  interval: "month",
200
224
  trialDays: "trialDays",
225
+ // Staff pause a membership for a set time (decision 10, ADR 0531): nothing charged, no
226
+ // classes, until the provider resumes it on its date.
227
+ pause: { minDays: "pauseMinDays", maxDays: "pauseMaxDays" },
201
228
  // What a subscription to it gives its holder, kept in step by the host (ADR 0510).
202
229
  grants: {
203
230
  object: "membership",
@@ -283,9 +310,13 @@ export default defineExtension({
283
310
  },
284
311
  },
285
312
  states: { field: "status", initial: "active", moves: followMoves },
313
+ // A member reads their own; a parent or guardian staff linked to a child reads the child's
314
+ // too, read only (ADR 0540): what the child has left to book with.
286
315
  customer: {
287
316
  field: "person",
317
+ guardians: {},
288
318
  read: [
319
+ "person",
289
320
  "title",
290
321
  "plan",
291
322
  "uses",
@@ -446,9 +477,12 @@ export default defineExtension({
446
477
  { from: "active", to: "void", by: ["host"], tools: ["voidPass"], final: true },
447
478
  ],
448
479
  },
480
+ // As a membership: their own, and a linked child's for a guardian, read only (ADR 0540).
449
481
  customer: {
450
482
  field: "person",
483
+ guardians: {},
451
484
  read: [
485
+ "person",
452
486
  "title",
453
487
  "passtype",
454
488
  "uses",
@@ -500,6 +534,13 @@ export default defineExtension({
500
534
  sort: { field: "until", direction: "asc" },
501
535
  columns: ["person", "title", "payer", "until"],
502
536
  },
537
+ paused: {
538
+ label: "Paused",
539
+ object: "memberships.membership",
540
+ filter: { field: "status", op: "eq", value: "paused" },
541
+ sort: { field: "from", direction: "desc" },
542
+ columns: ["person", "title", "payer", "from"],
543
+ },
503
544
  endingThisMonth: {
504
545
  label: "Ending this month",
505
546
  object: "memberships.membership",
@@ -512,6 +553,19 @@ export default defineExtension({
512
553
  sort: { field: "until", direction: "asc" },
513
554
  columns: ["person", "title", "status", "until"],
514
555
  },
556
+ passesExpiringThisWeek: {
557
+ label: "Passes expiring this week",
558
+ object: "memberships.pass",
559
+ filter: {
560
+ and: [
561
+ { field: "status", op: "eq", value: "active" },
562
+ { field: "until", op: "gte", value: { $relative: "now" } },
563
+ { field: "until", op: "lt", value: { $relative: "startOfNextWeek" } },
564
+ ],
565
+ },
566
+ sort: { field: "until", direction: "asc" },
567
+ columns: ["person", "title", "uses", "until"],
568
+ },
515
569
  passesExpiringThisMonth: {
516
570
  label: "Passes expiring this month",
517
571
  object: "memberships.pass",
@@ -556,4 +610,5 @@ export default defineExtension({
556
610
  // and members hold and a human admin may grant to anyone else (ADR 0449).
557
611
  grantable: ["memberships:passes"],
558
612
  tools: { plans, passTypes, buy, mine, holdings, givePass, voidPass },
613
+ dashboards: membershipsDashboards,
559
614
  });
package/dist/tools.d.ts CHANGED
@@ -50,7 +50,9 @@ export declare const buy: import("@composable-os/sdk").ToolSpec<z.ZodObject<{
50
50
  total: z.ZodNumber;
51
51
  token: z.ZodNullable<z.ZodString>;
52
52
  }, z.core.$strip>>;
53
- export declare const mine: import("@composable-os/sdk").ToolSpec<z.ZodObject<{}, z.core.$strip>, z.ZodObject<{
53
+ export declare const mine: import("@composable-os/sdk").ToolSpec<z.ZodObject<{
54
+ personId: z.ZodOptional<z.ZodString>;
55
+ }, z.core.$strip>, z.ZodObject<{
54
56
  holdings: z.ZodArray<z.ZodObject<{
55
57
  classTypes: z.ZodArray<z.ZodString>;
56
58
  weekdays: z.ZodArray<z.ZodString>;
package/dist/tools.js CHANGED
@@ -232,13 +232,19 @@ export const mine = defineTool({
232
232
  description: "The signed-in member's own memberships and passes: each one's title, state, what it allows " +
233
233
  "(classes per week or month, or in all; class types, days and times), when it started and " +
234
234
  "when it stops or expires, and the host's count for now: classes used and left this week, " +
235
- "this month or in all (left null: unlimited). Read-only.",
236
- input: z.object({}),
235
+ "this month or in all (left null: unlimited). With personId, a child's the gym linked to " +
236
+ "them instead (their parent or guardian reads what the child has left). Read-only.",
237
+ input: z.object({
238
+ personId: id.optional().describe("A child linked to them; left out, their own"),
239
+ }),
237
240
  output: z.object({ holdings: z.array(holding) }),
238
241
  risk: "read",
239
242
  audiences: ["customer"],
240
- async handler(_input, ctx) {
241
- return { holdings: await holdingsOf(ctx, "my.list", null) };
243
+ async handler(input, ctx) {
244
+ // The seam gives them their own and a linked child's (ADR 0540); the filter picks whose.
245
+ const whose = input.personId ??
246
+ (await ctx.ops.call("me.family", {})).self.personId;
247
+ return { holdings: await holdingsOf(ctx, "my.list", whose) };
242
248
  },
243
249
  });
244
250
  export const holdings = defineTool({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@composable-os/pack-memberships",
3
- "version": "0.1.0-beta.10",
3
+ "version": "0.1.0-beta.11",
4
4
  "license": "FSL-1.1-ALv2",
5
5
  "type": "module",
6
6
  "repository": {
@@ -32,7 +32,7 @@
32
32
  "description": "Membership plans paid every month and class passes bought once, with what each allows and what is left. Requires Programs."
33
33
  },
34
34
  "dependencies": {
35
- "@composable-os/client": "0.1.0-beta.10",
36
- "@composable-os/sdk": "0.1.0-beta.10"
35
+ "@composable-os/client": "0.1.0-beta.11",
36
+ "@composable-os/sdk": "0.1.0-beta.11"
37
37
  }
38
38
  }