@extantape/payload-plugin-membership 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +167 -2
- package/dist/access.d.ts +34 -0
- package/dist/access.js +168 -0
- package/dist/api.d.ts +65 -0
- package/dist/api.js +319 -0
- package/dist/collections.d.ts +6 -0
- package/dist/collections.js +319 -0
- package/dist/endpoints.d.ts +13 -0
- package/dist/endpoints.js +188 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/plugin.d.ts +9 -0
- package/dist/plugin.js +43 -0
- package/dist/types.d.ts +161 -0
- package/dist/types.js +1 -0
- package/package.json +64 -4
package/dist/api.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { checkoutAllowed } from './access.js';
|
|
3
|
+
const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
|
|
4
|
+
const ctx = { membershipSync: true };
|
|
5
|
+
export const membershipOf = (payload) => payload.config.custom?.membership;
|
|
6
|
+
const stripeOf = (o) => {
|
|
7
|
+
const s = o.stripe();
|
|
8
|
+
if (!s)
|
|
9
|
+
throw new APIError('Memberships are not available here yet.', 503, undefined, true);
|
|
10
|
+
return s;
|
|
11
|
+
};
|
|
12
|
+
/** Validates a choice and turns it into priced lines (creating Stripe products on first use). */
|
|
13
|
+
async function linesFor(payload, o, choice, scope) {
|
|
14
|
+
if (choice.interval !== 'month' && choice.interval !== 'year')
|
|
15
|
+
throw new APIError('Choose monthly or yearly.', 400, undefined, true);
|
|
16
|
+
const inScope = (d) => !o.scopeField || !scope || idOf(d[o.scopeField]) === scope;
|
|
17
|
+
if (choice.tier) {
|
|
18
|
+
const tier = (await payload.findByID({ collection: o.tiers, id: choice.tier, depth: 0, overrideAccess: true, disableErrors: true }));
|
|
19
|
+
const price = tier?.[choice.interval === 'month' ? 'monthly' : 'yearly'];
|
|
20
|
+
if (!tier || !tier.active || !inScope(tier) || !(price > 0))
|
|
21
|
+
throw new APIError('That tier isn’t available.', 400, undefined, true);
|
|
22
|
+
return { kind: 'tier', tier, pledges: [], lines: [{ product: await productFor(payload, o, o.tiers, tier), name: tier.name, amount: Math.round(price) }] };
|
|
23
|
+
}
|
|
24
|
+
const pledges = (choice.pledges ?? []).filter((p) => p && p.category && Number(p.amount) > 0).map((p) => ({ category: String(p.category), amount: Math.round(Number(p.amount)) }));
|
|
25
|
+
if (pledges.length === 0)
|
|
26
|
+
throw new APIError('Choose a tier, or at least one category with an amount.', 400, undefined, true);
|
|
27
|
+
if (pledges.length > 20)
|
|
28
|
+
throw new APIError('Choose at most 20 categories.', 400, undefined, true);
|
|
29
|
+
if (new Set(pledges.map((p) => p.category)).size !== pledges.length)
|
|
30
|
+
throw new APIError('Each category once, please.', 400, undefined, true);
|
|
31
|
+
const lines = [];
|
|
32
|
+
for (const p of pledges) {
|
|
33
|
+
const cat = (await payload.findByID({ collection: o.categories, id: p.category, depth: 0, overrideAccess: true, disableErrors: true }));
|
|
34
|
+
if (!cat || !cat.active || !inScope(cat))
|
|
35
|
+
throw new APIError('One of those categories isn’t available.', 400, undefined, true);
|
|
36
|
+
const minimum = (Number(cat.minimum) || 0) * (choice.interval === 'year' ? 12 : 1);
|
|
37
|
+
if (p.amount < Math.max(minimum, 50))
|
|
38
|
+
throw new APIError(`The minimum for ${cat.name} is ${(Math.max(minimum, 50) / 100).toFixed(2)}.`, 400, undefined, true);
|
|
39
|
+
lines.push({ product: await productFor(payload, o, o.categories, cat), name: cat.name, amount: p.amount });
|
|
40
|
+
}
|
|
41
|
+
return { kind: 'pledge', tier: null, pledges, lines };
|
|
42
|
+
}
|
|
43
|
+
async function productFor(payload, o, slug, doc) {
|
|
44
|
+
if (doc.stripeProduct)
|
|
45
|
+
return doc.stripeProduct;
|
|
46
|
+
const product = await stripeOf(o).products.create({ name: doc.name, metadata: { payloadCollection: slug, payloadId: String(doc.id) } });
|
|
47
|
+
await payload.update({ collection: slug, id: doc.id, data: { stripeProduct: product.id }, overrideAccess: true, context: ctx });
|
|
48
|
+
return product.id;
|
|
49
|
+
}
|
|
50
|
+
const priceData = (o, line, interval) => ({
|
|
51
|
+
currency: o.currency,
|
|
52
|
+
product: line.product,
|
|
53
|
+
unit_amount: line.amount,
|
|
54
|
+
recurring: { interval },
|
|
55
|
+
});
|
|
56
|
+
const labelOf = (user, kind, tier, lines) => `${user.name || user.email || 'Member'} · ${kind === 'tier' ? tier.name : lines.map((l) => l.name).join(', ')}`.slice(0, 200);
|
|
57
|
+
/** Members in good standing (or still paying) block a second membership in the same scope. */
|
|
58
|
+
async function currentMembership(payload, o, userId, scope) {
|
|
59
|
+
const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
|
|
60
|
+
return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Starts a membership: validates the choice, records it as pending and opens
|
|
64
|
+
* Stripe Checkout (a subscription with the member's own amounts). Returns the
|
|
65
|
+
* Checkout URL; the webhook activates it once Stripe confirms.
|
|
66
|
+
*/
|
|
67
|
+
export async function startCheckout(payload, args) {
|
|
68
|
+
const o = membershipOf(payload);
|
|
69
|
+
if (!(await checkoutAllowed(o, payload)))
|
|
70
|
+
throw new APIError('Memberships are not available here yet.', 503, undefined, true);
|
|
71
|
+
const stripe = stripeOf(o);
|
|
72
|
+
const scope = args.scope ?? null;
|
|
73
|
+
if (await currentMembership(payload, o, String(args.user.id), scope))
|
|
74
|
+
throw new APIError('You already have a membership: change it instead.', 409, undefined, true);
|
|
75
|
+
const { kind, lines, tier, pledges } = await linesFor(payload, o, args, scope);
|
|
76
|
+
const previous = (await payload.find({ collection: o.memberships, where: { and: [{ user: { equals: args.user.id } }, { 'stripe.customer': { exists: true } }] }, sort: '-createdAt', limit: 1, depth: 0, overrideAccess: true })).docs[0];
|
|
77
|
+
const membership = (await payload.create({
|
|
78
|
+
collection: o.memberships,
|
|
79
|
+
data: {
|
|
80
|
+
label: labelOf(args.user, kind, tier, lines),
|
|
81
|
+
user: args.user.id,
|
|
82
|
+
kind,
|
|
83
|
+
tier: tier ? tier.id : null,
|
|
84
|
+
pledges,
|
|
85
|
+
interval: args.interval,
|
|
86
|
+
amount: lines.reduce((sum, l) => sum + l.amount, 0),
|
|
87
|
+
currency: o.currency,
|
|
88
|
+
status: 'pending',
|
|
89
|
+
wall: { show: Boolean(args.wall?.show), name: args.wall?.name?.trim().slice(0, 80) || null },
|
|
90
|
+
...(o.scopeField && scope ? { [o.scopeField]: scope } : {}),
|
|
91
|
+
},
|
|
92
|
+
overrideAccess: true,
|
|
93
|
+
context: ctx,
|
|
94
|
+
}));
|
|
95
|
+
const session = await stripe.checkout.sessions.create({
|
|
96
|
+
mode: 'subscription',
|
|
97
|
+
line_items: lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, args.interval) })),
|
|
98
|
+
...(previous?.stripe?.customer ? { customer: previous.stripe.customer } : { customer_email: args.user.email }),
|
|
99
|
+
client_reference_id: String(membership.id),
|
|
100
|
+
metadata: { membership: String(membership.id) },
|
|
101
|
+
subscription_data: { metadata: { membership: String(membership.id) } },
|
|
102
|
+
success_url: args.successURL,
|
|
103
|
+
cancel_url: args.cancelURL,
|
|
104
|
+
});
|
|
105
|
+
await payload.update({ collection: o.memberships, id: membership.id, data: { stripe: { checkoutSession: session.id } }, overrideAccess: true, context: ctx });
|
|
106
|
+
if (!session.url)
|
|
107
|
+
throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
|
|
108
|
+
return { url: session.url, membership: String(membership.id) };
|
|
109
|
+
}
|
|
110
|
+
/** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
|
|
111
|
+
export async function changeMembership(payload, membershipId, choice) {
|
|
112
|
+
const o = membershipOf(payload);
|
|
113
|
+
const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 1, overrideAccess: true }));
|
|
114
|
+
if (!m.stripe?.subscription || !['active', 'past_due'].includes(m.status))
|
|
115
|
+
throw new APIError('Only a running membership can be changed.', 409, undefined, true);
|
|
116
|
+
const scope = o.scopeField ? idOf(m[o.scopeField]) : null;
|
|
117
|
+
const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
|
|
118
|
+
const stripe = stripeOf(o);
|
|
119
|
+
const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
|
|
120
|
+
await stripe.subscriptions.update(sub.id, {
|
|
121
|
+
items: [...sub.items.data.map((i) => ({ id: i.id, deleted: true })), ...lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, m.interval) }))],
|
|
122
|
+
proration_behavior: 'none',
|
|
123
|
+
cancel_at_period_end: false,
|
|
124
|
+
});
|
|
125
|
+
return (await payload.update({
|
|
126
|
+
collection: o.memberships,
|
|
127
|
+
id: m.id,
|
|
128
|
+
data: { kind, tier: tier ? tier.id : null, pledges, amount: lines.reduce((sum, l) => sum + l.amount, 0), cancelAtPeriodEnd: false, label: labelOf(typeof m.user === 'object' ? m.user : { email: '' }, kind, tier, lines) },
|
|
129
|
+
overrideAccess: true,
|
|
130
|
+
context: ctx,
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
/** Cancels at the end of the paid period (the member keeps their perks until then). */
|
|
134
|
+
export async function cancelMembership(payload, membershipId) {
|
|
135
|
+
const o = membershipOf(payload);
|
|
136
|
+
const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
|
|
137
|
+
if (!m.stripe?.subscription)
|
|
138
|
+
throw new APIError('This membership has no subscription to cancel.', 409, undefined, true);
|
|
139
|
+
await stripeOf(o).subscriptions.update(m.stripe.subscription, { cancel_at_period_end: true });
|
|
140
|
+
return (await payload.update({ collection: o.memberships, id: m.id, data: { cancelAtPeriodEnd: true }, overrideAccess: true, context: ctx }));
|
|
141
|
+
}
|
|
142
|
+
/** Stripe's customer portal (payment method, invoices, cancel). */
|
|
143
|
+
export async function portalLink(payload, membershipId, returnURL) {
|
|
144
|
+
const o = membershipOf(payload);
|
|
145
|
+
const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
|
|
146
|
+
if (!m.stripe?.customer)
|
|
147
|
+
throw new APIError('Nothing to manage yet.', 409, undefined, true);
|
|
148
|
+
return (await stripeOf(o).billingPortal.sessions.create({ customer: m.stripe.customer, return_url: returnURL })).url;
|
|
149
|
+
}
|
|
150
|
+
const statusFrom = (s) => s === 'active' || s === 'trialing' ? 'active' : s === 'past_due' || s === 'unpaid' ? 'past_due' : s === 'incomplete' ? 'incomplete' : s === 'paused' ? 'past_due' : 'canceled';
|
|
151
|
+
const recordOf = (m) => ({
|
|
152
|
+
id: String(m.id),
|
|
153
|
+
user: String(idOf(m.user)),
|
|
154
|
+
kind: m.kind,
|
|
155
|
+
tier: idOf(m.tier),
|
|
156
|
+
pledges: (m.pledges ?? []).map((p) => ({ category: String(idOf(p.category)), amount: p.amount })),
|
|
157
|
+
interval: m.interval,
|
|
158
|
+
amount: m.amount,
|
|
159
|
+
currency: m.currency,
|
|
160
|
+
status: m.status,
|
|
161
|
+
});
|
|
162
|
+
async function setMembership(payload, o, m, data) {
|
|
163
|
+
const updated = (await payload.update({ collection: o.memberships, id: m.id, data: data, overrideAccess: true, depth: 0, context: ctx }));
|
|
164
|
+
if (data.status && data.status !== m.status && o.onStatusChange)
|
|
165
|
+
await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
|
|
166
|
+
return updated;
|
|
167
|
+
}
|
|
168
|
+
async function findBy(payload, o, where) {
|
|
169
|
+
return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
|
|
170
|
+
}
|
|
171
|
+
const subscriptionIdOf = (obj) => idOf(obj.subscription) ?? idOf(obj.parent?.subscription_details?.subscription) ?? idOf(obj.lines?.data?.[0]?.parent?.subscription_item_details?.subscription) ?? null;
|
|
172
|
+
const periodEndOf = (sub) => sub.current_period_end ?? sub.items?.data?.[0]?.current_period_end;
|
|
173
|
+
/**
|
|
174
|
+
* Applies one Stripe webhook event. Safe to receive twice: payments are keyed
|
|
175
|
+
* by invoice, and status updates are idempotent.
|
|
176
|
+
*/
|
|
177
|
+
export async function handleStripeEvent(payload, event) {
|
|
178
|
+
const o = membershipOf(payload);
|
|
179
|
+
const obj = event.data.object;
|
|
180
|
+
switch (event.type) {
|
|
181
|
+
case 'checkout.session.completed': {
|
|
182
|
+
if (obj.mode !== 'subscription')
|
|
183
|
+
return 'ignored';
|
|
184
|
+
const id = obj.metadata?.membership ?? obj.client_reference_id;
|
|
185
|
+
const m = id ? await findBy(payload, o, { id: { equals: id } }) : undefined;
|
|
186
|
+
if (!m)
|
|
187
|
+
return 'ignored';
|
|
188
|
+
const subId = idOf(obj.subscription);
|
|
189
|
+
const sub = subId ? await stripeOf(o).subscriptions.retrieve(subId) : null;
|
|
190
|
+
const end = sub ? periodEndOf(sub) : undefined;
|
|
191
|
+
await setMembership(payload, o, m, {
|
|
192
|
+
stripe: { ...m.stripe, customer: idOf(obj.customer), subscription: subId },
|
|
193
|
+
status: sub ? statusFrom(sub.status) : 'incomplete',
|
|
194
|
+
startedAt: m.startedAt ?? new Date().toISOString(),
|
|
195
|
+
...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
|
|
196
|
+
});
|
|
197
|
+
return 'handled';
|
|
198
|
+
}
|
|
199
|
+
case 'invoice.paid': {
|
|
200
|
+
const subId = subscriptionIdOf(obj);
|
|
201
|
+
const m = subId ? await findBy(payload, o, { 'stripe.subscription': { equals: subId } }) : undefined;
|
|
202
|
+
if (!m || !(obj.amount_paid > 0))
|
|
203
|
+
return 'ignored';
|
|
204
|
+
const exists = await payload.find({ collection: o.payments, where: { invoiceId: { equals: obj.id } }, limit: 1, depth: 0, overrideAccess: true });
|
|
205
|
+
if (exists.totalDocs)
|
|
206
|
+
return 'ignored';
|
|
207
|
+
const paidAt = new Date((obj.status_transitions?.paid_at ?? obj.created ?? Date.now() / 1000) * 1000).toISOString();
|
|
208
|
+
const share = (amount) => (m.amount > 0 ? Math.round((amount * obj.amount_paid) / m.amount) : 0);
|
|
209
|
+
const pledges = (m.pledges ?? []).map((p) => ({ category: idOf(p.category), amount: share(p.amount) }));
|
|
210
|
+
let payment;
|
|
211
|
+
try {
|
|
212
|
+
payment = (await payload.create({
|
|
213
|
+
collection: o.payments,
|
|
214
|
+
data: { membership: m.id, user: idOf(m.user), amount: obj.amount_paid, currency: obj.currency ?? m.currency, paidAt, invoiceId: obj.id, tier: idOf(m.tier), pledges, ...(o.scopeField && m[o.scopeField] ? { [o.scopeField]: idOf(m[o.scopeField]) } : {}) },
|
|
215
|
+
overrideAccess: true,
|
|
216
|
+
context: ctx,
|
|
217
|
+
// One document, kept unique by the invoiceId index; no transaction needed. Inside one,
|
|
218
|
+
// a multi-tenant host's relationship checks run in parallel and Mongo aborts them.
|
|
219
|
+
disableTransaction: true,
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
// The same invoice arrived twice at once: the unique invoiceId let the other copy record it.
|
|
224
|
+
const recorded = await payload.count({ collection: o.payments, where: { invoiceId: { equals: obj.id } }, overrideAccess: true });
|
|
225
|
+
if (recorded.totalDocs)
|
|
226
|
+
return 'ignored';
|
|
227
|
+
throw err; // anything else (or the other copy not committed yet): fail, so Stripe retries
|
|
228
|
+
}
|
|
229
|
+
const periodEnd = obj.lines?.data?.[0]?.period?.end;
|
|
230
|
+
// Atomic writes outside a transaction, so two invoices paid at once both count: the total
|
|
231
|
+
// goes up with $inc, and only the delivery that actually flips the status reports it.
|
|
232
|
+
const memberships = o.memberships;
|
|
233
|
+
await payload.db.updateOne({
|
|
234
|
+
collection: memberships,
|
|
235
|
+
id: m.id,
|
|
236
|
+
data: { totalPaid: { $inc: obj.amount_paid }, ...(periodEnd ? { currentPeriodEnd: new Date(periodEnd * 1000).toISOString() } : {}) },
|
|
237
|
+
returning: false,
|
|
238
|
+
});
|
|
239
|
+
const activated = m.status !== 'active' &&
|
|
240
|
+
(await payload.db.updateOne({ collection: memberships, where: { and: [{ id: { equals: m.id } }, { status: { not_equals: 'active' } }] }, data: { status: 'active' } }));
|
|
241
|
+
const updated = (await payload.findByID({ collection: memberships, id: m.id, depth: 0, overrideAccess: true }));
|
|
242
|
+
if (activated && o.onStatusChange)
|
|
243
|
+
await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
|
|
244
|
+
if (o.onPayment)
|
|
245
|
+
await o.onPayment({
|
|
246
|
+
payload,
|
|
247
|
+
membership: recordOf(updated),
|
|
248
|
+
payment: { id: String(payment.id), membership: String(m.id), user: String(idOf(m.user)), amount: obj.amount_paid, currency: payment.currency, paidAt, invoiceId: obj.id, pledges: pledges, tier: idOf(m.tier) },
|
|
249
|
+
});
|
|
250
|
+
return 'handled';
|
|
251
|
+
}
|
|
252
|
+
case 'invoice.payment_failed': {
|
|
253
|
+
const subId = subscriptionIdOf(obj);
|
|
254
|
+
const m = subId ? await findBy(payload, o, { 'stripe.subscription': { equals: subId } }) : undefined;
|
|
255
|
+
if (!m)
|
|
256
|
+
return 'ignored';
|
|
257
|
+
await setMembership(payload, o, m, { status: 'past_due' });
|
|
258
|
+
return 'handled';
|
|
259
|
+
}
|
|
260
|
+
case 'customer.subscription.updated':
|
|
261
|
+
case 'customer.subscription.deleted': {
|
|
262
|
+
const sub = obj;
|
|
263
|
+
const m = (await findBy(payload, o, { 'stripe.subscription': { equals: sub.id } })) ?? (sub.metadata?.membership ? await findBy(payload, o, { id: { equals: sub.metadata.membership } }) : undefined);
|
|
264
|
+
if (!m)
|
|
265
|
+
return 'ignored';
|
|
266
|
+
const status = event.type === 'customer.subscription.deleted' ? 'canceled' : statusFrom(sub.status);
|
|
267
|
+
const end = periodEndOf(sub);
|
|
268
|
+
await setMembership(payload, o, m, {
|
|
269
|
+
status,
|
|
270
|
+
cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
|
|
271
|
+
...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
|
|
272
|
+
...(status === 'canceled' ? { canceledAt: new Date().toISOString() } : {}),
|
|
273
|
+
});
|
|
274
|
+
return 'handled';
|
|
275
|
+
}
|
|
276
|
+
default:
|
|
277
|
+
return 'ignored';
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The backers wall: active members who chose to be shown, under their tier or
|
|
282
|
+
* under each category they support, A–Z within each (user decision for
|
|
283
|
+
* the original site). Groups follow the admin's (drag-and-drop) order.
|
|
284
|
+
*/
|
|
285
|
+
export async function getBackers(payload, opts = {}) {
|
|
286
|
+
const o = membershipOf(payload);
|
|
287
|
+
const scoped = (w) => ({ and: [...w, ...(o.scopeField && opts.scope ? [{ [o.scopeField]: { equals: opts.scope } }] : [])] });
|
|
288
|
+
const read = { depth: 0, pagination: false, overrideAccess: true, locale: opts.locale };
|
|
289
|
+
const [members, tiers, categories] = await Promise.all([
|
|
290
|
+
payload.find({ collection: o.memberships, where: scoped([{ status: { equals: 'active' } }, { 'wall.show': { equals: true } }]), select: { kind: true, tier: true, pledges: true, wall: true, startedAt: true }, ...read }),
|
|
291
|
+
payload.find({ collection: o.tiers, where: scoped([]), sort: '_order', select: { name: true, description: true, color: true }, ...read }),
|
|
292
|
+
payload.find({ collection: o.categories, where: scoped([]), sort: '_order', select: { name: true, description: true, color: true, parent: true }, ...read }),
|
|
293
|
+
]);
|
|
294
|
+
const byTier = new Map();
|
|
295
|
+
const byCategory = new Map();
|
|
296
|
+
const add = (map, key, b) => key && map.set(key, [...(map.get(key) ?? []), b]);
|
|
297
|
+
for (const m of members.docs) {
|
|
298
|
+
const name = String(m.wall?.name ?? '').trim();
|
|
299
|
+
if (!name)
|
|
300
|
+
continue;
|
|
301
|
+
const b = { name, since: m.startedAt ?? null };
|
|
302
|
+
if (m.kind === 'tier')
|
|
303
|
+
add(byTier, idOf(m.tier), b);
|
|
304
|
+
else
|
|
305
|
+
for (const p of m.pledges ?? [])
|
|
306
|
+
add(byCategory, idOf(p.category), b);
|
|
307
|
+
}
|
|
308
|
+
const az = (list) => [...list].sort((a, b) => a.name.localeCompare(b.name, opts.locale ?? 'en', { sensitivity: 'base' }));
|
|
309
|
+
return {
|
|
310
|
+
tiers: tiers.docs.map((t) => ({ group: t, backers: az(byTier.get(String(t.id)) ?? []) })).filter((g) => g.backers.length),
|
|
311
|
+
categories: categories.docs.map((c) => ({ group: c, backers: az(byCategory.get(String(c.id)) ?? []) })).filter((g) => g.backers.length),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
/** The signed-in member's current membership in a scope (for account pages). */
|
|
315
|
+
export async function myMembership(payload, userId, scope = null) {
|
|
316
|
+
const o = membershipOf(payload);
|
|
317
|
+
const where = { and: [{ user: { equals: userId } }, { status: { not_equals: 'pending' } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
|
|
318
|
+
return (await payload.find({ collection: o.memberships, where, sort: '-createdAt', limit: 1, depth: 1, overrideAccess: true })).docs[0] ?? null;
|
|
319
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CollectionConfig } from 'payload';
|
|
2
|
+
import type { ResolvedMembership } from './types.js';
|
|
3
|
+
export declare function tiersCollection(o: ResolvedMembership): CollectionConfig;
|
|
4
|
+
export declare function categoriesCollection(o: ResolvedMembership): CollectionConfig;
|
|
5
|
+
export declare function membershipsCollection(o: ResolvedMembership): CollectionConfig;
|
|
6
|
+
export declare function paymentsCollection(o: ResolvedMembership): CollectionConfig;
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { generateKeyBetween } from 'payload/shared';
|
|
2
|
+
import { managerReaches, managerScope, matchesWhere, viaMembership } from './access.js';
|
|
3
|
+
const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
|
|
4
|
+
/** Drag-and-drop ordered (Payload `orderable`); a new record goes between its alphabetical neighbours. */
|
|
5
|
+
const placeAlphabetically = (o, slug, field) => async ({ data, operation, req }) => {
|
|
6
|
+
if (operation !== 'create' || data._order || !data[field])
|
|
7
|
+
return data;
|
|
8
|
+
const scope = o.scopeField ? idOf(data[o.scopeField]) : null;
|
|
9
|
+
const { docs } = await req.payload.find({
|
|
10
|
+
collection: slug,
|
|
11
|
+
where: o.scopeField && scope ? { [o.scopeField]: { equals: scope } } : {},
|
|
12
|
+
sort: '_order',
|
|
13
|
+
depth: 0,
|
|
14
|
+
pagination: false,
|
|
15
|
+
overrideAccess: true,
|
|
16
|
+
select: { [field]: true, _order: true },
|
|
17
|
+
req,
|
|
18
|
+
});
|
|
19
|
+
const ordered = docs;
|
|
20
|
+
const next = ordered.findIndex((d) => String(d[field]).localeCompare(String(data[field]), 'en', { sensitivity: 'base' }) > 0);
|
|
21
|
+
const before = next === -1 ? (ordered.at(-1)?._order ?? null) : next > 0 ? (ordered[next - 1]._order ?? null) : null;
|
|
22
|
+
const after = next === -1 ? null : (ordered[next]._order ?? null);
|
|
23
|
+
try {
|
|
24
|
+
data._order = generateKeyBetween(before, after);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// Neighbours out of order after manual moves: Payload appends it at the end instead.
|
|
28
|
+
}
|
|
29
|
+
return data;
|
|
30
|
+
};
|
|
31
|
+
/** No write through the API for anyone: only the plugin's own server code (with overrideAccess) changes these. */
|
|
32
|
+
const LOCKED = { update: () => false };
|
|
33
|
+
/** Only the member whose row it is. */
|
|
34
|
+
const memberOnly = ({ req, doc }) => Boolean(req.user) && String(idOf(doc?.user)) === String(req.user.id);
|
|
35
|
+
/** Only the member sets `wall.show` to true; a manager may only hide (`false`), e.g. for an offensive name or a takedown request. */
|
|
36
|
+
const wallShow = (o) => async (args) => {
|
|
37
|
+
if (await memberOnly(args))
|
|
38
|
+
return true;
|
|
39
|
+
if (args.siblingData?.show !== false)
|
|
40
|
+
return false;
|
|
41
|
+
const scope = await managerScope(o, args.req);
|
|
42
|
+
if (scope === true)
|
|
43
|
+
return true;
|
|
44
|
+
const id = args.id ?? args.doc?.id;
|
|
45
|
+
return Boolean(scope) && id != null && managerReaches(o, args.req, o.memberships, id);
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Manager access by `canManage`'s answer: `true` is every row, a query is only the rows it matches
|
|
49
|
+
* (`via` rewrites it for a collection that holds the rows indirectly), anything else is no. A new
|
|
50
|
+
* row (`create`) must match the query in its own data.
|
|
51
|
+
*/
|
|
52
|
+
function scopedManager(o, via = (w) => w, collection) {
|
|
53
|
+
// An update by a limited manager must leave the row inside their query: the existing row with the
|
|
54
|
+
// incoming data merged over it is matched in memory, so a row can't be moved out of scope or into
|
|
55
|
+
// another site. Nothing to check unless the data touches a field the query names.
|
|
56
|
+
const update = async ({ req, id, data }) => {
|
|
57
|
+
const scope = await managerScope(o, req);
|
|
58
|
+
if (scope === true)
|
|
59
|
+
return true;
|
|
60
|
+
if (!scope)
|
|
61
|
+
return false;
|
|
62
|
+
const where = via(scope);
|
|
63
|
+
if (data && collection && referencedFields(scope).some((k) => k in data)) {
|
|
64
|
+
let merged = data;
|
|
65
|
+
if (id != null) {
|
|
66
|
+
const existing = await req.payload.findByID({ collection: collection, id, depth: 0, overrideAccess: true, disableErrors: true, req });
|
|
67
|
+
if (!existing)
|
|
68
|
+
return false;
|
|
69
|
+
merged = { ...existing, ...data };
|
|
70
|
+
}
|
|
71
|
+
if (!matchesWhere(scope, merged))
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
return where;
|
|
75
|
+
};
|
|
76
|
+
const rows = () => async ({ req }) => {
|
|
77
|
+
const scope = await managerScope(o, req);
|
|
78
|
+
return scope === true ? true : scope ? via(scope) : false;
|
|
79
|
+
};
|
|
80
|
+
const create = async ({ req, data }) => {
|
|
81
|
+
const scope = await managerScope(o, req);
|
|
82
|
+
return scope === true || (scope !== null && matchesWhere(scope, data));
|
|
83
|
+
};
|
|
84
|
+
return { create, update: collection ? update : rows(), remove: rows() };
|
|
85
|
+
}
|
|
86
|
+
/** Top-level field names a query mentions. */
|
|
87
|
+
function referencedFields(where) {
|
|
88
|
+
return Object.entries(where).flatMap(([k, v]) => (k === 'and' || k === 'or' ? v.flatMap(referencedFields) : [k.split('.')[0]]));
|
|
89
|
+
}
|
|
90
|
+
/** Managers read what `canManage` reaches and members their own rows; anyone else gets nothing. */
|
|
91
|
+
function ownOrScoped(o, via = (w) => w) {
|
|
92
|
+
return async ({ req }) => {
|
|
93
|
+
if (!req.user)
|
|
94
|
+
return false;
|
|
95
|
+
const own = { user: { equals: req.user.id } };
|
|
96
|
+
const scope = await managerScope(o, req);
|
|
97
|
+
if (scope === true)
|
|
98
|
+
return true;
|
|
99
|
+
return scope ? { or: [via(scope), own] } : own;
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** A relationship may only be set to a row the manager reaches (nothing to check when it isn't being set). */
|
|
103
|
+
function inScope(o, target) {
|
|
104
|
+
return async ({ req, siblingData, data }) => {
|
|
105
|
+
const sent = siblingData?.parent ?? data?.parent;
|
|
106
|
+
if (sent == null || sent === '')
|
|
107
|
+
return true;
|
|
108
|
+
return managerReaches(o, req, target, idOf(sent));
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** Field access for managers: judged on the particular row, never on a bare yes. */
|
|
112
|
+
function managerFieldOn(o, collection) {
|
|
113
|
+
return async ({ req, id, doc, data }) => {
|
|
114
|
+
const scope = await managerScope(o, req);
|
|
115
|
+
if (scope === true)
|
|
116
|
+
return true;
|
|
117
|
+
if (!scope)
|
|
118
|
+
return false;
|
|
119
|
+
const rowId = id ?? doc?.id;
|
|
120
|
+
return rowId != null ? managerReaches(o, req, collection, rowId) : matchesWhere(scope, data);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
const money = (name, label, description) => ({ name, label, type: 'number', min: 0, admin: { description: `${description} In cents (e.g. 500 = 5.00).` } });
|
|
124
|
+
export function tiersCollection(o) {
|
|
125
|
+
const { create, update, remove } = scopedManager(o, undefined, o.tiers);
|
|
126
|
+
const managerField = managerFieldOn(o, o.tiers);
|
|
127
|
+
return {
|
|
128
|
+
slug: o.tiers,
|
|
129
|
+
labels: { singular: 'Membership tier', plural: 'Membership tiers' },
|
|
130
|
+
admin: {
|
|
131
|
+
useAsTitle: 'name',
|
|
132
|
+
defaultColumns: ['name', 'monthly', 'yearly', 'active'],
|
|
133
|
+
description: 'Fixed-price levels (Patreon-style). Shown in this order: drag rows to change it.',
|
|
134
|
+
},
|
|
135
|
+
access: { read: () => true, create, update, delete: remove },
|
|
136
|
+
orderable: true,
|
|
137
|
+
defaultSort: '_order',
|
|
138
|
+
hooks: { beforeChange: [placeAlphabetically(o, o.tiers, 'name')] },
|
|
139
|
+
fields: [
|
|
140
|
+
{ name: 'name', type: 'text', required: true },
|
|
141
|
+
{ name: 'active', label: 'Open to new members', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
|
|
142
|
+
{ type: 'row', fields: [{ ...money('monthly', 'Monthly price', 'Per month; empty: not offered monthly.'), admin: { width: '50%' } }, { ...money('yearly', 'Yearly price', 'Per year; empty: not offered yearly.'), admin: { width: '50%' } }] },
|
|
143
|
+
{ name: 'description', type: 'textarea' },
|
|
144
|
+
{ name: 'perks', type: 'array', fields: [{ name: 'perk', type: 'text', required: true }] },
|
|
145
|
+
{ name: 'color', type: 'text', admin: { position: 'sidebar', description: 'Badge color, e.g. #cf8137.' } },
|
|
146
|
+
{
|
|
147
|
+
name: 'sponsorListing',
|
|
148
|
+
label: 'Members are listed as sponsors',
|
|
149
|
+
type: 'checkbox',
|
|
150
|
+
admin: { position: 'sidebar', description: 'A perk your site can act on in onStatusChange (e.g. with payload-plugin-sponsors).' },
|
|
151
|
+
},
|
|
152
|
+
// Stripe product for this tier/category (created on first checkout; prices are set per member).
|
|
153
|
+
{ name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
|
|
154
|
+
],
|
|
155
|
+
timestamps: true,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
export function categoriesCollection(o) {
|
|
159
|
+
const { create, update, remove } = scopedManager(o, undefined, o.categories);
|
|
160
|
+
const managerField = managerFieldOn(o, o.categories);
|
|
161
|
+
return {
|
|
162
|
+
slug: o.categories,
|
|
163
|
+
labels: { singular: 'Membership category', plural: 'Membership categories' },
|
|
164
|
+
admin: {
|
|
165
|
+
useAsTitle: 'name',
|
|
166
|
+
defaultColumns: ['name', 'parent', 'minimum', 'active'],
|
|
167
|
+
description: 'What members can choose to support, setting their own amount (A–Z for new ones; drag to reorder). Add your own fields to tie categories to anything.',
|
|
168
|
+
},
|
|
169
|
+
access: { read: () => true, create, update, delete: remove },
|
|
170
|
+
orderable: true,
|
|
171
|
+
defaultSort: '_order',
|
|
172
|
+
hooks: { beforeChange: [placeAlphabetically(o, o.categories, 'name')] },
|
|
173
|
+
fields: [
|
|
174
|
+
{ name: 'name', type: 'text', required: true },
|
|
175
|
+
{ name: 'active', label: 'Open to new pledges', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
|
|
176
|
+
{ name: 'parent', type: 'relationship', relationTo: o.categories, access: { create: inScope(o, o.categories), update: inScope(o, o.categories) }, admin: { position: 'sidebar', description: 'Optional: nest under a broader category.' } },
|
|
177
|
+
{ name: 'description', type: 'textarea' },
|
|
178
|
+
money('minimum', 'Minimum per month', 'Smallest monthly amount for this category (yearly: 12×).'),
|
|
179
|
+
{
|
|
180
|
+
name: 'earmarked',
|
|
181
|
+
type: 'checkbox',
|
|
182
|
+
admin: { description: 'Off: the category is the member’s preference. On: pledges are reserved for work in this category (say so on your page).' },
|
|
183
|
+
},
|
|
184
|
+
{ name: 'color', type: 'text', admin: { position: 'sidebar' } },
|
|
185
|
+
// Stripe product for this tier/category (created on first checkout; prices are set per member).
|
|
186
|
+
{ name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
|
|
187
|
+
],
|
|
188
|
+
timestamps: true,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export function membershipsCollection(o) {
|
|
192
|
+
const { update, remove } = scopedManager(o, undefined, o.memberships);
|
|
193
|
+
const managerField = managerFieldOn(o, o.memberships);
|
|
194
|
+
// A manager reads what `canManage` reaches; members read their own (the plugin's own query, never the site's answer).
|
|
195
|
+
const ownOrManager = ownOrScoped(o);
|
|
196
|
+
const nobody = () => false;
|
|
197
|
+
return {
|
|
198
|
+
slug: o.memberships,
|
|
199
|
+
labels: { singular: 'Membership', plural: 'Memberships' },
|
|
200
|
+
admin: {
|
|
201
|
+
useAsTitle: 'label',
|
|
202
|
+
defaultColumns: ['label', 'kind', 'amount', 'interval', 'status', 'currentPeriodEnd'],
|
|
203
|
+
description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
|
|
204
|
+
},
|
|
205
|
+
// Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
|
|
206
|
+
access: { read: ownOrManager, create: nobody, update, delete: remove },
|
|
207
|
+
fields: [
|
|
208
|
+
{ name: 'label', type: 'text', access: LOCKED, admin: { readOnly: true } },
|
|
209
|
+
{ name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, access: LOCKED, admin: { readOnly: true } },
|
|
210
|
+
{
|
|
211
|
+
type: 'row',
|
|
212
|
+
fields: [
|
|
213
|
+
{ name: 'kind', type: 'select', required: true, options: [{ label: 'Tier', value: 'tier' }, { label: 'Pledge to categories', value: 'pledge' }], access: LOCKED, admin: { width: '33%', readOnly: true } },
|
|
214
|
+
{
|
|
215
|
+
name: 'status',
|
|
216
|
+
type: 'select',
|
|
217
|
+
required: true,
|
|
218
|
+
defaultValue: 'pending',
|
|
219
|
+
index: true,
|
|
220
|
+
access: LOCKED,
|
|
221
|
+
options: ['pending', 'incomplete', 'active', 'past_due', 'canceled'].map((v) => ({ label: v.replace('_', ' '), value: v })),
|
|
222
|
+
admin: { width: '33%', readOnly: true },
|
|
223
|
+
},
|
|
224
|
+
{ name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], access: LOCKED, admin: { width: '34%', readOnly: true } },
|
|
225
|
+
],
|
|
226
|
+
},
|
|
227
|
+
{ name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, access: LOCKED, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
|
|
228
|
+
{
|
|
229
|
+
name: 'pledges',
|
|
230
|
+
type: 'array',
|
|
231
|
+
access: LOCKED,
|
|
232
|
+
admin: { readOnly: true, condition: (d) => d?.kind === 'pledge' },
|
|
233
|
+
fields: [
|
|
234
|
+
{ name: 'category', type: 'relationship', relationTo: o.categories, required: true, index: true },
|
|
235
|
+
{ name: 'amount', type: 'number', required: true, min: 0, admin: { description: 'Per interval, in cents.' } },
|
|
236
|
+
],
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
type: 'row',
|
|
240
|
+
fields: [
|
|
241
|
+
{ name: 'amount', type: 'number', required: true, min: 0, access: LOCKED, admin: { width: '33%', readOnly: true, description: 'Per interval, in cents.' } },
|
|
242
|
+
{ name: 'currency', type: 'text', required: true, access: LOCKED, admin: { width: '33%', readOnly: true } },
|
|
243
|
+
{
|
|
244
|
+
name: 'totalPaid',
|
|
245
|
+
type: 'number',
|
|
246
|
+
defaultValue: 0,
|
|
247
|
+
// Only invoice.paid changes it, with an atomic $inc. Payload saves the whole document,
|
|
248
|
+
// so an edit, a Stripe event or a hook saved at the same moment as an invoice would
|
|
249
|
+
// write back an older total: leave it out of every save (0 on create).
|
|
250
|
+
access: { create: () => false, update: () => false },
|
|
251
|
+
hooks: {
|
|
252
|
+
beforeChange: [
|
|
253
|
+
({ operation, siblingData }) => {
|
|
254
|
+
if (operation === 'create')
|
|
255
|
+
return 0;
|
|
256
|
+
delete siblingData.totalPaid;
|
|
257
|
+
return undefined;
|
|
258
|
+
},
|
|
259
|
+
],
|
|
260
|
+
},
|
|
261
|
+
admin: { width: '34%', readOnly: true, description: 'All paid invoices, in cents.' },
|
|
262
|
+
},
|
|
263
|
+
],
|
|
264
|
+
},
|
|
265
|
+
{
|
|
266
|
+
type: 'row',
|
|
267
|
+
fields: [
|
|
268
|
+
{ name: 'startedAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
|
|
269
|
+
{ name: 'currentPeriodEnd', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
|
|
270
|
+
{ name: 'cancelAtPeriodEnd', type: 'checkbox', access: LOCKED, admin: { width: '25%', readOnly: true } },
|
|
271
|
+
{ name: 'canceledAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
|
|
272
|
+
],
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
name: 'wall',
|
|
276
|
+
label: 'Backers wall',
|
|
277
|
+
type: 'group',
|
|
278
|
+
admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
|
|
279
|
+
fields: [
|
|
280
|
+
{ name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false, access: { update: wallShow(o) } },
|
|
281
|
+
{ name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80, access: { update: memberOnly } },
|
|
282
|
+
],
|
|
283
|
+
},
|
|
284
|
+
// Stripe references: managers only, never in public responses.
|
|
285
|
+
{
|
|
286
|
+
name: 'stripe',
|
|
287
|
+
type: 'group',
|
|
288
|
+
access: { read: managerField, create: LOCKED.update, update: LOCKED.update },
|
|
289
|
+
admin: { position: 'sidebar', readOnly: true },
|
|
290
|
+
fields: [
|
|
291
|
+
{ name: 'customer', type: 'text', index: true },
|
|
292
|
+
{ name: 'subscription', type: 'text', index: true },
|
|
293
|
+
{ name: 'checkoutSession', type: 'text', index: true },
|
|
294
|
+
],
|
|
295
|
+
},
|
|
296
|
+
{ name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, admin: { position: 'sidebar' } },
|
|
297
|
+
],
|
|
298
|
+
timestamps: true,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
export function paymentsCollection(o) {
|
|
302
|
+
const { remove } = scopedManager(o, viaMembership);
|
|
303
|
+
const ownOrManager = ownOrScoped(o, viaMembership);
|
|
304
|
+
return {
|
|
305
|
+
slug: o.payments,
|
|
306
|
+
labels: { singular: 'Membership payment', plural: 'Membership payments' },
|
|
307
|
+
admin: { useAsTitle: 'invoiceId', defaultColumns: ['membership', 'amount', 'currency', 'paidAt'], description: 'Every paid invoice, recorded once from Stripe.' },
|
|
308
|
+
access: { read: ownOrManager, create: () => false, update: () => false, delete: remove },
|
|
309
|
+
fields: [
|
|
310
|
+
{ name: 'membership', type: 'relationship', relationTo: o.memberships, required: true, index: true },
|
|
311
|
+
{ name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true },
|
|
312
|
+
{ type: 'row', fields: [{ name: 'amount', type: 'number', required: true, admin: { width: '33%' } }, { name: 'currency', type: 'text', required: true, admin: { width: '33%' } }, { name: 'paidAt', type: 'date', required: true, index: true, admin: { width: '34%' } }] },
|
|
313
|
+
{ name: 'invoiceId', type: 'text', required: true, unique: true },
|
|
314
|
+
{ name: 'tier', type: 'relationship', relationTo: o.tiers },
|
|
315
|
+
{ name: 'pledges', type: 'array', fields: [{ name: 'category', type: 'relationship', relationTo: o.categories }, { name: 'amount', type: 'number' }] },
|
|
316
|
+
],
|
|
317
|
+
timestamps: true,
|
|
318
|
+
};
|
|
319
|
+
}
|