@composable-os/pack-memberships 0.0.0-stage → 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.
@@ -0,0 +1,297 @@
1
+ // The Memberships pack's headless entry (stage 32b; ADRs 0418 and 0453): functions and hooks over
2
+ // the typed client, no markup. A client app imports it as `@composable-os/pack-memberships/client`
3
+ // and hands it its generated client; the memberships blocks render what it returns.
4
+ //
5
+ // Nothing here decides a price, a trial, whether an intro offer may be bought, or how many classes
6
+ // are left: the host does (`sellable`, the one-trial rule, `onePerPerson`, `allowance.get`). The
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.
10
+ import { packHooks } from "@composable-os/client";
11
+ export const PLAN = "memberships.plan";
12
+ export const MEMBERSHIP = "memberships.membership";
13
+ export const PASS = "memberships.pass";
14
+ // --- Display only ---------------------------------------------------------------------------------
15
+ /** A price as the host gave it, in its currency (`99.00 AUD`). Display only: never worked out. */
16
+ export function formatPrice(price, currency) {
17
+ if (price === null || price === undefined)
18
+ return "";
19
+ try {
20
+ return currency
21
+ ? new Intl.NumberFormat(undefined, { style: "currency", currency }).format(price)
22
+ : String(price);
23
+ }
24
+ catch {
25
+ return `${price}${currency ? ` ${currency}` : ""}`;
26
+ }
27
+ }
28
+ /** A date as a reader sees it (`3 Dec 2026`), from the host's ISO timestamp. Display only. */
29
+ export function day(iso) {
30
+ if (!iso)
31
+ return "";
32
+ const at = new Date(iso);
33
+ return Number.isNaN(at.getTime())
34
+ ? ""
35
+ : at.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
36
+ }
37
+ const clock = (minute) => `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(minute % 60).padStart(2, "0")}`;
38
+ const DAY_NAMES = ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
39
+ /** What a plan or pass allows, in words: `3 classes a week · Mon, Wed · 09:00 to 16:00`. */
40
+ export function allowsWords(item) {
41
+ const per = item.per === "month" ? " a month" : item.per === "week" ? " a week" : "";
42
+ const count = item.uses === null
43
+ ? "Unlimited classes"
44
+ : `${item.uses} ${item.uses === 1 ? "class" : "classes"}${per}`;
45
+ const days = item.weekdays.length
46
+ ? item.weekdays.map((d) => DAY_NAMES[Number(d)] ?? d).join(", ")
47
+ : "";
48
+ const times = item.fromMinute !== null || item.untilMinute !== null
49
+ ? `${item.fromMinute !== null ? `from ${clock(item.fromMinute)}` : ""}${item.fromMinute !== null && item.untilMinute !== null ? " " : ""}${item.untilMinute !== null ? `before ${clock(item.untilMinute)}` : ""}`
50
+ : "";
51
+ return [count, days, times].filter(Boolean).join(" · ");
52
+ }
53
+ /**
54
+ * What is left of a holding, in words, from the host's count: `2 of 3 left this week`. Display
55
+ * only: whether it can pay for a class is the host's, at booking.
56
+ */
57
+ export function leftWords(h) {
58
+ if (!h.live) {
59
+ if (h.status === "void")
60
+ return "Void";
61
+ if (h.until && Date.parse(h.until) <= Date.now())
62
+ return `Ended ${day(h.until)}`;
63
+ if (h.status === "paused")
64
+ return "Paused";
65
+ if (h.status === "unpaid" || h.status === "ended")
66
+ return "Not active";
67
+ if (h.period && h.period.left === 0)
68
+ return "None left";
69
+ return "Not active";
70
+ }
71
+ const p = h.period;
72
+ if (!p || p.left === null)
73
+ return "Unlimited";
74
+ const when = h.per === "week" ? " this week" : h.per === "month" ? " this month" : "";
75
+ return h.uses !== null ? `${p.left} of ${h.uses} left${when}` : `${p.left} left${when}`;
76
+ }
77
+ /** What a membership's subscription means to its payer, in words. Display only. */
78
+ export function subscriptionStatus(sub) {
79
+ const ends = sub.cancelAtPeriodEnd ? sub.currentPeriodEnd : sub.cancelAt;
80
+ switch (sub.state) {
81
+ case "trialing":
82
+ return ends
83
+ ? `Free, ending on ${day(ends)}: nothing will be charged`
84
+ : `Free until ${day(sub.trialEnd ?? sub.currentPeriodEnd)}, then charged each ${sub.interval}`;
85
+ case "active":
86
+ return ends
87
+ ? `Active until ${day(ends)}, then it ends`
88
+ : `Active: next charge on ${day(sub.currentPeriodEnd)}`;
89
+ case "past_due":
90
+ return sub.actionUrl
91
+ ? "A payment needs you to confirm it"
92
+ : "A payment failed: the payment provider will try again";
93
+ case "unpaid":
94
+ return "Unpaid: update your card to keep booking";
95
+ case "paused":
96
+ return sub.change?.kind === "pause" && sub.change.pauseUntil
97
+ ? `Paused until ${day(sub.change.pauseUntil)}: nothing is charged meanwhile`
98
+ : "Paused";
99
+ case "incomplete":
100
+ return "Waiting for its first payment";
101
+ case "expired":
102
+ return "Never started: its first payment did not go through";
103
+ case "ended":
104
+ return `Ended${sub.endedAt ? ` on ${day(sub.endedAt)}` : ""}`;
105
+ }
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
+ }
156
+ /** Whether a subscription is still the payer's to cancel, resume or pay (not ended). */
157
+ export const isLive = (sub) => sub.state !== "ended" && sub.state !== "expired";
158
+ /** What a member is told when the host refuses a pass (its `rule` and `reason`). Display only. */
159
+ export function refusalWords(details) {
160
+ if (details?.rule === "once_per_person") {
161
+ switch (details.reason) {
162
+ case "sign_in":
163
+ return "This offer is one per person: sign in to buy it.";
164
+ case "used":
165
+ return "This offer is one per person, and you have had yours.";
166
+ case "held":
167
+ return "This offer is one per person, and an order for yours is waiting to be paid.";
168
+ default:
169
+ return "This offer is one per person.";
170
+ }
171
+ }
172
+ if (details?.rule === "sale_window" || details?.rule === "not_for_sale") {
173
+ return "This is not on sale just now.";
174
+ }
175
+ return "We could not start your order.";
176
+ }
177
+ /**
178
+ * The operations each hook calls (ADR 0453). The public's client gets the plans, the pass types,
179
+ * buying and subscribing; a customer's client also what they hold and their subscriptions; the
180
+ * staff client a person's holdings and giving or voiding a pass.
181
+ */
182
+ export const MEMBERSHIPS_HOOKS_CALL = {
183
+ usePlans: ["x.memberships.plans"],
184
+ usePassTypes: ["x.memberships.passTypes"],
185
+ useBuyPass: ["x.memberships.buy", "order.checkout"],
186
+ useMine: ["x.memberships.mine"],
187
+ useHoldings: ["x.memberships.holdings"],
188
+ useGivePass: ["x.memberships.givePass"],
189
+ useVoidPass: ["x.memberships.voidPass"],
190
+ // A membership's billing (stage 32a's flows). Every action is the web's: a native block may
191
+ // read the subscription only (the block lint).
192
+ useSubscribe: ["subscription.start"],
193
+ useMySubscriptions: ["subscription.list"],
194
+ useCancelSubscription: ["subscription.cancel"],
195
+ useResumeSubscription: ["subscription.resume"],
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"],
203
+ };
204
+ /**
205
+ * Hooks for a React or React Native app:
206
+ * `const memberships = createMembershipsHooks({ useQuery, useMutation }, api)`. The hooks a client
207
+ * cannot back are not there, and calling one does not compile.
208
+ */
209
+ export function createMembershipsHooks(react, client) {
210
+ return packHooks(client, MEMBERSHIPS_HOOKS_CALL, (api) => allMembershipsHooks(react, api));
211
+ }
212
+ function allMembershipsHooks(react, api) {
213
+ const { useQuery, useMutation } = react;
214
+ return {
215
+ /** The membership plans on sale, with the host's prices and trial days. */
216
+ usePlans() {
217
+ return useQuery(api.query("x.memberships.plans", {}));
218
+ },
219
+ /** The passes on sale, with the host's prices. */
220
+ usePassTypes() {
221
+ return useQuery(api.query("x.memberships.passTypes", {}));
222
+ },
223
+ /** Start an order for a pass; then `checkout` it on the provider's page (web only). */
224
+ useBuyPass() {
225
+ return {
226
+ start: useMutation(api.mutation("x.memberships.buy")),
227
+ checkout: useMutation(api.mutation("order.checkout")),
228
+ };
229
+ },
230
+ /** The signed-in member's memberships and passes, with the host's count of what is left. */
231
+ useMine() {
232
+ return useQuery(api.query("x.memberships.mine", {}));
233
+ },
234
+ /** Staff: one person's memberships and passes. */
235
+ useHoldings(personId) {
236
+ return useQuery(api.query("x.memberships.holdings", { personId }));
237
+ },
238
+ /** Staff (a person): give a pass by hand, with a reason. */
239
+ useGivePass() {
240
+ return useMutation(api.mutation("x.memberships.givePass"));
241
+ },
242
+ /** Staff (a person): void a pass given by hand, with a reason. */
243
+ useVoidPass() {
244
+ return useMutation(api.mutation("x.memberships.voidPass"));
245
+ },
246
+ /** Start a membership: the host opens the provider's page (web only); the trial is the host's. */
247
+ useSubscribe() {
248
+ return useMutation(api.mutation("subscription.start"));
249
+ },
250
+ /** The signed-in payer's own membership subscriptions, newest first. */
251
+ useMySubscriptions() {
252
+ return useQuery(api.query("subscription.list", {
253
+ filter: { field: "planObject", op: "eq", value: PLAN },
254
+ limit: 20,
255
+ }));
256
+ },
257
+ /** End their own membership when its period ends (web only). */
258
+ useCancelSubscription() {
259
+ return useMutation(api.mutation("subscription.cancel"));
260
+ },
261
+ /** Undo that, before the period ends (web only). */
262
+ useResumeSubscription() {
263
+ return useMutation(api.mutation("subscription.resume"));
264
+ },
265
+ /** The provider's portal for their card and past invoices (web only, never in a frame). */
266
+ useBillingPortal() {
267
+ return useMutation(api.mutation("subscription.portal"));
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
+ },
296
+ };
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 };