@extantape/payload-plugin-membership 0.3.1 → 0.4.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/README.md +52 -4
- package/dist/api.d.ts +19 -3
- package/dist/api.js +55 -16
- package/dist/endpoints.js +7 -7
- package/dist/plugin.js +4 -0
- package/dist/types.d.ts +12 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,8 +7,8 @@ Patreon, or let members support **categories** with **their own amount** — or
|
|
|
7
7
|
> The automated tests run on Payload 3.94.2 with an in-memory MongoDB and a fake Stripe. CI runs them on
|
|
8
8
|
> Node 24. They call REST and GraphQL in-process, and include `@payloadcms/plugin-multi-tenant` 3.94.2.
|
|
9
9
|
> Not tested: real Stripe, the admin UI in a browser, REST or GraphQL through a running web server,
|
|
10
|
-
> databases other than MongoDB, Payload versions after 3.94.2, Node 22, Node 26.13.1 or newer, and upgrading a real
|
|
11
|
-
> database. You need Payload 3.94.2 or later, and Node ^22.23.5, ^24.22.3, or 26.13.1 or newer.
|
|
10
|
+
> databases other than MongoDB, Payload versions after 3.94.2, Node 22, Node 26.13.1 or newer, and upgrading a real
|
|
11
|
+
> database from an earlier version. You need Payload 3.94.2 or later, and Node ^22.23.5, ^24.22.3, or 26.13.1 or newer.
|
|
12
12
|
|
|
13
13
|
- **Tiers** (Patreon-style): fixed monthly and/or yearly prices, perks, colors. Drag-and-drop order.
|
|
14
14
|
- **Categories**: things members can choose to support (e.g. "Turtles", "North American turtles"),
|
|
@@ -33,7 +33,7 @@ Patreon, or let members support **categories** with **their own amount** — or
|
|
|
33
33
|
|
|
34
34
|
- **Sponsors** (`@extantape/payload-plugin-sponsors`): tick "Members are listed as sponsors" on a tier, and call Sponsors' `upsertListing()` and `retireListing()` from `onStatusChange`. Your site makes the call; neither plugin imports the other.
|
|
35
35
|
- **Roadmap** (`@extantape/payload-plugin-roadmap`): Roadmap's extra votes come from a number your site works out (`allocation.earned`), and a membership can be where they come from. There's no adapter for this. It's a few lines of your own code.
|
|
36
|
-
- **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them.
|
|
36
|
+
- **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them. See [Sites](#sites) for what `scopeOf` returns and how `getBackers` and `myMembership` take a site.
|
|
37
37
|
|
|
38
38
|
**Family.** Membership is in the Patronage family, with Sponsors, Backing, Credits, Printify and Roadmap. Backing and Credits are named but not built yet, and the families are a working draft that may change.
|
|
39
39
|
|
|
@@ -91,11 +91,29 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
|
|
|
91
91
|
| `webhookSecret` | | Signing secret of the webhook endpoint |
|
|
92
92
|
| `currency` | `usd` | |
|
|
93
93
|
| `publicURL` | `serverURL` | Origin for Stripe return links |
|
|
94
|
-
| `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request |
|
|
94
|
+
| `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request. Set both or neither. See [Sites](#sites) |
|
|
95
95
|
| `onPayment` | | Once per paid invoice |
|
|
96
96
|
| `onStatusChange` | | When a membership's status changes |
|
|
97
97
|
| `overrides` | | Adjust the generated collections |
|
|
98
98
|
|
|
99
|
+
## Sites
|
|
100
|
+
|
|
101
|
+
Leave out `scopeField` and `scopeOf` on a single site. For several sites, set both: the plugin
|
|
102
|
+
refuses to build with only one of them.
|
|
103
|
+
|
|
104
|
+
- `scopeOf(req)` returns the request's site id as a non-empty string. Anything else counts as no
|
|
105
|
+
site: `null`, an empty string, a number, or a throw. If your ids are numbers, return `String(id)`.
|
|
106
|
+
- With no site, checkout answers 404 (`Not found.`) before it reads anything or calls Stripe, and so
|
|
107
|
+
do the member endpoints. Server code calling `startCheckout` passes `scope` the same way.
|
|
108
|
+
- Each membership is saved with its site, and only tiers and categories of that site can be chosen,
|
|
109
|
+
at checkout and when the member changes plan. A tier or category with no site is never offered.
|
|
110
|
+
A membership with no site can't be changed (404) until it has one.
|
|
111
|
+
- `getBackers(payload, { scope })` lists one site's wall. `getBackers(payload, { allSites: true })`
|
|
112
|
+
lists every site's. Anything else throws, including both at once.
|
|
113
|
+
- `myMembership(payload, userId, scope)` needs the site too, and throws without it.
|
|
114
|
+
- `onPayment` and `onStatusChange` get the site as `scope` on `membership` and `payment`. It is `null`
|
|
115
|
+
on a single site and for a row with no site, so don't treat `null` as a site.
|
|
116
|
+
|
|
99
117
|
## Access
|
|
100
118
|
|
|
101
119
|
`canManage` decides everything a manager can do. It gets `{ req }` and answers one of three things:
|
|
@@ -232,6 +250,36 @@ Upgrading from 0.2.0, checks to run once from server code:
|
|
|
232
250
|
manager can't save such a category until its parent is cleared or moved into their scope, so fix
|
|
233
251
|
these from server code or as a manager of every row.
|
|
234
252
|
|
|
253
|
+
Upgrading, sites (only if you set `scopeField`):
|
|
254
|
+
|
|
255
|
+
1. Set `scopeOf` too, if you hadn't. Make sure it returns the site id as a string.
|
|
256
|
+
2. Pass a `scope` to every server call of `startCheckout` and `myMembership`. Pass `scope` or
|
|
257
|
+
`allSites: true` to every `getBackers` call.
|
|
258
|
+
3. Find memberships that have no site, from server code. With `tenant` as your `scopeField`:
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
const { docs } = await payload.find({
|
|
262
|
+
collection: 'memberships',
|
|
263
|
+
where: { or: [{ tenant: { exists: false } }, { tenant: { equals: null } }] },
|
|
264
|
+
depth: 0,
|
|
265
|
+
pagination: false,
|
|
266
|
+
overrideAccess: true,
|
|
267
|
+
})
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
For a text field, also look for an empty string. For each row, first try to give it the site its
|
|
271
|
+
tier or categories belong to, with
|
|
272
|
+
`payload.update({ collection: 'memberships', id, data: { tenant: siteId }, overrideAccess: true })`,
|
|
273
|
+
and its payments too if you added the field to them. If you can't, `cancelMembership(payload, id)`
|
|
274
|
+
ends it at the close of the paid period, with no refund. To stop it now or refund, do that in
|
|
275
|
+
Stripe. A member who joins again before then pays for both. A row with no site can't be managed by
|
|
276
|
+
the member from any site, and it isn't on any one site's backers wall (`allSites: true` still lists
|
|
277
|
+
it). A Checkout opened before the upgrade can still finish afterwards and activate a row with no
|
|
278
|
+
site, so run the query again a day later.
|
|
279
|
+
4. Give a site to any tier or category that has none, or it won't be offered.
|
|
280
|
+
5. Check: a checkout with no site answers 404 and creates nothing, a checkout on a site works, and the
|
|
281
|
+
query in step 3 finds nothing.
|
|
282
|
+
|
|
235
283
|
This version requires Payload 3.94.2 or later (peer range `^3.94.2`). Upgrade Payload before you
|
|
236
284
|
install it.
|
|
237
285
|
|
package/dist/api.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import { type Payload } from 'payload';
|
|
|
2
2
|
import type { Interval, ResolvedMembership, StripeEvent } from './types.js';
|
|
3
3
|
type Doc = Record<string, any>;
|
|
4
4
|
export declare const membershipOf: (payload: Payload) => ResolvedMembership;
|
|
5
|
+
/** A site id the plugin accepts: a string with something in it. Anything else is no site. */
|
|
6
|
+
export declare const knownScope: (v: unknown) => string | null;
|
|
5
7
|
/** What a member chooses: a tier, or amounts (cents per interval) for categories. */
|
|
6
8
|
export type Choice = {
|
|
7
9
|
tier?: string | null;
|
|
@@ -14,7 +16,9 @@ export type Choice = {
|
|
|
14
16
|
/**
|
|
15
17
|
* Starts a membership: validates the choice, records it as pending and opens
|
|
16
18
|
* Stripe Checkout (a subscription with the member's own amounts). Returns the
|
|
17
|
-
* Checkout URL; the webhook activates it once Stripe confirms.
|
|
19
|
+
* Checkout URL; the webhook activates it once Stripe confirms. With `scopeField`,
|
|
20
|
+
* `scope` must be the site's id as a non-empty string, or this answers 404
|
|
21
|
+
* before it reads anything or calls Stripe.
|
|
18
22
|
*/
|
|
19
23
|
export declare function startCheckout(payload: Payload, args: Choice & {
|
|
20
24
|
user: Doc;
|
|
@@ -29,7 +33,11 @@ export declare function startCheckout(payload: Payload, args: Choice & {
|
|
|
29
33
|
url: string;
|
|
30
34
|
membership: string;
|
|
31
35
|
}>;
|
|
32
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
|
|
38
|
+
* With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
|
|
39
|
+
* site can't be changed (404) until it is given one.
|
|
40
|
+
*/
|
|
33
41
|
export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
|
|
34
42
|
/** Cancels at the end of the paid period (the member keeps their perks until then). */
|
|
35
43
|
export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
|
|
@@ -52,14 +60,22 @@ export type BackerGroup<T> = {
|
|
|
52
60
|
* The backers wall: active members who chose to be shown, under their tier or
|
|
53
61
|
* under each category they support, A–Z within each (user decision for
|
|
54
62
|
* the original site). Groups follow the admin's (drag-and-drop) order.
|
|
63
|
+
*
|
|
64
|
+
* With `scopeField`, pass the site's id as `scope` for that site's wall, or `allSites: true` for
|
|
65
|
+
* every site's together. Anything else throws, so a wall never lists more than was asked for.
|
|
66
|
+
* Without `scopeField`, both are ignored.
|
|
55
67
|
*/
|
|
56
68
|
export declare function getBackers(payload: Payload, opts?: {
|
|
57
69
|
scope?: string | null;
|
|
70
|
+
allSites?: boolean;
|
|
58
71
|
locale?: string;
|
|
59
72
|
}): Promise<{
|
|
60
73
|
tiers: BackerGroup<Doc>[];
|
|
61
74
|
categories: BackerGroup<Doc>[];
|
|
62
75
|
}>;
|
|
63
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* The signed-in member's current membership in a scope (for account pages). With `scopeField`, `scope`
|
|
78
|
+
* must be the site's id as a non-empty string, or this throws.
|
|
79
|
+
*/
|
|
64
80
|
export declare function myMembership(payload: Payload, userId: string, scope?: string | null): Promise<Doc | null>;
|
|
65
81
|
export {};
|
package/dist/api.js
CHANGED
|
@@ -3,6 +3,18 @@ import { checkoutAllowed } from './access.js';
|
|
|
3
3
|
const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
|
|
4
4
|
const ctx = { membershipSync: true };
|
|
5
5
|
export const membershipOf = (payload) => payload.config.custom?.membership;
|
|
6
|
+
/** A site id the plugin accepts: a string with something in it. Anything else is no site. */
|
|
7
|
+
export const knownScope = (v) => (typeof v === 'string' && v.trim() !== '' ? v : null);
|
|
8
|
+
/** With `scopeField`, an unknown site is answered as if nothing were there: 404, before any lookup. */
|
|
9
|
+
const notFound = () => new APIError('Not found.', 404, undefined, true);
|
|
10
|
+
function requireScope(o, scope) {
|
|
11
|
+
if (!o.scopeField)
|
|
12
|
+
return null;
|
|
13
|
+
const known = knownScope(scope);
|
|
14
|
+
if (known === null)
|
|
15
|
+
throw notFound();
|
|
16
|
+
return known;
|
|
17
|
+
}
|
|
6
18
|
const stripeOf = (o) => {
|
|
7
19
|
const s = o.stripe();
|
|
8
20
|
if (!s)
|
|
@@ -13,7 +25,10 @@ const stripeOf = (o) => {
|
|
|
13
25
|
async function linesFor(payload, o, choice, scope) {
|
|
14
26
|
if (choice.interval !== 'month' && choice.interval !== 'year')
|
|
15
27
|
throw new APIError('Choose monthly or yearly.', 400, undefined, true);
|
|
16
|
-
|
|
28
|
+
// With `scopeField`, a row counts only when its own site is this exact site; a row with no site never does.
|
|
29
|
+
if (o.scopeField && knownScope(scope) === null)
|
|
30
|
+
throw notFound();
|
|
31
|
+
const inScope = (d) => !o.scopeField || (scope !== null && idOf(d[o.scopeField]) === scope);
|
|
17
32
|
if (choice.tier) {
|
|
18
33
|
const tier = (await payload.findByID({ collection: o.tiers, id: choice.tier, depth: 0, overrideAccess: true, disableErrors: true }));
|
|
19
34
|
const price = tier?.[choice.interval === 'month' ? 'monthly' : 'yearly'];
|
|
@@ -56,20 +71,22 @@ const priceData = (o, line, interval) => ({
|
|
|
56
71
|
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
72
|
/** Members in good standing (or still paying) block a second membership in the same scope. */
|
|
58
73
|
async function currentMembership(payload, o, userId, scope) {
|
|
59
|
-
const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField
|
|
74
|
+
const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField ? [{ [o.scopeField]: { equals: scope } }] : [])] };
|
|
60
75
|
return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
|
|
61
76
|
}
|
|
62
77
|
/**
|
|
63
78
|
* Starts a membership: validates the choice, records it as pending and opens
|
|
64
79
|
* Stripe Checkout (a subscription with the member's own amounts). Returns the
|
|
65
|
-
* Checkout URL; the webhook activates it once Stripe confirms.
|
|
80
|
+
* Checkout URL; the webhook activates it once Stripe confirms. With `scopeField`,
|
|
81
|
+
* `scope` must be the site's id as a non-empty string, or this answers 404
|
|
82
|
+
* before it reads anything or calls Stripe.
|
|
66
83
|
*/
|
|
67
84
|
export async function startCheckout(payload, args) {
|
|
68
85
|
const o = membershipOf(payload);
|
|
86
|
+
const scope = requireScope(o, args.scope);
|
|
69
87
|
if (!(await checkoutAllowed(o, payload)))
|
|
70
88
|
throw new APIError('Memberships are not available here yet.', 503, undefined, true);
|
|
71
89
|
const stripe = stripeOf(o);
|
|
72
|
-
const scope = args.scope ?? null;
|
|
73
90
|
if (await currentMembership(payload, o, String(args.user.id), scope))
|
|
74
91
|
throw new APIError('You already have a membership: change it instead.', 409, undefined, true);
|
|
75
92
|
const { kind, lines, tier, pledges } = await linesFor(payload, o, args, scope);
|
|
@@ -87,7 +104,7 @@ export async function startCheckout(payload, args) {
|
|
|
87
104
|
currency: o.currency,
|
|
88
105
|
status: 'pending',
|
|
89
106
|
wall: { show: Boolean(args.wall?.show), name: args.wall?.name?.trim().slice(0, 80) || null },
|
|
90
|
-
...(o.scopeField
|
|
107
|
+
...(o.scopeField ? { [o.scopeField]: scope } : {}),
|
|
91
108
|
},
|
|
92
109
|
overrideAccess: true,
|
|
93
110
|
context: ctx,
|
|
@@ -107,13 +124,17 @@ export async function startCheckout(payload, args) {
|
|
|
107
124
|
throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
|
|
108
125
|
return { url: session.url, membership: String(membership.id) };
|
|
109
126
|
}
|
|
110
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
|
|
129
|
+
* With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
|
|
130
|
+
* site can't be changed (404) until it is given one.
|
|
131
|
+
*/
|
|
111
132
|
export async function changeMembership(payload, membershipId, choice) {
|
|
112
133
|
const o = membershipOf(payload);
|
|
113
134
|
const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 1, overrideAccess: true }));
|
|
114
135
|
if (!m.stripe?.subscription || !['active', 'past_due'].includes(m.status))
|
|
115
136
|
throw new APIError('Only a running membership can be changed.', 409, undefined, true);
|
|
116
|
-
const scope = o.scopeField ? idOf(m[o.scopeField]) : null;
|
|
137
|
+
const scope = o.scopeField ? requireScope(o, idOf(m[o.scopeField])) : null;
|
|
117
138
|
const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
|
|
118
139
|
const stripe = stripeOf(o);
|
|
119
140
|
const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
|
|
@@ -148,8 +169,10 @@ export async function portalLink(payload, membershipId, returnURL) {
|
|
|
148
169
|
return (await stripeOf(o).billingPortal.sessions.create({ customer: m.stripe.customer, return_url: returnURL })).url;
|
|
149
170
|
}
|
|
150
171
|
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
|
|
172
|
+
const scopeOfRow = (o, m) => (o.scopeField ? knownScope(idOf(m[o.scopeField])) : null);
|
|
173
|
+
const recordOf = (o, m) => ({
|
|
152
174
|
id: String(m.id),
|
|
175
|
+
scope: scopeOfRow(o, m),
|
|
153
176
|
user: String(idOf(m.user)),
|
|
154
177
|
kind: m.kind,
|
|
155
178
|
tier: idOf(m.tier),
|
|
@@ -162,7 +185,7 @@ const recordOf = (m) => ({
|
|
|
162
185
|
async function setMembership(payload, o, m, data) {
|
|
163
186
|
const updated = (await payload.update({ collection: o.memberships, id: m.id, data: data, overrideAccess: true, depth: 0, context: ctx }));
|
|
164
187
|
if (data.status && data.status !== m.status && o.onStatusChange)
|
|
165
|
-
await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
|
|
188
|
+
await o.onStatusChange({ payload, membership: recordOf(o, updated), previous: m.status ?? null });
|
|
166
189
|
return updated;
|
|
167
190
|
}
|
|
168
191
|
async function findBy(payload, o, where) {
|
|
@@ -211,7 +234,7 @@ export async function handleStripeEvent(payload, event) {
|
|
|
211
234
|
try {
|
|
212
235
|
payment = (await payload.create({
|
|
213
236
|
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
|
|
237
|
+
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, ...(scopeOfRow(o, m) !== null ? { [o.scopeField]: idOf(m[o.scopeField]) } : {}) },
|
|
215
238
|
overrideAccess: true,
|
|
216
239
|
context: ctx,
|
|
217
240
|
// One document, kept unique by the invoiceId index; no transaction needed. Inside one,
|
|
@@ -240,12 +263,12 @@ export async function handleStripeEvent(payload, event) {
|
|
|
240
263
|
(await payload.db.updateOne({ collection: memberships, where: { and: [{ id: { equals: m.id } }, { status: { not_equals: 'active' } }] }, data: { status: 'active' } }));
|
|
241
264
|
const updated = (await payload.findByID({ collection: memberships, id: m.id, depth: 0, overrideAccess: true }));
|
|
242
265
|
if (activated && o.onStatusChange)
|
|
243
|
-
await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
|
|
266
|
+
await o.onStatusChange({ payload, membership: recordOf(o, updated), previous: m.status ?? null });
|
|
244
267
|
if (o.onPayment)
|
|
245
268
|
await o.onPayment({
|
|
246
269
|
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) },
|
|
270
|
+
membership: recordOf(o, updated),
|
|
271
|
+
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), scope: scopeOfRow(o, m) },
|
|
249
272
|
});
|
|
250
273
|
return 'handled';
|
|
251
274
|
}
|
|
@@ -281,10 +304,21 @@ export async function handleStripeEvent(payload, event) {
|
|
|
281
304
|
* The backers wall: active members who chose to be shown, under their tier or
|
|
282
305
|
* under each category they support, A–Z within each (user decision for
|
|
283
306
|
* the original site). Groups follow the admin's (drag-and-drop) order.
|
|
307
|
+
*
|
|
308
|
+
* With `scopeField`, pass the site's id as `scope` for that site's wall, or `allSites: true` for
|
|
309
|
+
* every site's together. Anything else throws, so a wall never lists more than was asked for.
|
|
310
|
+
* Without `scopeField`, both are ignored.
|
|
284
311
|
*/
|
|
285
312
|
export async function getBackers(payload, opts = {}) {
|
|
286
313
|
const o = membershipOf(payload);
|
|
287
|
-
|
|
314
|
+
let scope = null;
|
|
315
|
+
if (o.scopeField) {
|
|
316
|
+
scope = knownScope(opts.scope);
|
|
317
|
+
const allSites = opts.allSites === true;
|
|
318
|
+
if (allSites === (scope !== null))
|
|
319
|
+
throw new Error('getBackers needs either a scope (the site’s id as a non-empty string) or allSites: true, not both, when scopeField is set.');
|
|
320
|
+
}
|
|
321
|
+
const scoped = (w) => ({ and: [...w, ...(o.scopeField && scope !== null ? [{ [o.scopeField]: { equals: scope } }] : [])] });
|
|
288
322
|
const read = { depth: 0, pagination: false, overrideAccess: true, locale: opts.locale };
|
|
289
323
|
const [members, tiers, categories] = await Promise.all([
|
|
290
324
|
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 }),
|
|
@@ -311,9 +345,14 @@ export async function getBackers(payload, opts = {}) {
|
|
|
311
345
|
categories: categories.docs.map((c) => ({ group: c, backers: az(byCategory.get(String(c.id)) ?? []) })).filter((g) => g.backers.length),
|
|
312
346
|
};
|
|
313
347
|
}
|
|
314
|
-
/**
|
|
348
|
+
/**
|
|
349
|
+
* The signed-in member's current membership in a scope (for account pages). With `scopeField`, `scope`
|
|
350
|
+
* must be the site's id as a non-empty string, or this throws.
|
|
351
|
+
*/
|
|
315
352
|
export async function myMembership(payload, userId, scope = null) {
|
|
316
353
|
const o = membershipOf(payload);
|
|
317
|
-
|
|
354
|
+
if (o.scopeField && knownScope(scope) === null)
|
|
355
|
+
throw new Error('myMembership needs a scope (the site’s id as a non-empty string) when scopeField is set.');
|
|
356
|
+
const where = { and: [{ user: { equals: userId } }, { status: { not_equals: 'pending' } }, ...(o.scopeField ? [{ [o.scopeField]: { equals: scope } }] : [])] };
|
|
318
357
|
return (await payload.find({ collection: o.memberships, where, sort: '-createdAt', limit: 1, depth: 1, overrideAccess: true })).docs[0] ?? null;
|
|
319
358
|
}
|
package/dist/endpoints.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { managerReaches } from './access.js';
|
|
2
|
-
import { cancelMembership, changeMembership, handleStripeEvent, membershipOf, portalLink, startCheckout } from './api.js';
|
|
2
|
+
import { cancelMembership, changeMembership, handleStripeEvent, knownScope, membershipOf, portalLink, startCheckout } from './api.js';
|
|
3
3
|
const json = (body, status = 200) => Response.json(body, { status });
|
|
4
4
|
const fail = (err) => {
|
|
5
5
|
const e = err;
|
|
@@ -10,16 +10,16 @@ const origin = (req) => membershipOf(req.payload).publicURL ?? req.payload.confi
|
|
|
10
10
|
/** Same-site paths only. */
|
|
11
11
|
const path = (p, fallback) => (typeof p === 'string' && /^\/(?!\/)/.test(p) ? p : fallback);
|
|
12
12
|
/**
|
|
13
|
-
* The request's site, from `scopeOf
|
|
14
|
-
* refuses as it would for an unknown site. Only the
|
|
15
|
-
* carry the host's request details.
|
|
13
|
+
* The request's site, from `scopeOf`: a non-empty string, or `null` for anything else. A throw or
|
|
14
|
+
* rejection counts as no site, so the caller refuses as it would for an unknown site. Only the
|
|
15
|
+
* error's name is logged: its message could carry the host's request details.
|
|
16
16
|
*/
|
|
17
17
|
async function siteOf(req) {
|
|
18
18
|
const o = membershipOf(req.payload);
|
|
19
19
|
if (!o.scopeOf)
|
|
20
20
|
return null;
|
|
21
21
|
try {
|
|
22
|
-
return await o.scopeOf(req);
|
|
22
|
+
return knownScope(await o.scopeOf(req));
|
|
23
23
|
}
|
|
24
24
|
catch (err) {
|
|
25
25
|
req.payload.logger.warn(`Membership: scopeOf failed (${err instanceof Error ? err.name : typeof err}); treated as no site`);
|
|
@@ -42,9 +42,9 @@ async function ownMembership(req, { memberOnly = false } = {}) {
|
|
|
42
42
|
const m = await req.payload.findByID({ collection, id, depth: 0, overrideAccess: true, disableErrors: true });
|
|
43
43
|
if (!m)
|
|
44
44
|
return null;
|
|
45
|
-
if (o.scopeField
|
|
45
|
+
if (o.scopeField) {
|
|
46
46
|
const here = await siteOf(req);
|
|
47
|
-
if (here
|
|
47
|
+
if (here === null || idOf(m[o.scopeField]) !== here)
|
|
48
48
|
return null;
|
|
49
49
|
}
|
|
50
50
|
if (idOf(m.user) === String(req.user.id))
|
package/dist/plugin.js
CHANGED
|
@@ -9,6 +9,10 @@ import { cancelEndpoint, changeEndpoint, checkoutEndpoint, portalEndpoint, wallE
|
|
|
9
9
|
* `getBackers` builds an opt-in backers wall, A–Z within each tier/category.
|
|
10
10
|
*/
|
|
11
11
|
export const membershipPlugin = (options = {}) => (config) => {
|
|
12
|
+
const hasField = typeof options.scopeField === 'string' && options.scopeField !== '';
|
|
13
|
+
const hasOf = typeof options.scopeOf === 'function';
|
|
14
|
+
if ((options.scopeField !== undefined || options.scopeOf !== undefined) && !(hasField && hasOf))
|
|
15
|
+
throw new Error('Membership: set scopeField and scopeOf together (a field name and a function), or neither.');
|
|
12
16
|
let client = options.stripe;
|
|
13
17
|
const o = {
|
|
14
18
|
tiers: options.slugs?.tiers ?? 'membership-tiers',
|
package/dist/types.d.ts
CHANGED
|
@@ -24,9 +24,13 @@ export type PaymentRecord = {
|
|
|
24
24
|
amount: number;
|
|
25
25
|
}[];
|
|
26
26
|
tier: string | null;
|
|
27
|
+
/** The membership's site (its `scopeField`), or `null` without `scopeField` or when the row has none. */
|
|
28
|
+
scope: string | null;
|
|
27
29
|
};
|
|
28
30
|
export type MembershipRecord = {
|
|
29
31
|
id: string;
|
|
32
|
+
/** The membership's site (its `scopeField`), or `null` without `scopeField` or when the row has none. */
|
|
33
|
+
scope: string | null;
|
|
30
34
|
user: string;
|
|
31
35
|
kind: 'tier' | 'pledge';
|
|
32
36
|
tier: string | null;
|
|
@@ -118,9 +122,15 @@ export type MembershipPluginOptions = {
|
|
|
118
122
|
currency?: string;
|
|
119
123
|
/** Public origin for Stripe return links. Default: `serverURL`. */
|
|
120
124
|
publicURL?: string;
|
|
121
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* A field that separates owners (e.g. `tenant`): new tiers/categories go A–Z among their own; memberships are per scope.
|
|
127
|
+
* Set it together with `scopeOf`, or neither: the plugin refuses to build with only one.
|
|
128
|
+
*/
|
|
122
129
|
scopeField?: string;
|
|
123
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* The scope of a request (e.g. the site of the request's host) as the site's id in a non-empty string, stored on new
|
|
132
|
+
* memberships. Anything else (`null`, an empty string, a number, a throw) is no site: checkout and the member endpoints answer 404.
|
|
133
|
+
*/
|
|
124
134
|
scopeOf?: (req: PayloadRequest) => Promise<string | null> | string | null;
|
|
125
135
|
/** Called once per paid invoice (idempotent: never twice for the same invoice). Award perks, votes, credits here. */
|
|
126
136
|
onPayment?: (args: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-membership",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Memberships for Payload: Patreon-style tiers or pick-your-own-amount pledges to categories, billed as Stripe subscriptions, with a backers wall and hooks for perks.",
|
|
5
5
|
"homepage": "https://github.com/ExtantApe/payload-plugin-membership#readme",
|
|
6
6
|
"bugs": {
|