@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EXTANT APE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,168 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-plugin-membership
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Memberships for [Payload](https://payloadcms.com), billed as Stripe subscriptions. Run it like
|
|
4
|
+
Patreon, or let members support **categories** with **their own amount** — or both.
|
|
5
|
+
|
|
6
|
+
- **Tiers** (Patreon-style): fixed monthly and/or yearly prices, perks, colors. Drag-and-drop order.
|
|
7
|
+
- **Categories**: things members can choose to support (e.g. "Turtles", "North American turtles"),
|
|
8
|
+
nestable, with a minimum amount and an optional **earmarked** flag (otherwise the category is the
|
|
9
|
+
member's preference). New categories go in A–Z; drag to reorder. Add your own fields to tie them to
|
|
10
|
+
anything (taxa, regions, projects…).
|
|
11
|
+
- **Memberships**: one running membership per member (per scope); a tier, or pledges split across
|
|
12
|
+
categories. Monthly or yearly. Members change, cancel (at the end of the paid period) or open Stripe's
|
|
13
|
+
customer portal.
|
|
14
|
+
- **Payments ledger**: every paid invoice recorded once (idempotent webhooks). `onPayment` runs once per
|
|
15
|
+
invoice: award perks, votes, credits, receipts.
|
|
16
|
+
- **Backers wall**: opt-in only, with the name the member chooses; listed under their tier or under each
|
|
17
|
+
category they support, **A–Z within each group**.
|
|
18
|
+
- **Works with** [`@extantape/payload-plugin-sponsors`](https://www.npmjs.com/package/@extantape/payload-plugin-sponsors):
|
|
19
|
+
mark a tier "Members are listed as sponsors" and call `upsertListing`/`retireListing` from `onStatusChange`.
|
|
20
|
+
|
|
21
|
+
## On its own, and with others
|
|
22
|
+
|
|
23
|
+
**On its own.** Membership needs a Stripe account (a secret key and a webhook) and an auth collection for members. It doesn't import any other plugin. Perks, votes and credits are whatever your own `onPayment` and `onStatusChange` do.
|
|
24
|
+
|
|
25
|
+
**Works with:**
|
|
26
|
+
|
|
27
|
+
- **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.
|
|
28
|
+
- **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.
|
|
29
|
+
- **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. Pass `scope` to `getBackers`, or it lists every site.
|
|
30
|
+
|
|
31
|
+
**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.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install @extantape/payload-plugin-membership
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { membershipPlugin } from '@extantape/payload-plugin-membership'
|
|
41
|
+
|
|
42
|
+
export default buildConfig({
|
|
43
|
+
plugins: [
|
|
44
|
+
membershipPlugin({
|
|
45
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
46
|
+
webhookSecret: process.env.STRIPE_MEMBERSHIP_WEBHOOK_SECRET,
|
|
47
|
+
canManage: ({ req }) => req.user?.role === 'admin',
|
|
48
|
+
onPayment: async ({ payload, payment, membership }) => {
|
|
49
|
+
// e.g. thank the member, grant perks
|
|
50
|
+
},
|
|
51
|
+
}),
|
|
52
|
+
],
|
|
53
|
+
})
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-webhook` for
|
|
57
|
+
`checkout.session.completed`, `invoice.paid`, `invoice.payment_failed`,
|
|
58
|
+
`customer.subscription.updated` and `customer.subscription.deleted`.
|
|
59
|
+
|
|
60
|
+
## Endpoints (signed-in members)
|
|
61
|
+
|
|
62
|
+
| Endpoint | Body | Result |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `POST /api/memberships/checkout` | `{ tier }` or `{ pledges: [{ category, amount }] }`, `interval` (`month`/`year`), `wall?: { show, name }`, `successPath?`, `cancelPath?` | `{ url }` of Stripe Checkout |
|
|
65
|
+
| `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
|
|
66
|
+
| `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
|
|
67
|
+
| `POST /api/memberships/:id/portal` | `{ returnPath? }` | `{ url }` of Stripe's customer portal |
|
|
68
|
+
| `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice. A manager may only send `show: false` |
|
|
69
|
+
|
|
70
|
+
Amounts are in cents. Server code can call `startCheckout`, `changeMembership`, `cancelMembership`,
|
|
71
|
+
`portalLink`, `myMembership` and `getBackers` directly.
|
|
72
|
+
|
|
73
|
+
## Options
|
|
74
|
+
|
|
75
|
+
| Option | Default | |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `slugs` | `membership-tiers`, `membership-categories`, `memberships`, `membership-payments` | |
|
|
78
|
+
| `users` | `admin.user` | The members' auth collection |
|
|
79
|
+
| `canManage` | nobody | Who manages tiers, categories and memberships in the admin: `true`, or a `Where` for one site's rows. See [Access](#access) |
|
|
80
|
+
| `canCheckout` | always | E.g. off in development. Only `true` allows a checkout |
|
|
81
|
+
| `stripeSecretKey` / `stripe` | | Key, or a ready client (tests) |
|
|
82
|
+
| `webhookSecret` | | Signing secret of the webhook endpoint |
|
|
83
|
+
| `currency` | `usd` | |
|
|
84
|
+
| `publicURL` | `serverURL` | Origin for Stripe return links |
|
|
85
|
+
| `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request |
|
|
86
|
+
| `onPayment` | | Once per paid invoice |
|
|
87
|
+
| `onStatusChange` | | When a membership's status changes |
|
|
88
|
+
| `overrides` | | Adjust the generated collections |
|
|
89
|
+
|
|
90
|
+
## Access
|
|
91
|
+
|
|
92
|
+
`canManage` decides everything a manager can do. It gets `{ req }` and answers one of three things:
|
|
93
|
+
|
|
94
|
+
- `true`: a manager of every row.
|
|
95
|
+
- A `Where`, such as `{ tenant: { equals: siteId } }`: a manager of only the rows it matches. Write it
|
|
96
|
+
against the memberships collection and the `scopeField` of tiers and categories. For payments the
|
|
97
|
+
plugin applies it through each payment's `membership`.
|
|
98
|
+
- Anything else is no: `false`, `null`, `0`, `''`, `1`, `'yes'`, an array, an empty `{}` or `{ and: [] }`,
|
|
99
|
+
a field with no operator, an operator Payload doesn't have or the plugin doesn't take (a typo such as
|
|
100
|
+
`equal` included), a value that would match every row (`like: ''`, `contains: ''`, `not_in: []`,
|
|
101
|
+
`all: []`), a query that doesn't run against the memberships collection (an unknown field), or an
|
|
102
|
+
error thrown or rejected. The request is refused cleanly, never a 500. An empty `{}` would match
|
|
103
|
+
every row, so it is a no. Return `true` to mean all. The accepted operators are `equals`,
|
|
104
|
+
`not_equals`, `in`, `not_in`, `all`, `exists`, `greater_than`, `greater_than_equal`, `less_than`,
|
|
105
|
+
`less_than_equal`, `like` and `contains`. `in: []` is accepted and matches nothing.
|
|
106
|
+
|
|
107
|
+
Nobody who isn't signed in is a manager, whatever `canManage` says.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
canManage: ({ req }) => {
|
|
111
|
+
const user = req.user as { role?: string; site?: string } | null
|
|
112
|
+
if (user?.role === 'admin') return true
|
|
113
|
+
if (user?.role === 'manager' && user.site) return { site: { equals: user.site } }
|
|
114
|
+
return false
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
A manager limited by a `Where` reaches only the matching memberships, payments, tiers and categories:
|
|
119
|
+
list, read, edit, delete, REST and GraphQL alike, and the endpoints below. A new tier or category
|
|
120
|
+
must match the `Where` in its own data. The plugin checks `equals`, `not_equals`, `in`, `not_in`,
|
|
121
|
+
`exists`, `and` and `or` there; any other operator is a no for a create. An update that names a
|
|
122
|
+
field your `Where` uses is checked the same way, on the stored row with the new data merged over it, so
|
|
123
|
+
a limited manager can't move a row out of their scope or into another one. An update that leaves those
|
|
124
|
+
fields alone isn't checked again.
|
|
125
|
+
|
|
126
|
+
`notes`, `stripe` and `stripeProduct` are judged row by row with the same answer, so a manager of
|
|
127
|
+
site A never reads site B's notes or Stripe ids, even in a list that includes site B's rows (for
|
|
128
|
+
example a membership they hold as a member there).
|
|
129
|
+
|
|
130
|
+
| Where | A manager | A signed-in member | Signed out |
|
|
131
|
+
|---|---|---|---|
|
|
132
|
+
| Tiers, categories | Reads; creates, edits, deletes within their scope | Reads | Reads |
|
|
133
|
+
| Their `stripeProduct` (field) | Reads and writes within their scope | Never sees it | Never sees it |
|
|
134
|
+
| Memberships | Reads and edits within their scope, deletes within their scope | Reads their own | Nothing |
|
|
135
|
+
| A membership's `stripe` and `notes` (fields) | Reads and writes within their scope | Never sees them | Nothing |
|
|
136
|
+
| Payments | Reads and deletes within their scope | Reads their own | Nothing |
|
|
137
|
+
| `cancel` endpoint | A membership within their scope, on this request's site | Their own | 404 |
|
|
138
|
+
| `wall` endpoint | Only to hide (`show: false`), within their scope | Their own, show and name | 404 |
|
|
139
|
+
| `change`, `portal` endpoints | Never | Their own | 404 |
|
|
140
|
+
|
|
141
|
+
Only the member changes their own plan, opens their own Stripe billing portal, shows themselves on the
|
|
142
|
+
backers wall or sets the wall name. A manager, even one who manages everything, gets a 404 on `change`
|
|
143
|
+
and `portal`, and may only hide a wall entry (`show: false`, for an offensive name or a takedown
|
|
144
|
+
request). Managers keep `cancel`. (Decided 2026-11-23.)
|
|
145
|
+
|
|
146
|
+
This is enforced in field access too, not just in the endpoints, so editing a membership through
|
|
147
|
+
Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
|
|
148
|
+
`kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
|
|
149
|
+
`stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
|
|
150
|
+
Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
|
|
151
|
+
set a category's `parent` only to a category in their scope.
|
|
152
|
+
|
|
153
|
+
Nobody creates memberships or payments directly: checkout and Stripe do. The member endpoints answer
|
|
154
|
+
404, not 403, to anyone who may not use them, so they don't say whether a membership exists.
|
|
155
|
+
|
|
156
|
+
Memberships' and payments' read access returns a query for members: the plugin's own "your rows"
|
|
157
|
+
filter. A manager's query comes only from `canManage`, and only when it passes the checks above.
|
|
158
|
+
`canCheckout` follows the exact-`true` rule: only `true` lets a checkout start, and anything else,
|
|
159
|
+
an error included, refuses it with "Memberships are not available here yet." (503).
|
|
160
|
+
|
|
161
|
+
Upgrading: a `canManage` that returned `true` or `false` works as before. One that returned an object
|
|
162
|
+
(it was a no) now has that object used as a query, so return `false` if you meant no.
|
|
163
|
+
|
|
164
|
+
`overrides` can change a collection's `access`; if you do, your rules replace these.
|
|
165
|
+
|
|
166
|
+
## License
|
|
167
|
+
|
|
168
|
+
MIT
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest, Where } from 'payload';
|
|
2
|
+
import type { ResolvedMembership } from './types.js';
|
|
3
|
+
/** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
|
|
4
|
+
export declare function exactlyTrue(check: () => unknown): Promise<boolean>;
|
|
5
|
+
/**
|
|
6
|
+
* A usable query: a plain object with at least one key, where `and`/`or` hold non-empty lists of
|
|
7
|
+
* usable queries and every field key holds a non-empty plain object of known operators with
|
|
8
|
+
* sensible values. `{}` matches every row, so it is not usable: a host that means "all" returns `true`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function usableWhere(w: unknown, depth?: number): w is Where;
|
|
11
|
+
/**
|
|
12
|
+
* What a manager may reach: `true` (everything), a query (only the rows it matches), or `null` (nothing).
|
|
13
|
+
* Only an exact `true` or a usable query counts, and a query must also run against the memberships
|
|
14
|
+
* collection (an unknown field makes it a no). Everything else, a throw or rejection included,
|
|
15
|
+
* and anyone not signed in, is `null`.
|
|
16
|
+
*/
|
|
17
|
+
export type ManagerScope = true | Where | null;
|
|
18
|
+
export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<ManagerScope>;
|
|
19
|
+
/** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
|
|
20
|
+
export declare function isManager(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<boolean>;
|
|
21
|
+
/** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
|
|
22
|
+
export declare function viaMembership(where: Where): Where;
|
|
23
|
+
/**
|
|
24
|
+
* Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
|
|
25
|
+
* `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
|
|
26
|
+
*/
|
|
27
|
+
export declare function matchesWhere(where: Where, data: Record<string, unknown> | undefined): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Whether this manager may reach one row: `true` always, a query only when it matches that row
|
|
30
|
+
* (checked against the database), nobody else. The answer is kept for the request.
|
|
31
|
+
*/
|
|
32
|
+
export declare function managerReaches(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, collection: string, id: unknown, via?: (w: Where) => Where): Promise<boolean>;
|
|
33
|
+
/** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
|
|
34
|
+
export declare const checkoutAllowed: (o: Pick<ResolvedMembership, "canCheckout">, payload: Payload) => Promise<boolean>;
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
|
|
2
|
+
export async function exactlyTrue(check) {
|
|
3
|
+
try {
|
|
4
|
+
return (await check()) === true;
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const isPlain = (v) => {
|
|
11
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
12
|
+
return false;
|
|
13
|
+
const proto = Object.getPrototypeOf(v);
|
|
14
|
+
return proto === Object.prototype || proto === null;
|
|
15
|
+
};
|
|
16
|
+
const scalar = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v);
|
|
17
|
+
const scalars = (v, minimum) => Array.isArray(v) && v.length >= minimum && v.every(scalar);
|
|
18
|
+
const nonEmptyText = (v) => typeof v === 'string' && v.length > 0;
|
|
19
|
+
const number = (v) => typeof v === 'number' || typeof v === 'string';
|
|
20
|
+
/**
|
|
21
|
+
* The operators the plugin accepts, each with a check on its value. An unknown operator (a typo
|
|
22
|
+
* such as `equal`) is refused rather than ignored, because Payload ignores some unknown operators
|
|
23
|
+
* on writes. Values that would match every row, such as an empty `like` or an empty `not_in`, are refused.
|
|
24
|
+
*/
|
|
25
|
+
const OPERATORS = {
|
|
26
|
+
equals: scalar,
|
|
27
|
+
not_equals: scalar,
|
|
28
|
+
in: (v) => scalars(v, 0), // an empty list matches nothing
|
|
29
|
+
not_in: (v) => scalars(v, 1),
|
|
30
|
+
all: (v) => scalars(v, 1),
|
|
31
|
+
exists: (v) => typeof v === 'boolean',
|
|
32
|
+
greater_than: number,
|
|
33
|
+
greater_than_equal: number,
|
|
34
|
+
less_than: number,
|
|
35
|
+
less_than_equal: number,
|
|
36
|
+
like: nonEmptyText,
|
|
37
|
+
contains: nonEmptyText,
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* A usable query: a plain object with at least one key, where `and`/`or` hold non-empty lists of
|
|
41
|
+
* usable queries and every field key holds a non-empty plain object of known operators with
|
|
42
|
+
* sensible values. `{}` matches every row, so it is not usable: a host that means "all" returns `true`.
|
|
43
|
+
*/
|
|
44
|
+
export function usableWhere(w, depth = 0) {
|
|
45
|
+
if (!isPlain(w) || depth > 8)
|
|
46
|
+
return false;
|
|
47
|
+
const keys = Object.keys(w);
|
|
48
|
+
if (!keys.length)
|
|
49
|
+
return false;
|
|
50
|
+
return keys.every((k) => {
|
|
51
|
+
const v = w[k];
|
|
52
|
+
if (k === 'and' || k === 'or')
|
|
53
|
+
return Array.isArray(v) && v.length > 0 && v.every((x) => usableWhere(x, depth + 1));
|
|
54
|
+
if (!isPlain(v))
|
|
55
|
+
return false;
|
|
56
|
+
const ops = Object.entries(v);
|
|
57
|
+
return ops.length > 0 && ops.every(([op, arg]) => Object.hasOwn(OPERATORS, op) && OPERATORS[op](arg));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
export async function managerScope(o, req) {
|
|
61
|
+
if (!req.user)
|
|
62
|
+
return null;
|
|
63
|
+
try {
|
|
64
|
+
const answer = await o.canManage({ req });
|
|
65
|
+
if (answer === true)
|
|
66
|
+
return true;
|
|
67
|
+
if (!usableWhere(answer))
|
|
68
|
+
return null;
|
|
69
|
+
const checked = (req.context.membershipWhereChecked ??= new Map());
|
|
70
|
+
const key = JSON.stringify(answer);
|
|
71
|
+
let ok = checked.get(key);
|
|
72
|
+
if (ok === undefined) {
|
|
73
|
+
try {
|
|
74
|
+
await req.payload.count({ collection: o.memberships, where: answer, overrideAccess: true, req });
|
|
75
|
+
ok = true;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
ok = false;
|
|
79
|
+
}
|
|
80
|
+
checked.set(key, ok);
|
|
81
|
+
}
|
|
82
|
+
return ok ? answer : null;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
|
|
89
|
+
export async function isManager(o, req) {
|
|
90
|
+
return (await managerScope(o, req)) !== null;
|
|
91
|
+
}
|
|
92
|
+
/** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
|
|
93
|
+
export function viaMembership(where) {
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const [k, v] of Object.entries(where)) {
|
|
96
|
+
if (k === 'and' || k === 'or')
|
|
97
|
+
out[k] = v.map(viaMembership);
|
|
98
|
+
else
|
|
99
|
+
out[k === 'id' ? 'membership' : `membership.${k}`] = v;
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
const idOf = (v) => (v && typeof v === 'object' && 'id' in v ? v.id : v);
|
|
104
|
+
const same = (a, b) => a != null && b != null && String(idOf(a)) === String(idOf(b));
|
|
105
|
+
/**
|
|
106
|
+
* Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
|
|
107
|
+
* `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
|
|
108
|
+
*/
|
|
109
|
+
export function matchesWhere(where, data) {
|
|
110
|
+
if (!data)
|
|
111
|
+
return false;
|
|
112
|
+
return Object.entries(where).every(([k, v]) => {
|
|
113
|
+
if (k === 'and')
|
|
114
|
+
return v.every((x) => matchesWhere(x, data));
|
|
115
|
+
if (k === 'or')
|
|
116
|
+
return v.some((x) => matchesWhere(x, data));
|
|
117
|
+
const value = data[k];
|
|
118
|
+
return Object.entries(v).every(([op, arg]) => {
|
|
119
|
+
switch (op) {
|
|
120
|
+
case 'equals':
|
|
121
|
+
return same(value, arg);
|
|
122
|
+
case 'not_equals':
|
|
123
|
+
return value != null && !same(value, arg);
|
|
124
|
+
case 'in':
|
|
125
|
+
return Array.isArray(arg) && arg.some((a) => same(value, a));
|
|
126
|
+
case 'not_in':
|
|
127
|
+
return value != null && Array.isArray(arg) && !arg.some((a) => same(value, a));
|
|
128
|
+
case 'exists':
|
|
129
|
+
return (value != null) === Boolean(arg);
|
|
130
|
+
default:
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Whether this manager may reach one row: `true` always, a query only when it matches that row
|
|
138
|
+
* (checked against the database), nobody else. The answer is kept for the request.
|
|
139
|
+
*/
|
|
140
|
+
export async function managerReaches(o, req, collection, id, via = (w) => w) {
|
|
141
|
+
const scope = await managerScope(o, req);
|
|
142
|
+
if (scope === true)
|
|
143
|
+
return true;
|
|
144
|
+
if (!scope || id == null || id === '')
|
|
145
|
+
return false;
|
|
146
|
+
const cache = (req.context.membershipReach ??= new Map());
|
|
147
|
+
const key = `${collection}:${String(id)}:${JSON.stringify(scope)}`;
|
|
148
|
+
const known = cache.get(key);
|
|
149
|
+
if (known !== undefined)
|
|
150
|
+
return known;
|
|
151
|
+
let reached = false;
|
|
152
|
+
try {
|
|
153
|
+
const found = await req.payload.count({
|
|
154
|
+
collection: collection,
|
|
155
|
+
where: { and: [{ id: { equals: id } }, via(scope)] },
|
|
156
|
+
overrideAccess: true,
|
|
157
|
+
req,
|
|
158
|
+
});
|
|
159
|
+
reached = found.totalDocs > 0;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
reached = false;
|
|
163
|
+
}
|
|
164
|
+
cache.set(key, reached);
|
|
165
|
+
return reached;
|
|
166
|
+
}
|
|
167
|
+
/** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
|
|
168
|
+
export const checkoutAllowed = (o, payload) => o.canCheckout ? exactlyTrue(() => o.canCheckout({ payload })) : Promise.resolve(true);
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type Payload } from 'payload';
|
|
2
|
+
import type { Interval, ResolvedMembership, StripeEvent } from './types.js';
|
|
3
|
+
type Doc = Record<string, any>;
|
|
4
|
+
export declare const membershipOf: (payload: Payload) => ResolvedMembership;
|
|
5
|
+
/** What a member chooses: a tier, or amounts (cents per interval) for categories. */
|
|
6
|
+
export type Choice = {
|
|
7
|
+
tier?: string | null;
|
|
8
|
+
pledges?: {
|
|
9
|
+
category: string;
|
|
10
|
+
amount: number;
|
|
11
|
+
}[] | null;
|
|
12
|
+
interval: Interval;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Starts a membership: validates the choice, records it as pending and opens
|
|
16
|
+
* Stripe Checkout (a subscription with the member's own amounts). Returns the
|
|
17
|
+
* Checkout URL; the webhook activates it once Stripe confirms.
|
|
18
|
+
*/
|
|
19
|
+
export declare function startCheckout(payload: Payload, args: Choice & {
|
|
20
|
+
user: Doc;
|
|
21
|
+
successURL: string;
|
|
22
|
+
cancelURL: string;
|
|
23
|
+
scope?: string | null;
|
|
24
|
+
wall?: {
|
|
25
|
+
show?: boolean;
|
|
26
|
+
name?: string | null;
|
|
27
|
+
};
|
|
28
|
+
}): Promise<{
|
|
29
|
+
url: string;
|
|
30
|
+
membership: string;
|
|
31
|
+
}>;
|
|
32
|
+
/** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
|
|
33
|
+
export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
|
|
34
|
+
/** Cancels at the end of the paid period (the member keeps their perks until then). */
|
|
35
|
+
export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
|
|
36
|
+
/** Stripe's customer portal (payment method, invoices, cancel). */
|
|
37
|
+
export declare function portalLink(payload: Payload, membershipId: string, returnURL: string): Promise<string>;
|
|
38
|
+
/**
|
|
39
|
+
* Applies one Stripe webhook event. Safe to receive twice: payments are keyed
|
|
40
|
+
* by invoice, and status updates are idempotent.
|
|
41
|
+
*/
|
|
42
|
+
export declare function handleStripeEvent(payload: Payload, event: StripeEvent): Promise<'handled' | 'ignored'>;
|
|
43
|
+
export type Backer = {
|
|
44
|
+
name: string;
|
|
45
|
+
since: string | null;
|
|
46
|
+
};
|
|
47
|
+
export type BackerGroup<T> = {
|
|
48
|
+
group: T;
|
|
49
|
+
backers: Backer[];
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* The backers wall: active members who chose to be shown, under their tier or
|
|
53
|
+
* under each category they support, A–Z within each (user decision for
|
|
54
|
+
* the original site). Groups follow the admin's (drag-and-drop) order.
|
|
55
|
+
*/
|
|
56
|
+
export declare function getBackers(payload: Payload, opts?: {
|
|
57
|
+
scope?: string | null;
|
|
58
|
+
locale?: string;
|
|
59
|
+
}): Promise<{
|
|
60
|
+
tiers: BackerGroup<Doc>[];
|
|
61
|
+
categories: BackerGroup<Doc>[];
|
|
62
|
+
}>;
|
|
63
|
+
/** The signed-in member's current membership in a scope (for account pages). */
|
|
64
|
+
export declare function myMembership(payload: Payload, userId: string, scope?: string | null): Promise<Doc | null>;
|
|
65
|
+
export {};
|