@dappermountain/payload-plugin-achievements 0.5.0 → 0.6.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 +278 -234
- package/dist/catalog.d.ts +3 -0
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +8 -0
- package/dist/collections/Grants/hooks/afterGrantMutation.d.ts.map +1 -1
- package/dist/collections/Grants/hooks/afterGrantMutation.js +15 -0
- package/dist/collections/Logs/hooks/afterLogMutation.d.ts +4 -0
- package/dist/collections/Logs/hooks/afterLogMutation.d.ts.map +1 -0
- package/dist/collections/Logs/hooks/afterLogMutation.js +47 -0
- package/dist/collections/Logs/hooks/index.d.ts.map +1 -1
- package/dist/collections/Logs/hooks/index.js +3 -0
- package/dist/collections/Logs/index.js +1 -1
- package/dist/collections/Reactions/access/index.d.ts +12 -0
- package/dist/collections/Reactions/access/index.d.ts.map +1 -0
- package/dist/collections/Reactions/access/index.js +2 -0
- package/dist/collections/Reactions/index.d.ts +3 -0
- package/dist/collections/Reactions/index.d.ts.map +1 -0
- package/dist/collections/Reactions/index.js +97 -0
- package/dist/collections/fields/ruleFields.d.ts.map +1 -1
- package/dist/collections/fields/ruleFields.js +19 -0
- package/dist/collections/fields/whenSibling.d.ts +7 -0
- package/dist/collections/fields/whenSibling.d.ts.map +1 -0
- package/dist/collections/fields/whenSibling.js +21 -0
- package/dist/collections/index.d.ts.map +1 -1
- package/dist/collections/index.js +2 -0
- package/dist/collections/slugs.d.ts.map +1 -1
- package/dist/collections/slugs.js +1 -0
- package/dist/defaults.d.ts +10 -1
- package/dist/defaults.d.ts.map +1 -1
- package/dist/defaults.js +34 -5
- package/dist/extensions/actions.d.ts +8 -0
- package/dist/extensions/actions.d.ts.map +1 -0
- package/dist/extensions/actions.js +26 -0
- package/dist/extensions/registry.d.ts +2 -0
- package/dist/extensions/registry.d.ts.map +1 -1
- package/dist/extensions/registry.js +19 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +9 -3
- package/dist/services/achievement/builtInRules.d.ts.map +1 -1
- package/dist/services/achievement/builtInRules.js +29 -10
- package/dist/services/achievement/eventTypeRequiresActor.d.ts +1 -0
- package/dist/services/achievement/eventTypeRequiresActor.d.ts.map +1 -1
- package/dist/services/achievement/eventTypeRequiresActor.js +2 -0
- package/dist/services/achievement/grantSideEffects.d.ts +11 -0
- package/dist/services/achievement/grantSideEffects.d.ts.map +1 -1
- package/dist/services/achievement/grantSideEffects.js +32 -0
- package/dist/services/achievement/index.d.ts +3 -1
- package/dist/services/achievement/index.d.ts.map +1 -1
- package/dist/services/achievement/index.js +2 -1
- package/dist/services/achievement/runReactions.d.ts +20 -0
- package/dist/services/achievement/runReactions.d.ts.map +1 -0
- package/dist/services/achievement/runReactions.js +86 -0
- package/dist/types.d.ts +46 -6
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,171 +1,307 @@
|
|
|
1
1
|
# `@dappermountain/payload-plugin-achievements`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Achievements, ranks, points, and an activity log for Payload CMS — all configured in Admin.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
You describe what people can earn and what has to happen first. Your app records those happenings. The plugin derives the current rank and progress from that history, so the ladder stays in step with real activity.
|
|
6
6
|
|
|
7
|
-
##
|
|
7
|
+
## What you get
|
|
8
8
|
|
|
9
|
-
- **
|
|
10
|
-
- **Composable rules
|
|
11
|
-
- **Derived
|
|
12
|
-
- **Request
|
|
13
|
-
- **
|
|
14
|
-
- **
|
|
15
|
-
- **Host
|
|
9
|
+
- **A catalog in Admin.** Achievements, tiers, metrics, event types, and reactions. Editors change rules there.
|
|
10
|
+
- **Composable rules.** Nested all-of / any-of trees, plus your own leaf types.
|
|
11
|
+
- **Derived ranks.** Current tier and next-tier fill come from the same unlock rules.
|
|
12
|
+
- **Request and review.** Members can ask for an achievement; reviewers approve or reject. Composed achievements can grant themselves when their completion rules pass.
|
|
13
|
+
- **An activity log.** Grants, score changes, rank moves, and your own event kinds.
|
|
14
|
+
- **Optional multi-tenant scope.** Point `scope` at your tenants / workspaces / orgs collection.
|
|
15
|
+
- **Host hooks.** Prefixable slugs, collection overrides, a review policy you inject, and server helpers for trusted code.
|
|
16
16
|
|
|
17
17
|
## Requirements
|
|
18
18
|
|
|
19
19
|
- Payload `^3.89`
|
|
20
20
|
- `@payloadcms/ui` `^3.89`
|
|
21
21
|
- `@payloadcms/richtext-lexical` `^3.89`
|
|
22
|
+
- `lucide-react` `^0.543`
|
|
22
23
|
- React `^19`
|
|
23
24
|
|
|
24
25
|
## Install
|
|
25
26
|
|
|
26
|
-
Preferred package manager: **Bun**.
|
|
27
|
-
|
|
28
27
|
```bash
|
|
29
28
|
bun add @dappermountain/payload-plugin-achievements
|
|
30
29
|
```
|
|
31
30
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
Next.js hosts should list the package in `transpilePackages` so `'use client'` admin components compile. Host imports stay on the package name; relative `.js` specifiers are internal to this package.
|
|
31
|
+
`npm` and other clients work too. Next.js hosts should list the package in `transpilePackages` so the `'use client'` Admin fields compile.
|
|
35
32
|
|
|
36
|
-
##
|
|
33
|
+
## Wire it up
|
|
37
34
|
|
|
38
35
|
```ts
|
|
39
36
|
import { buildConfig } from 'payload'
|
|
40
37
|
import { achievementPlugin } from '@dappermountain/payload-plugin-achievements'
|
|
41
38
|
|
|
42
39
|
export default buildConfig({
|
|
43
|
-
// ...
|
|
44
40
|
plugins: [
|
|
45
41
|
achievementPlugin({
|
|
46
42
|
usersCollectionSlug: 'users',
|
|
47
|
-
canReview: (user, scopeId) =>
|
|
48
|
-
// Return true when this user may edit catalogs and approve requests
|
|
49
|
-
// for the given scope (or null for unscoped / global).
|
|
50
|
-
return Boolean(user?.roles?.includes('admin'))
|
|
51
|
-
},
|
|
52
|
-
// Optional: scope catalog + progress to a tenant collection
|
|
43
|
+
canReview: (user, scopeId) => Boolean(user?.roles?.includes('admin')),
|
|
53
44
|
// scope: { collection: 'tenants', relationField: 'scope' },
|
|
54
45
|
}),
|
|
55
46
|
],
|
|
56
47
|
})
|
|
57
48
|
```
|
|
58
49
|
|
|
59
|
-
|
|
50
|
+
`canReview` is how staff get to edit catalogs and approve requests. It receives the user and a scope id (`null` when the row is global).
|
|
60
51
|
|
|
61
|
-
|
|
62
|
-
payload generate:importmap
|
|
63
|
-
```
|
|
52
|
+
Then:
|
|
64
53
|
|
|
65
|
-
|
|
54
|
+
1. `payload generate:importmap` — Admin fields for logs, subjects, and Lucide icons.
|
|
55
|
+
2. Migrate (or push) schema. The plugin adds collections; your app still owns the migrate runner.
|
|
56
|
+
3. Restart so Payload can seed the system catalog on `onInit` (`points`, `metric.delta`, `achievement.granted`, `achievement.revoked`, `tier.changed`). Set `seedSystemCatalog: false` if you want to call `seedAchievementCatalog` yourself.
|
|
66
57
|
|
|
67
|
-
|
|
58
|
+
Your product catalog — extra event types, metrics, tiers, achievements — is `seedAchievements`.
|
|
68
59
|
|
|
69
|
-
|
|
70
|
-
import { seedAchievementCatalog } from '@dappermountain/payload-plugin-achievements'
|
|
60
|
+
## How the pieces fit
|
|
71
61
|
|
|
72
|
-
|
|
73
|
-
```
|
|
62
|
+
Think of four layers:
|
|
74
63
|
|
|
75
|
-
|
|
64
|
+
1. **Catalog** — named things in Admin (event types, metrics, tiers, achievements, reactions).
|
|
65
|
+
2. **Log** — what happened. Your hooks call `recordLog` / `recordMetricChange`. Grant and revoke write their own rows.
|
|
66
|
+
3. **Grants** — what someone has earned. One row per user (+ scope). Creating or deleting a grant updates the log and re-checks composed achievements and ranks.
|
|
67
|
+
4. **Reactions** — set-based side effects when a host event is logged or an achievement is granted/revoked.
|
|
76
68
|
|
|
77
|
-
|
|
69
|
+
Writing a host or metric log also re-checks composed achievements and derived tiers. Grant and revoke logs skip that path because the Grants hooks already ran it.
|
|
78
70
|
|
|
79
|
-
|
|
71
|
+
## Collections
|
|
72
|
+
|
|
73
|
+
Slugs use the prefix `achievement-` so they sit beside your own collections. Override with `collections.prefix` or per-key `collections.slugs`.
|
|
80
74
|
|
|
81
75
|
| Config key | Default slug | Purpose |
|
|
82
76
|
| --- | --- | --- |
|
|
83
|
-
| `metrics` | `achievement-metrics` | Named numbers: **stored**
|
|
84
|
-
| `metricBalances` | `achievement-metric-balances` |
|
|
77
|
+
| `metrics` | `achievement-metrics` | Named numbers: **stored** totals or **computed** values (elapsed time). |
|
|
78
|
+
| `metricBalances` | `achievement-metric-balances` | Running totals for stored metrics, per user (+ scope). Leaderboards read this. |
|
|
85
79
|
| `eventTypes` | `achievement-event-types` | Kinds of log entries you can count or require. |
|
|
86
|
-
| `tiers` | `achievement-tiers` |
|
|
87
|
-
| `achievements` | `achievement-definitions` |
|
|
88
|
-
| `grants` | `achievement-grants` | One
|
|
80
|
+
| `tiers` | `achievement-tiers` | Ladder steps with unlock rules. |
|
|
81
|
+
| `achievements` | `achievement-definitions` | Earnable items with eligibility and completion rules. |
|
|
82
|
+
| `grants` | `achievement-grants` | One earned achievement per user (+ scope). |
|
|
89
83
|
| `achievementRequests` | `achievement-requests` | Request → pending / approved / rejected. |
|
|
90
|
-
| `tierRequests` | `achievement-tier-requests` |
|
|
91
|
-
| `logs` | `achievement-logs` |
|
|
84
|
+
| `tierRequests` | `achievement-tier-requests` | Rank unlock waiting on review (`requiresReview` on the tier). |
|
|
85
|
+
| `logs` | `achievement-logs` | Activity history. |
|
|
86
|
+
| `reactions` | `achievement-reactions` | Side effects when something is logged or granted. |
|
|
87
|
+
|
|
88
|
+
System rows (`points` and the four engine event types) are protected. The plugin locks their slugs and blocks deletes.
|
|
89
|
+
|
|
90
|
+
## Event types
|
|
92
91
|
|
|
93
|
-
|
|
92
|
+
Each log row points at an event type. Dotted slugs read well: `post.published`, `comment.created`, `course.completed`, `post.edited`.
|
|
94
93
|
|
|
95
|
-
|
|
94
|
+
Flags on the type decide which log fields Admin asks for:
|
|
95
|
+
|
|
96
|
+
| Flag | Log field |
|
|
96
97
|
| --- | --- |
|
|
97
|
-
| `
|
|
98
|
-
|
|
|
99
|
-
| `
|
|
100
|
-
|
|
|
101
|
-
|
|
98
|
+
| Requires an actor | `actor` — who caused it (a peer, an admin, …) |
|
|
99
|
+
| Adjusts a metric | `metric` + `change` |
|
|
100
|
+
| Requires a subject | `subject` — the host document (a post, a comment, a user, …) |
|
|
101
|
+
| Snapshot actor tiers | stamps the actor’s derived rank at write time |
|
|
102
|
+
|
|
103
|
+
**Actor tier** on an `event-count` rule then counts only logs whose snapshot already met that rank in this scope. Leave Actor tier blank to count every matching event. A filter only matches logs that were stamped.
|
|
104
|
+
|
|
105
|
+
Unscoped logs stamp every ladder. Scoped logs stamp that tenant plus any unscoped ranks.
|
|
106
|
+
|
|
107
|
+
## Subjects
|
|
108
|
+
|
|
109
|
+
Logs can link to a host document the same way they link to an actor.
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
achievementPlugin({
|
|
113
|
+
canReview,
|
|
114
|
+
subjects: {
|
|
115
|
+
collections: ['posts', 'comments', 'users'],
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
That turns on:
|
|
121
|
+
|
|
122
|
+
- **Requires a subject** and **Subject collections** on event types
|
|
123
|
+
- a polymorphic **Subject** field on logs
|
|
124
|
+
- `recordLog({ subject: logSubject('posts', postId) })`
|
|
125
|
+
|
|
126
|
+
`collections: 'all'` includes every collection on your Payload config except this plugin’s slugs and anything prefixed `payload-`. It is optional. The picker and generated types grow with your schema, and collections you add later show up after a restart.
|
|
127
|
+
|
|
128
|
+
Example — “this member enrolled”, scoped to a tenant, subject = the user:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
await recordLog({
|
|
132
|
+
payload,
|
|
133
|
+
req,
|
|
134
|
+
userId: memberId,
|
|
135
|
+
scopeId: tenantId,
|
|
136
|
+
type: 'user.enrolled',
|
|
137
|
+
subject: logSubject('users', memberId),
|
|
138
|
+
})
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Same shape as `post.published` with `subject: logSubject('posts', postId)`.
|
|
102
142
|
|
|
103
|
-
|
|
143
|
+
Put host document links on `subject`. Engine grant/revoke/tier rows use a small `{ from, to }` envelope in `data`:
|
|
104
144
|
|
|
105
|
-
|
|
145
|
+
| type | `from` | `to` |
|
|
146
|
+
| --- | --- | --- |
|
|
147
|
+
| `tier.changed` | previous tier (`null` on first climb) | current tier |
|
|
148
|
+
| `achievement.granted` | `null` | achievement |
|
|
149
|
+
| `achievement.revoked` | achievement | `null` |
|
|
150
|
+
|
|
151
|
+
## Rules
|
|
106
152
|
|
|
107
|
-
Unlock (tiers), eligibility, and completion (achievements) share
|
|
153
|
+
Unlock (tiers), eligibility, and completion (achievements) share one tree:
|
|
108
154
|
|
|
109
|
-
-
|
|
110
|
-
-
|
|
111
|
-
- Built-in leaves
|
|
112
|
-
-
|
|
155
|
+
- Empty top-level list — everyone passes
|
|
156
|
+
- Groups — **All of these** (AND) or **Any of these** (OR)
|
|
157
|
+
- Built-in leaves — `tier-at-least`, `achievement-complete`, `metric-minimum`, `event-count`
|
|
158
|
+
- Your leaves — `extensions.ruleTypes` (`type`, `evaluate`, optional `progress`, `progressRole`, `label`, `fields`)
|
|
113
159
|
|
|
114
|
-
|
|
160
|
+
`label` and `fields` show up in the Admin rule editor. The plugin only displays those fields when that leaf type is selected.
|
|
115
161
|
|
|
116
|
-
|
|
162
|
+
**Eligibility** gates who may request an achievement. **Completion** describes what a composed achievement is made of. When `requiresReview` is off and completion passes, the parent grants itself. Nested achievement graphs skip cycles.
|
|
163
|
+
|
|
164
|
+
**Current tier** walks ranks in order (`resolveCurrentTier`). A tier with `requiresReview` becomes current after an **approved** tier request. Turning `requiresReview` off approves pending requests for that row and writes missing `tier.changed` logs for people who already meet the unlock rules.
|
|
165
|
+
|
|
166
|
+
**Next-tier fill** (`resolveTierProgress` / `evaluateRuleProgress`):
|
|
167
|
+
|
|
168
|
+
| Combinator / leaf | Progress |
|
|
117
169
|
| --- | --- |
|
|
118
170
|
| AND | Equal average of *requirement* children |
|
|
119
|
-
| OR | Best child
|
|
171
|
+
| OR | Best child |
|
|
120
172
|
| `tier-at-least` | Gate — skipped in AND averages |
|
|
121
|
-
| `event-count` / `metric-minimum` | Fraction of the target
|
|
122
|
-
| `achievement-complete` | `1` if granted; otherwise
|
|
173
|
+
| `event-count` / `metric-minimum` | Fraction of the target |
|
|
174
|
+
| `achievement-complete` | `1` if granted; otherwise that achievement’s own completion (or eligibility) tree |
|
|
175
|
+
|
|
176
|
+
`buildUnlockRequirementLeaves` walks a tree and returns met/progress plus catalog subjects (`relations`, `target`, `unit`, `since`). Your UI supplies the copy. `achievement-complete` is omitted by default so those stay on catalog groups. `eachRuleLeaf` is the walker on its own.
|
|
177
|
+
|
|
178
|
+
## Metrics
|
|
123
179
|
|
|
124
|
-
**
|
|
180
|
+
**Stored** metrics (default `points`) are sums of `change` on `metric.delta` logs. `recordMetricChange` writes the log and updates `achievement-metric-balances` together. Reconcile rebuilds balances from the log if they drift.
|
|
125
181
|
|
|
126
|
-
**
|
|
182
|
+
**Computed** metrics (v1: elapsed time) are derived at evaluation:
|
|
127
183
|
|
|
128
|
-
|
|
184
|
+
- `kind: 'computed'`, `compute: 'elapsed'`
|
|
185
|
+
- `unit`: seconds, minutes, hours, days, years (365-day years)
|
|
186
|
+
- `since`: `user-created-at`, `first-event` (plus an event type), or a key from `extensions.metricAnchors`
|
|
129
187
|
|
|
130
|
-
|
|
188
|
+
System seed creates stored `points`. You seed computed metrics after your anchors are registered.
|
|
131
189
|
|
|
132
|
-
**
|
|
190
|
+
**Leaderboards** (`getMetricLeaderboard` / `GET /api/achievements/leaderboard?metric=points`) rank stored balances for authenticated users. Each row is `{ user, value, rank }`. Your UI adds names, current tier, and who may appear. For a single user’s computed value, call `resolveMetricValue`.
|
|
133
191
|
|
|
134
|
-
|
|
192
|
+
## Reactions
|
|
135
193
|
|
|
136
|
-
|
|
194
|
+
A reaction is: **when this happens, run this command**.
|
|
137
195
|
|
|
138
|
-
|
|
196
|
+
Triggers:
|
|
139
197
|
|
|
140
|
-
-
|
|
141
|
-
-
|
|
142
|
-
- Server helpers (`recordLog`, `recordMetricChange`, `grantAchievement`, `resolveCurrentTier`, …) run with `overrideAccess: true`. Call them only from trusted server code (hooks, jobs, locked-down endpoints).
|
|
198
|
+
- **Event logged** — a host event type (for example `course.completed`)
|
|
199
|
+
- **Achievement granted** / **revoked** — a specific achievement
|
|
143
200
|
|
|
144
|
-
|
|
201
|
+
Built-in action: **Grant achievement** (no-op if they already have it).
|
|
145
202
|
|
|
146
|
-
|
|
203
|
+
Your actions go in `extensions.actions`. Each one needs a `type` (a command slug like `accessGroup.addMember`), optional `label` / `fields` for Admin, and a `run` function. `run` should be set-based: adding someone who is already a member is a no-op. Reactions run in the same request as the log or grant. Start a job from `run` if the work belongs on a queue.
|
|
204
|
+
|
|
205
|
+
Grant/revoke reactions fire from the grant row. Point event reactions at your host event types (`post.published`, `course.completed`, …).
|
|
206
|
+
|
|
207
|
+
## Custom rules, anchors, and actions
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
achievementPlugin({
|
|
211
|
+
canReview,
|
|
212
|
+
extensions: {
|
|
213
|
+
metricAnchors: {
|
|
214
|
+
'membership-started': {
|
|
215
|
+
label: ({ t }) => t('custom:achievements:anchors:membershipStarted'),
|
|
216
|
+
resolve: async ({ payload, userId, scopeId }) => {
|
|
217
|
+
if (!scopeId) return null
|
|
218
|
+
const found = await payload.find({
|
|
219
|
+
collection: 'memberships',
|
|
220
|
+
limit: 1,
|
|
221
|
+
overrideAccess: true,
|
|
222
|
+
where: {
|
|
223
|
+
and: [
|
|
224
|
+
{ user: { equals: userId } },
|
|
225
|
+
{ workspace: { equals: scopeId } },
|
|
226
|
+
],
|
|
227
|
+
},
|
|
228
|
+
})
|
|
229
|
+
const startedAt = (found.docs[0] as { startedAt?: string } | undefined)?.startedAt
|
|
230
|
+
return startedAt ? new Date(startedAt) : null
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
ruleTypes: [
|
|
235
|
+
{
|
|
236
|
+
type: 'host.course-complete',
|
|
237
|
+
label: 'Course complete',
|
|
238
|
+
fields: [
|
|
239
|
+
{ name: 'course', type: 'relationship', relationTo: 'courses', required: true },
|
|
240
|
+
],
|
|
241
|
+
evaluate: async ({ rule, userId, payload, req }) => {
|
|
242
|
+
// return true when this user has completed rule.course
|
|
243
|
+
return true
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
],
|
|
247
|
+
actions: [
|
|
248
|
+
{
|
|
249
|
+
type: 'accessGroup.addMember',
|
|
250
|
+
label: 'Add to access group',
|
|
251
|
+
fields: [
|
|
252
|
+
{
|
|
253
|
+
name: 'accessGroup',
|
|
254
|
+
type: 'relationship',
|
|
255
|
+
relationTo: 'access-groups',
|
|
256
|
+
required: true,
|
|
257
|
+
},
|
|
258
|
+
],
|
|
259
|
+
run: async ({ userId, reaction, req }) => {
|
|
260
|
+
// merge the user into the group; already-a-member is a no-op
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
],
|
|
264
|
+
},
|
|
265
|
+
})
|
|
266
|
+
```
|
|
147
267
|
|
|
148
|
-
|
|
268
|
+
Anchor `label` is a Payload Admin string (`OptionLabel`): plain text, `{ en, es }`, or `({ t }) => t('custom:…')`. Your app owns those `custom:` keys.
|
|
269
|
+
|
|
270
|
+
Then seed a computed metric (`since: 'membership-started'`) and use `metric-minimum` in rules.
|
|
271
|
+
|
|
272
|
+
## Access
|
|
273
|
+
|
|
274
|
+
- Catalog, grants, logs, reactions, and request approval use `canReview(user, scopeId)`.
|
|
275
|
+
- Metric balances: reviewers can read and delete; trusted helpers write them.
|
|
276
|
+
- Member-facing requests use normal collection access plus eligibility hooks.
|
|
277
|
+
- Server helpers (`recordLog`, `recordMetricChange`, `grantAchievement`, …) run with `overrideAccess: true`. Call them from hooks, jobs, and locked-down endpoints. Pass `req` so nested Local API stays in the same transaction.
|
|
278
|
+
|
|
279
|
+
## Localization
|
|
280
|
+
|
|
281
|
+
With Payload `localization` enabled, these catalog fields are already `localized: true`:
|
|
282
|
+
|
|
283
|
+
| Collection | Localized | Other |
|
|
149
284
|
| --- | --- | --- |
|
|
150
|
-
| Achievements / tiers | `name` (text), `description` (
|
|
151
|
-
| Metrics / event types | `name` | `slug`,
|
|
285
|
+
| Achievements / tiers | `name` (text), `description` (Lexical) | `slug`, rules, flags |
|
|
286
|
+
| Metrics / event types | `name` | `slug`, flags |
|
|
152
287
|
|
|
153
|
-
Tier `icon` is a
|
|
288
|
+
Tier `icon` is a Lucide picker (stores `sparkles`, `shield`, …). Peer-depend on `@payloadcms/richtext-lexical` and `lucide-react`. After upgrading, regenerate the import map and migrate so `description` columns accept JSON.
|
|
154
289
|
|
|
155
|
-
|
|
290
|
+
`GET /api/achievements/me` and progress helpers return Lexical `description` as stored. Convert in your UI (`convertLexicalToHTML`, `convertLexicalToPlaintext`, or the plugin’s `descriptionToPlaintext` / `plainTextToLexical`).
|
|
156
291
|
|
|
157
|
-
|
|
292
|
+
Admin chrome ships in English. Member-facing copy lives in your i18n bundle. Seed extra locales after the English system catalog exists.
|
|
158
293
|
|
|
159
|
-
## Configuration
|
|
294
|
+
## Configuration
|
|
160
295
|
|
|
161
296
|
```ts
|
|
162
297
|
achievementPlugin({
|
|
163
298
|
enabled?: boolean
|
|
299
|
+
seedSystemCatalog?: boolean
|
|
164
300
|
usersCollectionSlug?: string
|
|
165
301
|
canReview?: (user, scopeId) => boolean | Promise<boolean>
|
|
166
302
|
scope?: { collection: string; relationField?: string }
|
|
167
303
|
mediaCollection?: string
|
|
168
|
-
slugPrefix?: string // deprecated
|
|
304
|
+
slugPrefix?: string // deprecated; use collections.prefix
|
|
169
305
|
collections?: {
|
|
170
306
|
prefix?: string
|
|
171
307
|
adminGroup?: string | false
|
|
@@ -174,35 +310,37 @@ achievementPlugin({
|
|
|
174
310
|
}
|
|
175
311
|
users?: { includeJoins?: boolean }
|
|
176
312
|
endpoints?: { me?: string | false; leaderboard?: string | false; reconcile?: string | false }
|
|
313
|
+
subjects?: { collections?: 'all' | string[] }
|
|
177
314
|
extensions?: {
|
|
178
315
|
ruleTypes?: AchievementRuleType[]
|
|
179
|
-
metricAnchors?: Record<string,
|
|
316
|
+
metricAnchors?: Record<string, AchievementMetricAnchorEntry>
|
|
317
|
+
actions?: AchievementAction[]
|
|
180
318
|
}
|
|
181
319
|
})
|
|
182
320
|
```
|
|
183
321
|
|
|
184
|
-
### Core
|
|
322
|
+
### Core
|
|
185
323
|
|
|
186
324
|
| Option | Default | Notes |
|
|
187
325
|
| --- | --- | --- |
|
|
188
|
-
| `enabled` | `true` |
|
|
189
|
-
| `seedSystemCatalog` | `true` |
|
|
190
|
-
| `usersCollectionSlug` | `'users'` | Users collection
|
|
191
|
-
| `canReview` |
|
|
192
|
-
| `scope` |
|
|
193
|
-
| `mediaCollection` |
|
|
194
|
-
| `extensions.metricAnchors` |
|
|
326
|
+
| `enabled` | `true` | `false` leaves the package installed with no collections or endpoints. |
|
|
327
|
+
| `seedSystemCatalog` | `true` | Upserts system metrics and event types on `onInit`. |
|
|
328
|
+
| `usersCollectionSlug` | `'users'` | Users collection for grants, requests, and joins. |
|
|
329
|
+
| `canReview` | denied | Staff catalog and approval access. `scopeId` may be `null`. |
|
|
330
|
+
| `scope` | unset | `collection` is the tenant target. `relationField` defaults to `'scope'`. |
|
|
331
|
+
| `mediaCollection` | unset | e.g. `'media'` — optional upload on tiers for badge images. Icon keys still work. |
|
|
332
|
+
| `extensions.metricAnchors` | unset | Named dates for elapsed metrics. |
|
|
333
|
+
| `extensions.ruleTypes` | unset | Custom rule leaves; `label` / `fields` appear in Admin. |
|
|
334
|
+
| `extensions.actions` | unset | Extra reaction commands. Built-in `achievement.grant` is always there. |
|
|
195
335
|
|
|
196
336
|
### `collections`
|
|
197
337
|
|
|
198
338
|
| Option | Default | Notes |
|
|
199
339
|
| --- | --- | --- |
|
|
200
|
-
| `prefix` | `'achievement'` |
|
|
201
|
-
| `adminGroup` | `'Achievements'` |
|
|
202
|
-
| `slugs` |
|
|
203
|
-
| `overrides` |
|
|
204
|
-
|
|
205
|
-
Example override (notify after a grant is created via request approval):
|
|
340
|
+
| `prefix` | `'achievement'` | Default slugs, REST paths, and table names. |
|
|
341
|
+
| `adminGroup` | `'Achievements'` | Sidebar group. `false` leaves collections ungrouped. |
|
|
342
|
+
| `slugs` | derived | Absolute slug per key (ignores `prefix` for that key). |
|
|
343
|
+
| `overrides` | unset | `access`, `admin`, `hooks`, `labels`. Access keys replace; hook arrays append after plugin hooks; `admin` / `labels` merge shallowly. |
|
|
206
344
|
|
|
207
345
|
```ts
|
|
208
346
|
achievementPlugin({
|
|
@@ -229,98 +367,27 @@ achievementPlugin({
|
|
|
229
367
|
|
|
230
368
|
| Option | Default | Notes |
|
|
231
369
|
| --- | --- | --- |
|
|
232
|
-
| `includeJoins` | `true` |
|
|
370
|
+
| `includeJoins` | `true` | Adds an `achievements` group on users (`grants` / `requests` joins). `false` if you already own that UI. |
|
|
233
371
|
|
|
234
372
|
### `subjects`
|
|
235
373
|
|
|
236
|
-
Host documents that logs may point at via a polymorphic `subject` field (same idea as `requiresActor` / `requiresMetric`).
|
|
237
|
-
|
|
238
374
|
| Option | Default | Notes |
|
|
239
375
|
| --- | --- | --- |
|
|
240
|
-
| `collections` | `[]` |
|
|
241
|
-
|
|
242
|
-
When configured:
|
|
243
|
-
|
|
244
|
-
- Event types gain **Requires a subject** + optional **Subject collections** (`subjectRelationTo`).
|
|
245
|
-
- Logs gain a polymorphic **Subject** relationship (Admin links to the host doc).
|
|
246
|
-
- `recordLog({ subject: { relationTo, value } })` (or `logSubject(relationTo, value)`) writes the ref.
|
|
247
|
-
- Prefer `subject` over stuffing ids into `data` JSON.
|
|
248
|
-
|
|
249
|
-
```ts
|
|
250
|
-
achievementPlugin({
|
|
251
|
-
canReview,
|
|
252
|
-
subjects: {
|
|
253
|
-
collections: ['posts', 'comments', 'endorsements'],
|
|
254
|
-
},
|
|
255
|
-
})
|
|
256
|
-
|
|
257
|
-
await seedAchievements(payload, {
|
|
258
|
-
eventTypes: [
|
|
259
|
-
{
|
|
260
|
-
name: 'Comment created',
|
|
261
|
-
slug: 'comment.created',
|
|
262
|
-
requiresSubject: true,
|
|
263
|
-
subjectRelationTo: ['comments'],
|
|
264
|
-
},
|
|
265
|
-
],
|
|
266
|
-
})
|
|
267
|
-
|
|
268
|
-
await recordLog({
|
|
269
|
-
payload,
|
|
270
|
-
userId,
|
|
271
|
-
scopeId,
|
|
272
|
-
type: 'comment.created',
|
|
273
|
-
actorId: userId,
|
|
274
|
-
subject: logSubject('comments', commentId),
|
|
275
|
-
})
|
|
276
|
-
```
|
|
376
|
+
| `collections` | `[]` | Host slugs for log `subject`, or `'all'`. Empty skips the feature. |
|
|
277
377
|
|
|
278
378
|
### `endpoints`
|
|
279
379
|
|
|
280
380
|
| Option | Default | Notes |
|
|
281
381
|
| --- | --- | --- |
|
|
282
|
-
| `me` | `'/achievements/me'` |
|
|
283
|
-
| `leaderboard` | `'/achievements/leaderboard'` |
|
|
284
|
-
| `reconcile` | `'/achievements/reconcile'` |
|
|
285
|
-
|
|
286
|
-
Query params (`me`): `scope`, `limit`, `page`, `requestsLimit`, `reviews`. Leaderboard: `metric` (required), `scope`, `limit`, `page`.
|
|
287
|
-
|
|
288
|
-
### `extensions.ruleTypes` / `metricAnchors`
|
|
382
|
+
| `me` | `'/achievements/me'` | Signed-in user’s grants, derived tiers, lean requests. `?reviews=1` adds a review snapshot. Always the caller’s own snapshot. `false` skips it. |
|
|
383
|
+
| `leaderboard` | `'/achievements/leaderboard'` | Stored-metric ranks. `false` skips it. |
|
|
384
|
+
| `reconcile` | `'/achievements/reconcile'` | Reviewer repair endpoint. `false` skips it. |
|
|
289
385
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
```ts
|
|
293
|
-
achievementPlugin({
|
|
294
|
-
canReview,
|
|
295
|
-
extensions: {
|
|
296
|
-
metricAnchors: {
|
|
297
|
-
'enrollment-started': {
|
|
298
|
-
// Admin UI i18n (Payload label / OptionLabel)
|
|
299
|
-
label: ({ t }) => t('custom:achievements:anchors:enrollmentStarted'),
|
|
300
|
-
resolve: async ({ payload, userId, scopeId }) => {
|
|
301
|
-
// return a Date from host data, or null
|
|
302
|
-
return null
|
|
303
|
-
},
|
|
304
|
-
},
|
|
305
|
-
},
|
|
306
|
-
ruleTypes: [
|
|
307
|
-
{
|
|
308
|
-
type: 'host.custom-check',
|
|
309
|
-
evaluate: async ({ rule, userId, payload, req }) => {
|
|
310
|
-
// return true when the rule passes
|
|
311
|
-
return true
|
|
312
|
-
},
|
|
313
|
-
// optional: progress: async () => 0.5,
|
|
314
|
-
// optional: progressRole: 'requirement' | 'gate',
|
|
315
|
-
},
|
|
316
|
-
],
|
|
317
|
-
},
|
|
318
|
-
})
|
|
319
|
-
```
|
|
386
|
+
`me` query: `scope`, `limit`, `page`, `requestsLimit`, `reviews`. Leaderboard: `metric` (required), `scope`, `limit`, `page`.
|
|
320
387
|
|
|
321
388
|
## Server helpers
|
|
322
389
|
|
|
323
|
-
|
|
390
|
+
Call these from hooks, jobs, and trusted endpoints:
|
|
324
391
|
|
|
325
392
|
```ts
|
|
326
393
|
import {
|
|
@@ -341,71 +408,50 @@ import {
|
|
|
341
408
|
logSubject,
|
|
342
409
|
} from '@dappermountain/payload-plugin-achievements'
|
|
343
410
|
|
|
344
|
-
await recordLog({ payload, userId, scopeId, type: '
|
|
345
|
-
await
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
actorId: userId,
|
|
351
|
-
subject: logSubject('comments', commentId),
|
|
352
|
-
})
|
|
353
|
-
await recordMetricChange({ payload, userId, scopeId, metric: 'points', change: 10 })
|
|
354
|
-
const points = await resolveMetricValue({ payload, userId, scopeId, metric: 'points' })
|
|
355
|
-
const board = await getMetricLeaderboard({ payload, metric: 'points', scopeId, limit: 20 })
|
|
356
|
-
const tier = await resolveCurrentTier({ payload, userId, scopeId })
|
|
357
|
-
const progress = await getUserProgress({ payload, userId, scopeId, include: { reviews: true } })
|
|
411
|
+
await recordLog({ payload, req, userId, scopeId, type: 'post.published', subject: logSubject('posts', postId) })
|
|
412
|
+
await recordMetricChange({ payload, req, userId, scopeId, metric: 'points', change: 10 })
|
|
413
|
+
const points = await resolveMetricValue({ payload, req, userId, scopeId, metric: 'points' })
|
|
414
|
+
const board = await getMetricLeaderboard({ payload, req, metric: 'points', scopeId, limit: 20 })
|
|
415
|
+
const tier = await resolveCurrentTier({ payload, req, userId, scopeId })
|
|
416
|
+
const progress = await getUserProgress({ payload, req, userId, scopeId, include: { reviews: true } })
|
|
358
417
|
const unlockLeaves = await buildUnlockRequirementLeaves({
|
|
359
418
|
payload,
|
|
419
|
+
req,
|
|
360
420
|
userId,
|
|
361
421
|
scopeId,
|
|
362
422
|
rules: nextTier.unlockRules,
|
|
363
423
|
ladderRank: tier?.rank ?? null,
|
|
364
424
|
})
|
|
365
425
|
|
|
366
|
-
|
|
367
|
-
await reconcileProgression({ payload })
|
|
368
|
-
|
|
369
|
-
// Optional filters (ids or slugs)
|
|
426
|
+
await reconcileProgression({ payload, req })
|
|
370
427
|
await reconcileProgression({
|
|
371
428
|
payload,
|
|
429
|
+
req,
|
|
372
430
|
userId: '…',
|
|
373
431
|
scopeId: '…',
|
|
374
|
-
achievementSlug: '
|
|
432
|
+
achievementSlug: 'first-steps',
|
|
375
433
|
tierSlug: 'veteran',
|
|
376
434
|
})
|
|
377
435
|
|
|
378
|
-
// Host CLI (only boot config in the app — flags live in the plugin):
|
|
379
|
-
// bun --env-file=.env ./scripts/reconcile-achievements.ts -- --user=<id> --achievement=path-complete
|
|
380
436
|
import { runReconcileCli } from '@dappermountain/payload-plugin-achievements/cli'
|
|
381
437
|
await runReconcileCli({ config })
|
|
382
438
|
```
|
|
383
439
|
|
|
384
|
-
Pass catalog **slugs**
|
|
385
|
-
|
|
386
|
-
Engine log `data` for those system events uses a shared transition envelope:
|
|
440
|
+
Pass catalog **slugs** or ids for `type` and `metric`. Creating or deleting a grant writes `achievement.granted` / `achievement.revoked`, syncs composed achievements, and may open tier requests or write `tier.changed`.
|
|
387
441
|
|
|
388
|
-
|
|
389
|
-
{ from: { id, slug? } | null, to: { id, slug? } | null }
|
|
390
|
-
```
|
|
391
|
-
|
|
392
|
-
| type | `from` | `to` |
|
|
393
|
-
| --- | --- | --- |
|
|
394
|
-
| `tier.changed` | previous tier (null on first climb) | current tier |
|
|
395
|
-
| `achievement.granted` | `null` | achievement |
|
|
396
|
-
| `achievement.revoked` | achievement | `null` |
|
|
442
|
+
Turning **Requires review** off on a definition or tier approves that row’s pending requests (each waiting user goes through the existing request hooks).
|
|
397
443
|
|
|
398
|
-
|
|
444
|
+
The Grants list in Admin includes **Repair progression**, which `POST`s the reconcile endpoint (`canReview`).
|
|
399
445
|
|
|
400
|
-
|
|
446
|
+
Also exported: `collectionOf` / `slugOf` (resolved collection slugs), `syncProgressionFromLog`, `runReactions`.
|
|
401
447
|
|
|
402
|
-
|
|
448
|
+
## REST
|
|
403
449
|
|
|
404
|
-
|
|
450
|
+
Paths follow your `collections.prefix` / `slugs`.
|
|
405
451
|
|
|
406
452
|
| Goal | Request |
|
|
407
453
|
| --- | --- |
|
|
408
|
-
| Current user snapshot | `GET /api/achievements/me?scope=<scopeId>&limit=10&page=1` (`&reviews=1` for
|
|
454
|
+
| Current user snapshot | `GET /api/achievements/me?scope=<scopeId>&limit=10&page=1` (`&reviews=1` for review keys) |
|
|
409
455
|
| Stored metric leaderboard | `GET /api/achievements/leaderboard?metric=points&scope=<scopeId>&limit=20&page=1` |
|
|
410
456
|
| Repair progression | `POST /api/achievements/reconcile` (reviewer; optional `{ userId, scopeId, achievementId\|achievementSlug, tierId\|tierSlug, limit }`) |
|
|
411
457
|
| List grants | `GET /api/achievement-grants?where[user][equals]=<userId>` |
|
|
@@ -413,9 +459,7 @@ Turning **Requires review** off on a definition or tier **approves pending reque
|
|
|
413
459
|
| Request an achievement | `POST /api/achievement-requests` with `{ achievement }` |
|
|
414
460
|
| Approve / reject achievement | `PATCH /api/achievement-requests/:id` with `{ status: "approved" \| "rejected" }` |
|
|
415
461
|
| Approve / reject tier | `PATCH /api/achievement-tier-requests/:id` with `{ status: "approved" \| "rejected" }` |
|
|
416
|
-
| Browse catalogs | `GET /api/achievement-event-types`, `GET /api/achievement-metrics`, … |
|
|
417
|
-
|
|
418
|
-
Exact collection paths follow your `collections.prefix` / `slugs` settings.
|
|
462
|
+
| Browse catalogs | `GET /api/achievement-event-types`, `GET /api/achievement-metrics`, `GET /api/achievement-reactions`, … |
|
|
419
463
|
|
|
420
464
|
## Seeding
|
|
421
465
|
|
|
@@ -425,26 +469,27 @@ import {
|
|
|
425
469
|
seedAchievements,
|
|
426
470
|
} from '@dappermountain/payload-plugin-achievements'
|
|
427
471
|
|
|
428
|
-
await seedAchievementCatalog(payload)
|
|
472
|
+
await seedAchievementCatalog(payload)
|
|
429
473
|
|
|
430
474
|
await seedAchievements(payload, {
|
|
431
475
|
eventTypes: [
|
|
432
|
-
{ name: '
|
|
476
|
+
{ name: 'Post published', slug: 'post.published', requiresSubject: true, subjectRelationTo: ['posts'] },
|
|
477
|
+
{ name: 'Comment created', slug: 'comment.created', requiresActor: true, requiresSubject: true, subjectRelationTo: ['comments'] },
|
|
478
|
+
{ name: 'User enrolled', slug: 'user.enrolled', requiresSubject: true, subjectRelationTo: ['users'] },
|
|
479
|
+
],
|
|
480
|
+
metrics: [
|
|
481
|
+
{ name: 'Streak days', slug: 'streak-days' },
|
|
433
482
|
{
|
|
434
|
-
name: '
|
|
435
|
-
slug: '
|
|
436
|
-
|
|
437
|
-
|
|
483
|
+
name: 'Days as member',
|
|
484
|
+
slug: 'days-as-member',
|
|
485
|
+
kind: 'computed',
|
|
486
|
+
compute: 'elapsed',
|
|
487
|
+
unit: 'days',
|
|
488
|
+
since: 'membership-started',
|
|
438
489
|
},
|
|
439
490
|
],
|
|
440
|
-
metrics: [{ name: 'Streak days', slug: 'streak-days' }],
|
|
441
491
|
tiers: [
|
|
442
|
-
{
|
|
443
|
-
name: 'Novice',
|
|
444
|
-
slug: 'novice',
|
|
445
|
-
rank: 0,
|
|
446
|
-
unlockRules: [], // open
|
|
447
|
-
},
|
|
492
|
+
{ name: 'Novice', slug: 'novice', rank: 0, unlockRules: [] },
|
|
448
493
|
],
|
|
449
494
|
achievements: [
|
|
450
495
|
{
|
|
@@ -454,10 +499,11 @@ await seedAchievements(payload, {
|
|
|
454
499
|
completionRules: [{ type: 'metric-minimum', metricSlug: 'points', minimum: 10 }],
|
|
455
500
|
},
|
|
456
501
|
],
|
|
502
|
+
removeAchievementSlugs: ['old-slug'],
|
|
457
503
|
})
|
|
458
504
|
```
|
|
459
505
|
|
|
460
|
-
`name` / `description` accept a string (default locale) or
|
|
506
|
+
`name` / `description` accept a string (default locale) or `{ en: '…', es: '…' }` when localization is on. Seed extra locales after English system rows exist. Rule arrays in seed can use `metricSlug` / `eventTypeSlug` / `achievementSlug`; the seeder resolves them to relationships.
|
|
461
507
|
|
|
462
508
|
## License
|
|
463
509
|
|
|
@@ -465,12 +511,10 @@ MIT © Dapper Mountain
|
|
|
465
511
|
|
|
466
512
|
## Agent context (Cursor)
|
|
467
513
|
|
|
468
|
-
|
|
514
|
+
Rules and skills live under [`.agents/`](.agents/). See [`AGENTS.md`](AGENTS.md).
|
|
469
515
|
|
|
470
516
|
```bash
|
|
471
517
|
bun install
|
|
472
518
|
bun run agents:sync
|
|
473
519
|
bun run skills:install
|
|
474
520
|
```
|
|
475
|
-
|
|
476
|
-
Dev dependencies: [`@dappermountain/agent-practices`](https://www.npmjs.com/package/@dappermountain/agent-practices), [`@dappermountain/agent-payload`](https://www.npmjs.com/package/@dappermountain/agent-payload). Run `agents:sync` after install or upgrade so rules land under `.agents/`.
|