@dappermountain/payload-plugin-achievements 1.0.0-beta.2 → 1.0.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.
Files changed (50) hide show
  1. package/README.md +36 -8
  2. package/dist/catalog.d.ts +22 -1
  3. package/dist/catalog.d.ts.map +1 -1
  4. package/dist/catalog.js +19 -1
  5. package/dist/collections/Achievements/index.d.ts.map +1 -1
  6. package/dist/collections/Achievements/index.js +23 -3
  7. package/dist/collections/Grants/index.d.ts.map +1 -1
  8. package/dist/collections/Grants/index.js +33 -2
  9. package/dist/collections/TierRequests/hooks/prepareTierRequest.d.ts +1 -1
  10. package/dist/collections/TierRequests/hooks/prepareTierRequest.d.ts.map +1 -1
  11. package/dist/collections/TierRequests/hooks/prepareTierRequest.js +114 -7
  12. package/dist/collections/TierRequests/index.js +1 -1
  13. package/dist/collections/Tiers/index.js +1 -1
  14. package/dist/collections/applyOverrides.d.ts +1 -0
  15. package/dist/collections/applyOverrides.d.ts.map +1 -1
  16. package/dist/collections/applyOverrides.js +8 -0
  17. package/dist/collections/fields/index.d.ts +1 -1
  18. package/dist/collections/fields/index.d.ts.map +1 -1
  19. package/dist/collections/fields/index.js +1 -1
  20. package/dist/collections/fields/ruleFields.d.ts +27 -14
  21. package/dist/collections/fields/ruleFields.d.ts.map +1 -1
  22. package/dist/collections/fields/ruleFields.js +82 -18
  23. package/dist/index.d.ts +4 -4
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2 -2
  26. package/dist/seed/index.d.ts +7 -0
  27. package/dist/seed/index.d.ts.map +1 -1
  28. package/dist/seed/index.js +2 -0
  29. package/dist/services/achievement/builtInRules.d.ts.map +1 -1
  30. package/dist/services/achievement/builtInRules.js +10 -2
  31. package/dist/services/achievement/grantLifecycle.d.ts +31 -0
  32. package/dist/services/achievement/grantLifecycle.d.ts.map +1 -0
  33. package/dist/services/achievement/grantLifecycle.js +139 -0
  34. package/dist/services/achievement/grantSideEffects.d.ts +22 -0
  35. package/dist/services/achievement/grantSideEffects.d.ts.map +1 -1
  36. package/dist/services/achievement/grantSideEffects.js +94 -3
  37. package/dist/services/achievement/index.d.ts +4 -0
  38. package/dist/services/achievement/index.d.ts.map +1 -1
  39. package/dist/services/achievement/index.js +3 -0
  40. package/dist/services/achievement/logData.d.ts +6 -2
  41. package/dist/services/achievement/logData.d.ts.map +1 -1
  42. package/dist/services/achievement/reviewTierRequest.d.ts +28 -0
  43. package/dist/services/achievement/reviewTierRequest.d.ts.map +1 -0
  44. package/dist/services/achievement/reviewTierRequest.js +77 -0
  45. package/dist/services/achievement/submitTierRequest.d.ts +16 -0
  46. package/dist/services/achievement/submitTierRequest.d.ts.map +1 -0
  47. package/dist/services/achievement/submitTierRequest.js +84 -0
  48. package/dist/types.d.ts +8 -1
  49. package/dist/types.d.ts.map +1 -1
  50. package/package.json +1 -1
package/README.md CHANGED
@@ -18,7 +18,7 @@ You describe what people can earn and what has to happen first. Your app records
18
18
 
19
19
  | Plugin line | Payload | Notes |
20
20
  | ----------- | ------- | ----- |
21
- | **`1.x`** (this package — e.g. `1.0.0-beta.2`) | **4** (`^4.0.0-beta.1` / `^4.0.0`) | Current line. Opt out of P4 default versions/authorship on high-churn collections. |
21
+ | **`1.x`** (this package — e.g. `1.0.0`) | **4** (`^4.0.0-beta.1` / `^4.0.0`) | Current line. Opt out of P4 default versions/authorship on high-churn collections. |
22
22
  | **`0.6.x`** | **3** (`^3.89`) | Last Payload 3 line. Same product features (reactions, composites, etc.). Stay on `0.6.x` until you upgrade the host to Payload 4. |
23
23
 
24
24
  One published version cannot peer both Payload majors (Admin field types and collection defaults diverge). Pick the line that matches your host.
@@ -37,7 +37,7 @@ Plugin collections opt out of Payload 4’s default versions and authorship (app
37
37
 
38
38
  ```bash
39
39
  # Payload 4 hosts
40
- bun add @dappermountain/payload-plugin-achievements@^1.0.0-beta.2
40
+ bun add @dappermountain/payload-plugin-achievements@^1.0.0
41
41
 
42
42
  # Payload 3 hosts (stay on the 0.6 line)
43
43
  bun add @dappermountain/payload-plugin-achievements@0.6
@@ -68,7 +68,7 @@ Then:
68
68
 
69
69
  1. `payload generate:importmap` — Admin fields for logs, subjects, and Lucide icons.
70
70
  2. Migrate (or push) schema. The plugin adds collections; your app still owns the migrate runner.
71
- 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.
71
+ 3. Restart so Payload can seed the system catalog on `onInit` (`points`, `metric.delta`, `achievement.granted` / `revoked` / `renewed` / `expired` / `superseded`, `tier.changed`, `tier.request.submitted` / `approved` / `rejected`). Set `seedSystemCatalog: false` if you want to call `seedAchievementCatalog` yourself.
72
72
 
73
73
  Your product catalog — extra event types, metrics, tiers, achievements — is `seedAchievements`.
74
74
 
@@ -93,14 +93,14 @@ Slugs use the prefix `achievement-` so they sit beside your own collections. Ove
93
93
  | `metricBalances` | `achievement-metric-balances` | Running totals for stored metrics, per user (+ scope). Leaderboards read this. |
94
94
  | `eventTypes` | `achievement-event-types` | Kinds of log entries you can count or require. |
95
95
  | `tiers` | `achievement-tiers` | Ladder steps with unlock rules. |
96
- | `achievements` | `achievement-definitions` | Earnable items with eligibility and completion rules. |
97
- | `grants` | `achievement-grants` | One earned achievement per user (+ scope). |
96
+ | `achievements` | `achievement-definitions` | Earnable items with eligibility and completion rules, `lifecycle` (`once` \| `ongoing`), plus optional JSON `metadata` for host/product structure. |
97
+ | `grants` | `achievement-grants` | One earned achievement per user (+ scope). Ongoing defs keep the row and set `status` (`active` \| `expired` \| `superseded`). |
98
98
  | `achievementRequests` | `achievement-requests` | Request → pending / approved / rejected. |
99
99
  | `tierRequests` | `achievement-tier-requests` | Tier unlock waiting on review (`requiresReview` on the tier). |
100
100
  | `logs` | `achievement-logs` | Activity history. |
101
101
  | `reactions` | `achievement-reactions` | Side effects when something is logged or granted. |
102
102
 
103
- System rows (`points` and the four engine event types) are protected. The plugin locks their slugs and blocks deletes.
103
+ System rows (`points` and the engine event types) are protected. The plugin locks their slugs and blocks deletes.
104
104
 
105
105
  ## Event types
106
106
 
@@ -163,6 +163,8 @@ Put host document links on `subject`. Engine grant/revoke/tier rows use a small
163
163
  | `achievement.granted` | `null` | achievement |
164
164
  | `achievement.revoked` | achievement | `null` |
165
165
 
166
+ Tier-request lifecycle logs (`tier.request.submitted` / `approved` / `rejected`) store `{ requestId, status, fromStatus, tier }` so hosts and reactions can listen without forking ladder derivation.
167
+
166
168
  ## Rules
167
169
 
168
170
  Unlock (tiers), eligibility, and completion (achievements) share one tree:
@@ -176,7 +178,9 @@ Unlock (tiers), eligibility, and completion (achievements) share one tree:
176
178
 
177
179
  **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.
178
180
 
179
- **Current tier** walks the ladder in `rank` 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.
181
+ **Definition `metadata`** is an optional JSON field on achievement definitions for host/product structure (filters, effects, completion shape, and so on). The plugin does not interpret it. Keep member-facing copy in localized `name` / `description` and host i18n keyed by slug — not inside `metadata`. Seed with `seedAchievements({ achievements: [{ metadata, … }] })`. For typed Admin fields on hot paths, use `collections.overrides.achievements.fields`.
182
+
183
+ **Current tier** walks the ladder in `rank` order (`resolveCurrentTier`). A tier with `requiresReview` becomes current after an **approved** tier request. Members open requests with `submitTierRequest` (unlock rules must pass); staff use `reviewTierRequest` / `findTierRequestsForReview`. Turning `requiresReview` off approves pending requests for that row and writes missing `tier.changed` logs for people who already meet the unlock rules.
180
184
 
181
185
  **Next-tier fill** (`resolveTierProgress` / `evaluateRuleProgress`):
182
186
 
@@ -355,7 +359,7 @@ achievementPlugin({
355
359
  | `prefix` | `'achievement'` | Default slugs, REST paths, and table names. |
356
360
  | `adminGroup` | `'Achievements'` | Sidebar group. `false` leaves collections ungrouped. |
357
361
  | `slugs` | derived | Absolute slug per key (ignores `prefix` for that key). |
358
- | `overrides` | unset | `access`, `admin`, `hooks`, `labels`. Access keys replace; hook arrays append after plugin hooks; `admin` / `labels` merge shallowly. |
362
+ | `overrides` | unset | `access`, `admin`, `hooks`, `labels`, `fields`. Access keys replace; hook arrays append after plugin hooks; `admin` / `labels` merge shallowly; `fields` replaces the list (use `({ defaultFields }) => …` to wrap). |
359
363
 
360
364
  ```ts
361
365
  achievementPlugin({
@@ -373,6 +377,12 @@ achievementPlugin({
373
377
  ],
374
378
  },
375
379
  },
380
+ achievements: {
381
+ fields: ({ defaultFields }) => [
382
+ ...defaultFields,
383
+ // optional typed Admin fields for hot paths; prefer definition `metadata` for product JSON
384
+ ],
385
+ },
376
386
  },
377
387
  },
378
388
  })
@@ -400,6 +410,16 @@ achievementPlugin({
400
410
 
401
411
  `me` query: `scope`, `limit`, `page`, `requestsLimit`, `reviews`. Leaderboard: `metric` (required), `scope`, `limit`, `page`.
402
412
 
413
+ ## Ongoing grants
414
+
415
+ Definitions default to **`lifecycle: 'once'`** (binary grant / revoke). Set **`ongoing`** when standing should be maintained on one grant row:
416
+
417
+ - Grant **`status`**: `active` \| `expired` \| `superseded` (default `active`)
418
+ - Optional **`renewedAt`**, **`supersededBy`** (relationship to another grant)
419
+ - Helpers: **`renewGrant`**, **`expireGrant`**, **`supersedeGrant`** (reject `once` definitions)
420
+ - Logs: `achievement.renewed` / `.expired` / `.superseded`
421
+ - Rule checks (`achievement-complete`) and composites only count **`active`** grants
422
+
403
423
  ## Server helpers
404
424
 
405
425
  Call these from hooks, jobs, and trusted endpoints:
@@ -411,6 +431,9 @@ import {
411
431
  getMetricLeaderboard,
412
432
  resolveMetricValue,
413
433
  grantAchievement,
434
+ renewGrant,
435
+ expireGrant,
436
+ supersedeGrant,
414
437
  reconcileProgression,
415
438
  reconcileUserProgression,
416
439
  resolveCurrentTier,
@@ -420,6 +443,9 @@ import {
420
443
  buildUnlockRequirementLeaves,
421
444
  submitAchievementRequest,
422
445
  reviewAchievementRequest,
446
+ submitTierRequest,
447
+ reviewTierRequest,
448
+ findTierRequestsForReview,
423
449
  logSubject,
424
450
  } from '@dappermountain/payload-plugin-achievements'
425
451
 
@@ -512,6 +538,8 @@ await seedAchievements(payload, {
512
538
  slug: 'first-steps',
513
539
  requiresReview: false,
514
540
  completionRules: [{ type: 'metric-minimum', metricSlug: 'points', minimum: 10 }],
541
+ // Optional host JSON — structure only; validate in the host (Zod, etc.)
542
+ metadata: { kind: 'action', effort: 'immediate' },
515
543
  },
516
544
  ],
517
545
  removeAchievementSlugs: ['old-slug'],
package/dist/catalog.d.ts CHANGED
@@ -4,6 +4,15 @@ export declare const ENGINE_EVENT_TYPES: readonly [{
4
4
  }, {
5
5
  readonly slug: "achievement.revoked";
6
6
  readonly name: "Achievement revoked";
7
+ }, {
8
+ readonly slug: "achievement.renewed";
9
+ readonly name: "Achievement renewed";
10
+ }, {
11
+ readonly slug: "achievement.expired";
12
+ readonly name: "Achievement expired";
13
+ }, {
14
+ readonly slug: "achievement.superseded";
15
+ readonly name: "Achievement superseded";
7
16
  }, {
8
17
  readonly slug: "metric.delta";
9
18
  readonly name: "Metric delta";
@@ -11,6 +20,15 @@ export declare const ENGINE_EVENT_TYPES: readonly [{
11
20
  }, {
12
21
  readonly slug: "tier.changed";
13
22
  readonly name: "Tier changed";
23
+ }, {
24
+ readonly slug: "tier.request.submitted";
25
+ readonly name: "Tier request submitted";
26
+ }, {
27
+ readonly slug: "tier.request.approved";
28
+ readonly name: "Tier request approved";
29
+ }, {
30
+ readonly slug: "tier.request.rejected";
31
+ readonly name: "Tier request rejected";
14
32
  }];
15
33
  export declare const ENGINE_METRICS: readonly [{
16
34
  readonly slug: "points";
@@ -22,7 +40,10 @@ export type EngineMetricSlug = (typeof ENGINE_METRICS)[number]['slug'];
22
40
  export declare const DEFAULT_ACHIEVEMENT_METRIC_SLUG: EngineMetricSlug;
23
41
  /** @deprecated Use {@link DEFAULT_ACHIEVEMENT_METRIC_SLUG}. */
24
42
  export declare const DEFAULT_ACHIEVEMENT_METRIC: "points";
25
- /** Grant/revoke audit logs — progression already runs from Grants hooks. */
43
+ /** Grant standing audit logs — progression already runs from Grants hooks / status helpers. */
26
44
  export declare const GRANT_AUDIT_EVENT_SLUGS: ReadonlySet<string>;
45
+ /** Tier-request lifecycle logs — TierRequests afterChange already syncs the ladder. */
46
+ export declare const TIER_REQUEST_AUDIT_EVENT_SLUGS: ReadonlySet<string>;
27
47
  export declare function isGrantAuditEventSlug(slug: string | null | undefined): boolean;
48
+ export declare function isTierRequestAuditEventSlug(slug: string | null | undefined): boolean;
28
49
  //# sourceMappingURL=catalog.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;EAKrB,CAAA;AAEV,eAAO,MAAM,cAAc;;;;EAAyE,CAAA;AAEpG,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;AAC7E,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;AAEtE,eAAO,MAAM,+BAA+B,EAAE,gBAA2B,CAAA;AAEzE,+DAA+D;AAC/D,eAAO,MAAM,0BAA0B,UAAkC,CAAA;AAEzE,4EAA4E;AAC5E,eAAO,MAAM,uBAAuB,EAAE,WAAW,CAAC,MAAM,CAGtD,CAAA;AAEF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAE9E"}
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWrB,CAAA;AAEV,eAAO,MAAM,cAAc;;;;EAAyE,CAAA;AAEpG,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;AAC7E,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAA;AAEtE,eAAO,MAAM,+BAA+B,EAAE,gBAA2B,CAAA;AAEzE,+DAA+D;AAC/D,eAAO,MAAM,0BAA0B,UAAkC,CAAA;AAEzE,+FAA+F;AAC/F,eAAO,MAAM,uBAAuB,EAAE,WAAW,CAAC,MAAM,CAMtD,CAAA;AAEF,uFAAuF;AACvF,eAAO,MAAM,8BAA8B,EAAE,WAAW,CAAC,MAAM,CAI7D,CAAA;AAEF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAE9E;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAEpF"}
package/dist/catalog.js CHANGED
@@ -1,18 +1,36 @@
1
1
  export const ENGINE_EVENT_TYPES = [
2
2
  { slug: 'achievement.granted', name: 'Achievement granted' },
3
3
  { slug: 'achievement.revoked', name: 'Achievement revoked' },
4
+ { slug: 'achievement.renewed', name: 'Achievement renewed' },
5
+ { slug: 'achievement.expired', name: 'Achievement expired' },
6
+ { slug: 'achievement.superseded', name: 'Achievement superseded' },
4
7
  { slug: 'metric.delta', name: 'Metric delta', requiresMetric: true },
5
8
  { slug: 'tier.changed', name: 'Tier changed' },
9
+ { slug: 'tier.request.submitted', name: 'Tier request submitted' },
10
+ { slug: 'tier.request.approved', name: 'Tier request approved' },
11
+ { slug: 'tier.request.rejected', name: 'Tier request rejected' },
6
12
  ];
7
13
  export const ENGINE_METRICS = [{ slug: 'points', name: 'Points', kind: 'stored' }];
8
14
  export const DEFAULT_ACHIEVEMENT_METRIC_SLUG = 'points';
9
15
  /** @deprecated Use {@link DEFAULT_ACHIEVEMENT_METRIC_SLUG}. */
10
16
  export const DEFAULT_ACHIEVEMENT_METRIC = DEFAULT_ACHIEVEMENT_METRIC_SLUG;
11
- /** Grant/revoke audit logs — progression already runs from Grants hooks. */
17
+ /** Grant standing audit logs — progression already runs from Grants hooks / status helpers. */
12
18
  export const GRANT_AUDIT_EVENT_SLUGS = new Set([
13
19
  'achievement.granted',
14
20
  'achievement.revoked',
21
+ 'achievement.renewed',
22
+ 'achievement.expired',
23
+ 'achievement.superseded',
24
+ ]);
25
+ /** Tier-request lifecycle logs — TierRequests afterChange already syncs the ladder. */
26
+ export const TIER_REQUEST_AUDIT_EVENT_SLUGS = new Set([
27
+ 'tier.request.submitted',
28
+ 'tier.request.approved',
29
+ 'tier.request.rejected',
15
30
  ]);
16
31
  export function isGrantAuditEventSlug(slug) {
17
32
  return typeof slug === 'string' && GRANT_AUDIT_EVENT_SLUGS.has(slug);
18
33
  }
34
+ export function isTierRequestAuditEventSlug(slug) {
35
+ return typeof slug === 'string' && TIER_REQUEST_AUDIT_EVENT_SLUGS.has(slug);
36
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/Achievements/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAO/C,wBAAgB,2BAA2B,IAAI,gBAAgB,CA8D9D"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/Achievements/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAO/C,wBAAgB,2BAA2B,IAAI,gBAAgB,CAoF9D"}
@@ -13,7 +13,7 @@ export function buildAchievementsCollection() {
13
13
  hooks,
14
14
  admin: collectionAdmin({
15
15
  useAsTitle: 'name',
16
- defaultColumns: columnsWithOptionalScope(['name', 'slug', 'requiresReview', 'scope']),
16
+ defaultColumns: columnsWithOptionalScope(['name', 'slug', 'lifecycle', 'requiresReview', 'scope']),
17
17
  description: 'What someone can earn. Set who’s eligible and whether a person on your team needs to approve it.',
18
18
  }),
19
19
  fields: [
@@ -33,6 +33,26 @@ export function buildAchievementsCollection() {
33
33
  ],
34
34
  },
35
35
  localizedDescriptionField(),
36
+ {
37
+ name: 'metadata',
38
+ type: 'json',
39
+ admin: {
40
+ description: 'Optional host/product payload (structure only). Shape is owned by the host — validate with Zod or similar at read/seed time. Do not store localized copy here; use name, description, and host i18n.',
41
+ },
42
+ },
43
+ {
44
+ name: 'lifecycle',
45
+ type: 'select',
46
+ required: true,
47
+ defaultValue: 'once',
48
+ options: [
49
+ { label: 'Once', value: 'once' },
50
+ { label: 'Ongoing', value: 'ongoing' },
51
+ ],
52
+ admin: {
53
+ description: 'Once: binary grant (create/delete). Ongoing: one grant row whose status can be active, expired, or superseded.',
54
+ },
55
+ },
36
56
  {
37
57
  name: 'requiresReview',
38
58
  type: 'checkbox',
@@ -49,7 +69,7 @@ export function buildAchievementsCollection() {
49
69
  admin: {
50
70
  description: 'Who may request this achievement. Composed parents that auto-grant should leave this empty.',
51
71
  },
52
- fields: buildRuleTreeFields({ dbName: 'ach_elig_r' }),
72
+ fields: buildRuleTreeFields({ site: 'eligibility' }),
53
73
  },
54
74
  {
55
75
  name: 'completionRules',
@@ -58,7 +78,7 @@ export function buildAchievementsCollection() {
58
78
  admin: {
59
79
  description: 'What this achievement is made of. When every rule passes, it is granted automatically (do not require review on composed parents). Nested achievements appear in this order in your app UI.',
60
80
  },
61
- fields: buildRuleTreeFields({ dbName: 'ach_comp_r' }),
81
+ fields: buildRuleTreeFields({ site: 'completion' }),
62
82
  },
63
83
  ],
64
84
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/Grants/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAQtD,wBAAgB,qBAAqB,IAAI,gBAAgB,CA4ExD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/Grants/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAQtD,wBAAgB,qBAAqB,IAAI,gBAAgB,CA4GxD"}
@@ -18,9 +18,9 @@ export function buildGrantsCollection() {
18
18
  hooks,
19
19
  admin: collectionAdmin({
20
20
  useAsTitle: 'title',
21
- defaultColumns: columnsWithOptionalScope(['title', 'user', 'completedAt', 'scope']),
21
+ defaultColumns: columnsWithOptionalScope(['title', 'user', 'status', 'completedAt', 'scope']),
22
22
  listSearchableFields: ['title'],
23
- description: 'What someone has earned — one row per grant. Creating or deleting a grant updates logs and composed progression automatically.',
23
+ description: 'What someone has earned — one row per user and achievement (+ scope). Creating or deleting a grant updates logs and composed progression. Ongoing definitions keep the row and change status instead of deleting.',
24
24
  ...(apiPath
25
25
  ? {
26
26
  components: {
@@ -69,6 +69,37 @@ export function buildGrantsCollection() {
69
69
  },
70
70
  ],
71
71
  },
72
+ {
73
+ name: 'status',
74
+ type: 'select',
75
+ required: true,
76
+ defaultValue: 'active',
77
+ index: true,
78
+ options: [
79
+ { label: 'Active', value: 'active' },
80
+ { label: 'Expired', value: 'expired' },
81
+ { label: 'Superseded', value: 'superseded' },
82
+ ],
83
+ admin: {
84
+ description: 'Standing for ongoing achievements. Once achievements stay active until the grant is deleted. Prefer renew / expire / supersede helpers over editing this by hand.',
85
+ },
86
+ },
87
+ {
88
+ name: 'renewedAt',
89
+ type: 'date',
90
+ admin: {
91
+ date: { pickerAppearance: 'dayAndTime' },
92
+ description: 'Last renew time for an ongoing grant.',
93
+ },
94
+ },
95
+ {
96
+ name: 'supersededBy',
97
+ type: 'relationship',
98
+ relationTo: collectionOf('grants'),
99
+ admin: {
100
+ description: 'Grant that replaced this one when status is superseded.',
101
+ },
102
+ },
72
103
  {
73
104
  name: 'note',
74
105
  type: 'textarea',
@@ -1,7 +1,7 @@
1
1
  import type { CollectionAfterChangeHook, CollectionBeforeValidateHook } from 'payload';
2
2
  /**
3
3
  * System-created requests (reconcile / progression sync) may set user freely.
4
- * Member creates are not used for tiers in v1 — reviewers/system own the flow.
4
+ * Member creates bind `req.user`, require unlock rules, and requireReview on the tier.
5
5
  */
6
6
  export declare const prepareTierRequest: CollectionBeforeValidateHook;
7
7
  export declare const afterTierRequestChange: CollectionAfterChangeHook;
@@ -1 +1 @@
1
- {"version":3,"file":"prepareTierRequest.d.ts","sourceRoot":"","sources":["../../../../src/collections/TierRequests/hooks/prepareTierRequest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,4BAA4B,EAE7B,MAAM,SAAS,CAAA;AAYhB;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,4BAyChC,CAAA;AAED,eAAO,MAAM,sBAAsB,EAAE,yBAoBpC,CAAA"}
1
+ {"version":3,"file":"prepareTierRequest.d.ts","sourceRoot":"","sources":["../../../../src/collections/TierRequests/hooks/prepareTierRequest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,yBAAyB,EACzB,4BAA4B,EAE7B,MAAM,SAAS,CAAA;AA2BhB;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,4BAiGhC,CAAA;AA8CD,eAAO,MAAM,sBAAsB,EAAE,yBAkCpC,CAAA"}
@@ -1,56 +1,163 @@
1
1
  import { APIError } from 'payload';
2
2
  import { collectionOf } from '../../../collections/helpers.js';
3
3
  import { CTX_SYSTEM_REQUEST } from '../../../services/achievement/contextFlags.js';
4
- import { syncTierChangedLog } from '../../../services/achievement/recordEvent.js';
4
+ import { evaluateRules } from '../../../services/achievement/evaluateRules.js';
5
+ import { catalogRef } from '../../../services/achievement/logData.js';
6
+ import { recordLog, syncTierChangedLog } from '../../../services/achievement/recordEvent.js';
5
7
  import { relationId } from '../../../services/achievement/relationId.js';
6
8
  function scopeIdOf(data) {
7
9
  return relationId(data?.scope);
8
10
  }
11
+ const TIER_REQUEST_STATUS_EVENT = {
12
+ pending: 'tier.request.submitted',
13
+ approved: 'tier.request.approved',
14
+ rejected: 'tier.request.rejected',
15
+ };
9
16
  /**
10
17
  * System-created requests (reconcile / progression sync) may set user freely.
11
- * Member creates are not used for tiers in v1 — reviewers/system own the flow.
18
+ * Member creates bind `req.user`, require unlock rules, and requireReview on the tier.
12
19
  */
13
20
  export const prepareTierRequest = async ({ data, operation, req, originalDoc, }) => {
14
21
  if (!data)
15
22
  return data;
16
23
  if (operation === 'create') {
17
- if (!req.context?.[CTX_SYSTEM_REQUEST]) {
24
+ const system = Boolean(req.context?.[CTX_SYSTEM_REQUEST]);
25
+ if (!system) {
18
26
  const userId = req.user?.id;
19
27
  if (typeof userId !== 'string')
20
28
  throw new APIError('Unauthorized', 401);
21
29
  data.user = userId;
22
30
  }
31
+ else {
32
+ const bound = relationId(data.user);
33
+ if (!bound)
34
+ throw new APIError('user required', 400);
35
+ data.user = bound;
36
+ }
37
+ const userId = relationId(data.user);
38
+ if (!userId)
39
+ throw new APIError('user required', 400);
23
40
  const tierId = relationId(data.tier);
24
41
  if (!tierId)
25
42
  throw new APIError('tier required', 400);
26
- const tier = await req.payload.findByID({
43
+ const tier = (await req.payload.findByID({
27
44
  collection: collectionOf('tiers'),
28
45
  id: tierId,
29
46
  depth: 0,
30
47
  overrideAccess: true,
31
48
  req,
32
- });
49
+ }));
33
50
  if (!tier)
34
51
  throw new APIError(`Unknown tier: ${tierId}`, 400);
35
52
  if (tier.requiresReview !== true) {
36
53
  throw new APIError('This tier does not require review.', 400);
37
54
  }
38
55
  data.tier = tierId;
39
- if (!data.status)
56
+ if (!system) {
57
+ const scopeId = scopeIdOf(data);
58
+ const unlocked = await evaluateRules({
59
+ payload: req.payload,
60
+ req,
61
+ rules: tier.unlockRules,
62
+ userId,
63
+ scopeId,
64
+ });
65
+ if (!unlocked) {
66
+ throw new APIError('Unlock rules not met for this tier.', 400);
67
+ }
68
+ // Members cannot self-approve; only reviewers / system may set approved|rejected.
69
+ data.status = 'pending';
70
+ }
71
+ else if (!data.status) {
40
72
  data.status = 'pending';
73
+ }
41
74
  return data;
42
75
  }
43
76
  if (operation === 'update' && originalDoc) {
44
77
  data.user = originalDoc.user;
45
78
  data.tier = originalDoc.tier;
79
+ const nextStatus = typeof data.status === 'string' ? data.status : undefined;
80
+ const prevStatus = originalDoc.status;
81
+ if (nextStatus === 'pending' && prevStatus && prevStatus !== 'pending') {
82
+ const userId = relationId(originalDoc.user);
83
+ const tierId = relationId(originalDoc.tier);
84
+ if (userId && tierId) {
85
+ const tier = (await req.payload.findByID({
86
+ collection: collectionOf('tiers'),
87
+ id: tierId,
88
+ depth: 0,
89
+ overrideAccess: true,
90
+ req,
91
+ }));
92
+ const scopeId = scopeIdOf({
93
+ scope: data.scope ?? originalDoc.scope,
94
+ });
95
+ const unlocked = await evaluateRules({
96
+ payload: req.payload,
97
+ req,
98
+ rules: (tier?.unlockRules ?? []),
99
+ userId,
100
+ scopeId,
101
+ });
102
+ if (!unlocked) {
103
+ throw new APIError('Unlock rules not met for this tier.', 400);
104
+ }
105
+ }
106
+ }
46
107
  }
47
108
  return data;
48
109
  };
49
- export const afterTierRequestChange = async ({ doc, req, }) => {
110
+ async function recordTierRequestStatusLog(args) {
111
+ const eventType = TIER_REQUEST_STATUS_EVENT[args.status];
112
+ if (!eventType)
113
+ return;
114
+ // Only log real transitions (and create-as-pending / create-as-approved).
115
+ if (args.previousStatus === args.status)
116
+ return;
117
+ const userId = relationId(args.doc.user);
118
+ const tierId = relationId(args.doc.tier);
119
+ if (!userId || !tierId)
120
+ return;
121
+ const tier = (await args.req.payload.findByID({
122
+ collection: collectionOf('tiers'),
123
+ id: tierId,
124
+ depth: 0,
125
+ overrideAccess: true,
126
+ req: args.req,
127
+ select: { slug: true },
128
+ }));
129
+ const scopeId = scopeIdOf(args.doc);
130
+ const requestId = typeof args.doc.id === 'string' ? args.doc.id : String(args.doc.id ?? '');
131
+ await recordLog({
132
+ payload: args.req.payload,
133
+ req: args.req,
134
+ userId,
135
+ scopeId,
136
+ type: eventType,
137
+ actorId: typeof args.req.user?.id === 'string' ? args.req.user.id : undefined,
138
+ data: {
139
+ requestId,
140
+ status: args.status,
141
+ fromStatus: args.previousStatus,
142
+ tier: catalogRef(tierId, tier?.slug),
143
+ },
144
+ });
145
+ }
146
+ export const afterTierRequestChange = async ({ doc, operation, previousDoc, req, }) => {
50
147
  const userId = relationId(doc.user);
51
148
  if (!userId)
52
149
  return doc;
53
150
  const scopeId = scopeIdOf(doc);
151
+ const status = typeof doc.status === 'string' ? doc.status : '';
152
+ const previousStatus = operation === 'update' && previousDoc && typeof previousDoc.status === 'string'
153
+ ? previousDoc.status
154
+ : null;
155
+ await recordTierRequestStatusLog({
156
+ req: req,
157
+ doc: doc,
158
+ previousStatus,
159
+ status,
160
+ });
54
161
  // Any status transition (or create as pending/rejected/approved) can change the
55
162
  // live ladder — including demotions when approved → pending/rejected. Sync is
56
163
  // idempotent when the latest audit already matches resolveCurrentTier.
@@ -40,7 +40,7 @@ export function buildTierRequestsCollection() {
40
40
  {
41
41
  name: 'note',
42
42
  type: 'textarea',
43
- admin: { description: 'Optional note from the reviewer.' },
43
+ admin: { description: 'Optional note from the requester or reviewer.' },
44
44
  },
45
45
  ],
46
46
  };
@@ -85,7 +85,7 @@ export function buildTiersCollection() {
85
85
  admin: {
86
86
  description: 'Rules that must pass to unlock this tier (all-of or any-of). Empty rules mean this step is open. Current tier is derived by walking ranks; optional tier.changed logs record moves.',
87
87
  },
88
- fields: buildRuleTreeFields({ dbName: 'ach_unlk_r' }),
88
+ fields: buildRuleTreeFields({ site: 'unlock' }),
89
89
  },
90
90
  ],
91
91
  };
@@ -4,6 +4,7 @@ import type { AchievementCollectionOverride } from '../types.js';
4
4
  * Layer host overrides on a plugin collection:
5
5
  * - `access` / `admin` / `labels`: shallow merge (host wins per key)
6
6
  * - `hooks`: append host hook arrays after the plugin’s (plugin runs first)
7
+ * - `fields`: replace — function receives `{ defaultFields }` (Form Builder–style)
7
8
  */
8
9
  export declare function applyCollectionOverrides(collection: CollectionConfig, override?: AchievementCollectionOverride): CollectionConfig;
9
10
  //# sourceMappingURL=applyOverrides.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"applyOverrides.d.ts","sourceRoot":"","sources":["../../src/collections/applyOverrides.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAA;AAEhE;;;;GAIG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,gBAAgB,EAC5B,QAAQ,CAAC,EAAE,6BAA6B,GACvC,gBAAgB,CA6BlB"}
1
+ {"version":3,"file":"applyOverrides.d.ts","sourceRoot":"","sources":["../../src/collections/applyOverrides.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAS,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,aAAa,CAAA;AAEhE;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,gBAAgB,EAC5B,QAAQ,CAAC,EAAE,6BAA6B,GACvC,gBAAgB,CAsClB"}
@@ -2,6 +2,7 @@
2
2
  * Layer host overrides on a plugin collection:
3
3
  * - `access` / `admin` / `labels`: shallow merge (host wins per key)
4
4
  * - `hooks`: append host hook arrays after the plugin’s (plugin runs first)
5
+ * - `fields`: replace — function receives `{ defaultFields }` (Form Builder–style)
5
6
  */
6
7
  export function applyCollectionOverrides(collection, override) {
7
8
  if (!override)
@@ -18,6 +19,12 @@ export function applyCollectionOverrides(collection, override) {
18
19
  hooks[key] = [...base, ...extra];
19
20
  }
20
21
  }
22
+ const defaultFields = (collection.fields ?? []);
23
+ const fields = override.fields == null
24
+ ? undefined
25
+ : typeof override.fields === 'function'
26
+ ? override.fields({ defaultFields })
27
+ : override.fields;
21
28
  return {
22
29
  ...collection,
23
30
  access: {
@@ -29,6 +36,7 @@ export function applyCollectionOverrides(collection, override) {
29
36
  ...override.admin,
30
37
  },
31
38
  ...(override.labels ? { labels: override.labels } : {}),
39
+ ...(fields ? { fields } : {}),
32
40
  hooks,
33
41
  };
34
42
  }
@@ -1,6 +1,6 @@
1
1
  export { scopeField } from './scopeField.js';
2
2
  export { userField } from './userField.js';
3
- export { assertSafeRuleArrayDbName, buildRuleRowFields, buildRuleTreeFields, POSTGRES_IDENTIFIER_MAX, ruleArrayIdentifierLength, type BuildRuleTreeFieldsArgs, } from './ruleFields.js';
3
+ export { assertSafeRuleArrayDbName, buildRuleRowFields, buildRuleTreeFields, collectionTableName, maxRuleArrayDbNameLength, POSTGRES_IDENTIFIER_MAX, resolvedCollectionsPrefix, ruleArrayDbName, ruleArrayIdentifierLength, sanitizeDbIdentifierSegment, type BuildRuleTreeFieldsArgs, type RuleArraySite, } from './ruleFields.js';
4
4
  export { usersAchievementsGroup } from './usersAchievementsGroup.js';
5
5
  export { localizedDescriptionField, localizedNameField } from './localizedText.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/fields/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,EACvB,yBAAyB,EACzB,KAAK,uBAAuB,GAC7B,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAA;AACpE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/collections/fields/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,yBAAyB,EACzB,eAAe,EACf,yBAAyB,EACzB,2BAA2B,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,aAAa,GACnB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAA;AACpE,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA"}
@@ -1,5 +1,5 @@
1
1
  export { scopeField } from './scopeField.js';
2
2
  export { userField } from './userField.js';
3
- export { assertSafeRuleArrayDbName, buildRuleRowFields, buildRuleTreeFields, POSTGRES_IDENTIFIER_MAX, ruleArrayIdentifierLength, } from './ruleFields.js';
3
+ export { assertSafeRuleArrayDbName, buildRuleRowFields, buildRuleTreeFields, collectionTableName, maxRuleArrayDbNameLength, POSTGRES_IDENTIFIER_MAX, resolvedCollectionsPrefix, ruleArrayDbName, ruleArrayIdentifierLength, sanitizeDbIdentifierSegment, } from './ruleFields.js';
4
4
  export { usersAchievementsGroup } from './usersAchievementsGroup.js';
5
5
  export { localizedDescriptionField, localizedNameField } from './localizedText.js';