@proveanything/smartlinks 2.1.40 → 2.1.41

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 (104) hide show
  1. package/README.md +754 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/api/collection.d.ts +8 -1
  5. package/dist/api/collection.js +10 -0
  6. package/dist/baseline.css +194 -194
  7. package/dist/docs/API_SUMMARY.md +863 -835
  8. package/dist/docs/admin-cards.md +189 -189
  9. package/dist/docs/agent-tools.md +156 -156
  10. package/dist/docs/ai-tools-and-skills.md +180 -180
  11. package/dist/docs/ai.md +1721 -1721
  12. package/dist/docs/analytics.md +39 -39
  13. package/dist/docs/app-data-storage.md +277 -277
  14. package/dist/docs/app-docs.md +73 -73
  15. package/dist/docs/app-manifest.md +852 -852
  16. package/dist/docs/app-records-pattern.md +388 -388
  17. package/dist/docs/appConfig.md +550 -550
  18. package/dist/docs/assistant-apps.md +172 -172
  19. package/dist/docs/assistant-context.md +119 -119
  20. package/dist/docs/bookings.md +442 -442
  21. package/dist/docs/comms.md +686 -686
  22. package/dist/docs/connectors.md +340 -340
  23. package/dist/docs/css-baseline.md +133 -133
  24. package/dist/docs/customer-guide.md +70 -70
  25. package/dist/docs/deploying-apps.md +340 -340
  26. package/dist/docs/entitlements.md +90 -90
  27. package/dist/docs/files.md +69 -69
  28. package/dist/docs/host-dependency-contract.md +210 -210
  29. package/dist/docs/integrations.md +322 -322
  30. package/dist/docs/interactions.md +545 -545
  31. package/dist/docs/item-context.md +181 -181
  32. package/dist/docs/knowledge.md +102 -102
  33. package/dist/docs/lots.md +111 -111
  34. package/dist/docs/loyalty.md +352 -352
  35. package/dist/docs/members.md +182 -182
  36. package/dist/docs/mobile-admin-container.md +693 -693
  37. package/dist/docs/operations.md +281 -281
  38. package/dist/docs/overview.md +482 -482
  39. package/dist/docs/proof-comms-triggers.md +142 -142
  40. package/dist/docs/proof-ownership-transfer.md +155 -155
  41. package/dist/docs/proof-product-data-scoping.md +462 -462
  42. package/dist/docs/proof-share-grants.md +305 -305
  43. package/dist/docs/realtime.md +138 -138
  44. package/dist/docs/records-admin-pattern.md +304 -304
  45. package/dist/docs/standard-query.md +187 -187
  46. package/dist/docs/tag-codes.md +97 -97
  47. package/dist/docs/theme-tokens.md +252 -252
  48. package/dist/docs/wallet-passes.md +107 -107
  49. package/dist/docs/websites.md +123 -123
  50. package/dist/openapi.yaml +80 -3
  51. package/dist/theme-boot.js +78 -78
  52. package/dist/theme.css +75 -75
  53. package/dist/types/appManifest.d.ts +21 -0
  54. package/dist/types/collection.d.ts +26 -0
  55. package/docs/API_SUMMARY.md +863 -835
  56. package/docs/admin-cards.md +189 -189
  57. package/docs/agent-tools.md +156 -156
  58. package/docs/ai-tools-and-skills.md +180 -180
  59. package/docs/ai.md +1721 -1721
  60. package/docs/analytics.md +39 -39
  61. package/docs/app-data-storage.md +277 -277
  62. package/docs/app-docs.md +73 -73
  63. package/docs/app-manifest.md +852 -852
  64. package/docs/app-records-pattern.md +388 -388
  65. package/docs/appConfig.md +550 -550
  66. package/docs/assistant-apps.md +172 -172
  67. package/docs/assistant-context.md +119 -119
  68. package/docs/bookings.md +442 -442
  69. package/docs/comms.md +686 -686
  70. package/docs/connectors.md +340 -340
  71. package/docs/css-baseline.md +133 -133
  72. package/docs/customer-guide.md +70 -70
  73. package/docs/deploying-apps.md +340 -340
  74. package/docs/entitlements.md +90 -90
  75. package/docs/files.md +69 -69
  76. package/docs/host-dependency-contract.md +210 -210
  77. package/docs/integrations.md +322 -322
  78. package/docs/interactions.md +545 -545
  79. package/docs/item-context.md +181 -181
  80. package/docs/knowledge.md +102 -102
  81. package/docs/lots.md +111 -111
  82. package/docs/loyalty.md +352 -352
  83. package/docs/members.md +182 -182
  84. package/docs/mobile-admin-container.md +693 -693
  85. package/docs/operations.md +281 -281
  86. package/docs/overview.md +482 -482
  87. package/docs/proof-comms-triggers.md +142 -142
  88. package/docs/proof-ownership-transfer.md +155 -155
  89. package/docs/proof-product-data-scoping.md +462 -462
  90. package/docs/proof-share-grants.md +305 -305
  91. package/docs/realtime.md +138 -138
  92. package/docs/standard-query.md +187 -187
  93. package/docs/tag-codes.md +97 -97
  94. package/docs/theme-lookbook.v1.json +120 -120
  95. package/docs/theme-tokens.md +252 -252
  96. package/docs/wallet-passes.md +107 -107
  97. package/docs/websites.md +123 -123
  98. package/openapi.yaml +80 -3
  99. package/package.json +87 -87
  100. package/scripts/headless-check.mjs +87 -87
  101. package/scripts/lib/bare-imports.mjs +57 -57
  102. package/scripts/lib/keyed-app-data.mjs +21 -21
  103. package/scripts/publish.mjs +272 -272
  104. package/scripts/register-release.mjs +91 -91
package/docs/loyalty.md CHANGED
@@ -1,352 +1,352 @@
1
- # Loyalty: Points, Members & Earning Rules
2
-
3
- The `loyalty` namespace lets you build loyalty programmes on top of any collection. Contacts earn points for doing things — registering products, voting, entering competitions, engaging with content — and you track their balance, lifetime points, and full transaction history.
4
-
5
- Loyalty is designed to be **decoupled from your app logic**. You configure earning rules that say "this interaction earns N points under these conditions", and the platform awards points automatically whenever that interaction event fires. Your app just logs interactions as normal.
6
-
7
- ---
8
-
9
- ## Core Concepts
10
-
11
- | Concept | Description |
12
- |---------|-------------|
13
- | **Scheme** | A named loyalty programme within a collection (e.g. "Brand Rewards"). A collection can have multiple schemes. |
14
- | **Member** | A contact's enrolment in a scheme. Created automatically the first time they earn points. Holds their current `balance` and `lifetimePoints`. |
15
- | **Transaction** | An append-only ledger entry. Signed integer — positive = earn, negative = spend/deduct. Every point change goes through a transaction. |
16
- | **Earning Rule** | Links an Interaction definition to a point award. When an interaction event fires that matches the rule's conditions, points are awarded automatically. |
17
-
18
- ```text
19
- ┌─────────────────────────────────────────────────────────────────────┐
20
- │ User registers a product │
21
- │ ↓ │
22
- │ interactions.appendEvent(collectionId, { │
23
- │ interactionId: 'product-registration', │
24
- │ outcome: 'activated', │
25
- │ contactId: '...' │
26
- │ }) │
27
- │ ↓ │
28
- │ Platform evaluates earning rules for 'product-registration' │
29
- │ ↓ │
30
- │ Rule matches → contact awarded 50 points automatically │
31
- │ ↓ │
32
- │ loyalty.publicGetMe(collectionId) → balance: 50 │
33
- └─────────────────────────────────────────────────────────────────────┘
34
- ```
35
-
36
- ---
37
-
38
- ## Schemes
39
-
40
- ### Create a Scheme
41
-
42
- ```typescript
43
- const scheme = await SL.loyalty.create(collectionId, {
44
- name: 'Brand Rewards',
45
- type: 'points',
46
- data: {
47
- pointName: 'Star', // Display name for one point
48
- pointNamePlural: 'Stars',
49
- currencySymbol: '⭐',
50
- },
51
- });
52
- ```
53
-
54
- ### List & Get
55
-
56
- ```typescript
57
- // Admin: all schemes including inactive/deleted
58
- const schemes = await SL.loyalty.list(collectionId);
59
- const scheme = await SL.loyalty.get(collectionId, schemeId);
60
-
61
- // Public: active schemes only (no admin/owner data blocks)
62
- const schemes = await SL.loyalty.publicList(collectionId);
63
- const scheme = await SL.loyalty.publicGet(collectionId, schemeId);
64
- ```
65
-
66
- ### Update & Delete
67
-
68
- ```typescript
69
- await SL.loyalty.update(collectionId, schemeId, { active: false });
70
- await SL.loyalty.remove(collectionId, schemeId); // soft-delete
71
- ```
72
-
73
- ---
74
-
75
- ## Getting a User's Loyalty Status
76
-
77
- ### The one-call pattern
78
-
79
- `publicGetMe` is the primary entry point for any loyalty UI. It returns all active schemes with the caller's membership embedded — one request, everything you need.
80
-
81
- ```typescript
82
- const schemes = await SL.loyalty.publicGetMe(collectionId);
83
-
84
- // schemes[0] looks like:
85
- // {
86
- // id: 'abc-123',
87
- // name: 'Brand Rewards',
88
- // type: 'points',
89
- // data: { pointName: 'Star', ... },
90
- // member: {
91
- // balance: 350,
92
- // lifetimePoints: 820,
93
- // contactId: '...',
94
- // createdAt: '...',
95
- // ...
96
- // }
97
- // }
98
- //
99
- // member is null if the user hasn't earned any points yet in that scheme
100
- ```
101
-
102
- Unauthenticated callers get `member: null` on every scheme — useful for previewing the programme before sign-in.
103
-
104
- ### Scheme-specific membership
105
-
106
- ```typescript
107
- // Current balance + lifetime points
108
- const member = await SL.loyalty.publicGetMine(collectionId, schemeId);
109
-
110
- // Transaction history (newest first, paginated)
111
- const { items } = await SL.loyalty.publicGetMineHistory(collectionId, schemeId, {
112
- limit: 20,
113
- offset: 0,
114
- });
115
- ```
116
-
117
- ---
118
-
119
- ## Earning Rules
120
-
121
- Earning rules are the control plane that connects interactions to point awards. The server evaluates them automatically — your app never sets a point value directly.
122
-
123
- Every `interactionId` in a loyalty rule must reference an existing interaction type definition in the same collection.
124
-
125
- ### Create a Rule
126
-
127
- ```typescript
128
- // Award 50 points when a product is registered
129
- await SL.loyalty.createEarningRule(collectionId, schemeId, {
130
- interactionId: 'product-registration',
131
- points: 50,
132
- conditions: { outcome: 'activated' }, // only fires on this outcome
133
- maxPerContact: 1, // once per contact lifetime
134
- });
135
-
136
- // Award 1 point for any vote, no limit, 24-hour cooldown
137
- await SL.loyalty.createEarningRule(collectionId, schemeId, {
138
- interactionId: 'competition-vote',
139
- points: 1,
140
- cooldownHours: 24,
141
- });
142
-
143
- // Award 10 points for winning — conditions match event fields
144
- await SL.loyalty.createEarningRule(collectionId, schemeId, {
145
- interactionId: 'spin-to-win',
146
- points: 10,
147
- conditions: { outcome: 'win' },
148
- });
149
-
150
- // Award 2 points for entering — same interaction, different rule
151
- await SL.loyalty.createEarningRule(collectionId, schemeId, {
152
- interactionId: 'spin-to-win',
153
- points: 2,
154
- conditions: { outcome: 'entered' },
155
- cooldownHours: 24,
156
- });
157
- ```
158
-
159
- Multiple rules can reference the same `interactionId`. All matching rules fire — so an event can earn points from several rules simultaneously if you design them that way.
160
-
161
- ### Conditions
162
-
163
- Conditions are key-value pairs matched against the interaction event before a rule fires. An empty `conditions` object means the rule always fires for any event on that interaction.
164
-
165
- | Condition key | What it matches |
166
- |---------------|-----------------|
167
- | `outcome` | `event.outcome` |
168
- | `scope` | `event.scope` |
169
- | `status` | `event.status` |
170
- | `eventType` | `event.eventType` |
171
- | `metadata.tier` | `event.metadata.tier` |
172
- | `metadata.region` | `event.metadata.region` |
173
-
174
- ```typescript
175
- // Only award points to gold-tier members in UK events
176
- await SL.loyalty.createEarningRule(collectionId, schemeId, {
177
- interactionId: 'competition-entry',
178
- points: 5,
179
- conditions: {
180
- outcome: 'entered',
181
- 'metadata.tier': 'gold',
182
- 'metadata.region': 'UK',
183
- },
184
- });
185
- ```
186
-
187
- ### Rate Limiting
188
-
189
- | Field | Effect |
190
- |-------|--------|
191
- | `maxPerContact` | Caps the total lifetime number of times this rule can fire per contact. `null` = unlimited. |
192
- | `cooldownHours` | Minimum gap between triggers for the same contact. `null` = no cooldown. |
193
-
194
- ### List, Update & Delete Rules
195
-
196
- ```typescript
197
- // List rules (admin)
198
- const rules = await SL.loyalty.listEarningRules(collectionId, schemeId);
199
-
200
- // Public: show "how to earn" in UI (active rules only)
201
- const rules = await SL.loyalty.publicListEarningRules(collectionId, schemeId);
202
-
203
- // Update
204
- await SL.loyalty.updateEarningRule(collectionId, schemeId, ruleId, {
205
- points: 75,
206
- active: false,
207
- });
208
-
209
- // Delete
210
- await SL.loyalty.removeEarningRule(collectionId, schemeId, ruleId);
211
- ```
212
-
213
- ---
214
-
215
- ## Manual Transactions (Admin)
216
-
217
- For welcome bonuses, corrections, or admin overrides — points that aren't tied to an interaction event.
218
-
219
- ```typescript
220
- // Award a welcome bonus
221
- await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
222
- points: 100,
223
- reason: 'Welcome bonus',
224
- idempotencyKey: `welcome-${contactId}`, // prevents double-award on retry
225
- });
226
-
227
- // Deduct points (spend)
228
- await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
229
- points: -50,
230
- reason: 'Redeemed for discount',
231
- metadata: { redemptionRef: 'DISC-2026-0042' },
232
- });
233
- ```
234
-
235
- Deducting below zero returns HTTP 422 `INSUFFICIENT_BALANCE`. The transaction is rejected — the balance is never taken negative.
236
-
237
- ### Idempotency
238
-
239
- Supply `idempotencyKey` whenever there is any risk of the request being retried (network failures, client retries, webhook replays). The key is scoped per scheme — reusing it on a different scheme is fine.
240
-
241
- ```typescript
242
- await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
243
- points: 50,
244
- reason: 'Referral reward',
245
- idempotencyKey: `referral-${referrerId}-${refereeId}`,
246
- });
247
- // Calling again with the same key returns 409 — no duplicate transaction created
248
- ```
249
-
250
- ### Viewing Member History (Admin)
251
-
252
- ```typescript
253
- // All members in a scheme
254
- const { items } = await SL.loyalty.listMembers(collectionId, schemeId, { limit: 50 });
255
-
256
- // A specific member
257
- const member = await SL.loyalty.getMember(collectionId, schemeId, contactId);
258
-
259
- // Full transaction history for a member
260
- const { items } = await SL.loyalty.getMemberHistory(collectionId, schemeId, contactId, {
261
- limit: 100,
262
- offset: 0,
263
- });
264
- ```
265
-
266
- ---
267
-
268
- ## balance vs lifetimePoints
269
-
270
- | Field | What it tracks | Can it decrease? |
271
- |-------|---------------|-----------------|
272
- | `balance` | Current redeemable points | Yes — deducted on spend |
273
- | `lifetimePoints` | Total ever earned | Never — only increases |
274
-
275
- Use `lifetimePoints` for tier calculations (Bronze / Silver / Gold). Use `balance` for showing what a contact can currently spend.
276
-
277
- ---
278
-
279
- ## Integration with Interactions
280
-
281
- Loyalty earning is a side-effect of the interaction system. Your app calls `interactions.appendEvent` exactly as it would without loyalty — the platform handles the rest.
282
-
283
- ```typescript
284
- // Your app logs an interaction event as normal
285
- await SL.interactions.appendEvent(collectionId, {
286
- appId: 'my-app',
287
- interactionId: 'product-registration',
288
- outcome: 'activated',
289
- contactId: contact.contactId,
290
- productId: product.id,
291
- metadata: { serialNumber: 'SN-12345' },
292
- });
293
-
294
- // Behind the scenes (no app code needed):
295
- // 1. Event is logged to BigQuery
296
- // 2. Platform checks earning rules for 'product-registration'
297
- // 3. Matching rules fire → contact's balance updated atomically
298
- // 4. Transaction appended to ledger with ruleId in metadata
299
- ```
300
-
301
- A loyalty failure never causes the interaction event to fail — errors are caught and logged server-side so your app always gets a clean response.
302
-
303
- ---
304
-
305
- ## External loyalty platforms
306
-
307
- The schemes above are SmartLinks' own points. When a brand runs its programme on an external loyalty or
308
- engagement platform, the platform stays the record of truth and SmartLinks connects to it through a
309
- **connector app** and the integration engine — no member base is mirrored here:
310
-
311
- | Flow | How |
312
- |---|---|
313
- | **Earn** — what happens on a pack or in a Hub awards points there | an outbound flow with `sourceEntity: 'interaction' \| 'event'`, an `eventMapping` onto the provider's registered events, signed delivery, retries — [integrations.md](integrations.md#event-sourced-flows-and-the-envelope) |
314
- | **Profile** — member id, tier and points on the contact | the connector's webhook function calls `ctx.sl.members.apply(...)`; the contact gets `customFields.loyalty` and flat `loyaltyTier / loyaltyPoints / loyaltyMemberId`, usable in segments and comms targeting — [connectors.md](connectors.md#loyalty-and-crm-connectors) |
315
- | **Gate / display** — "Gold members only", live balance | the entitlement check, answered on demand from a signed claim, the connector's cached `lookup`, or the contact's fields — [entitlements.md](entitlements.md) |
316
-
317
- A collection runs one loyalty source: the native schemes here, or an external provider through a
318
- connector.
319
-
320
- ---
321
-
322
- ## TypeScript Types
323
-
324
- ```typescript
325
- import type {
326
- LoyaltyScheme, // Scheme definition
327
- LoyaltyMember, // Contact's enrolment + balance
328
- LoyaltyTransaction, // Single ledger entry
329
- LoyaltyEarningRule, // Interaction → points mapping
330
- LoyaltySchemeWithMembership, // publicGetMe() response shape
331
- LoyaltyTransactionResult, // recordTransaction() response
332
- LoyaltyPaginatedResult, // { items, limit, offset }
333
- LoyaltyPaginationParams, // { limit?, offset? }
334
- CreateLoyaltySchemeBody,
335
- UpdateLoyaltySchemeBody,
336
- CreateLoyaltyEarningRuleBody,
337
- UpdateLoyaltyEarningRuleBody,
338
- RecordLoyaltyTransactionBody,
339
- } from '@proveanything/smartlinks';
340
- ```
341
-
342
- ---
343
-
344
- ## Best Practices
345
-
346
- - Use `publicGetMe` as your single loyalty widget data source — one call, all schemes, membership embedded
347
- - Always supply `idempotencyKey` on manual transactions that could be retried
348
- - Use `maxPerContact: 1` on one-time actions (product registration, sign-up bonus)
349
- - Use `cooldownHours` on repeating actions to prevent gaming (daily check-ins, votes)
350
- - Store display config (`pointName`, `currencySymbol`, tier thresholds) in the scheme's `data` block — keeps the UI configurable without code changes
351
- - Use `lifetimePoints` for tier logic, `balance` for spend eligibility
352
- - Let interactions do the validation — don't award points via `recordTransaction` for events that should go through an earning rule; let the server be the arbiter of point values
1
+ # Loyalty: Points, Members & Earning Rules
2
+
3
+ The `loyalty` namespace lets you build loyalty programmes on top of any collection. Contacts earn points for doing things — registering products, voting, entering competitions, engaging with content — and you track their balance, lifetime points, and full transaction history.
4
+
5
+ Loyalty is designed to be **decoupled from your app logic**. You configure earning rules that say "this interaction earns N points under these conditions", and the platform awards points automatically whenever that interaction event fires. Your app just logs interactions as normal.
6
+
7
+ ---
8
+
9
+ ## Core Concepts
10
+
11
+ | Concept | Description |
12
+ |---------|-------------|
13
+ | **Scheme** | A named loyalty programme within a collection (e.g. "Brand Rewards"). A collection can have multiple schemes. |
14
+ | **Member** | A contact's enrolment in a scheme. Created automatically the first time they earn points. Holds their current `balance` and `lifetimePoints`. |
15
+ | **Transaction** | An append-only ledger entry. Signed integer — positive = earn, negative = spend/deduct. Every point change goes through a transaction. |
16
+ | **Earning Rule** | Links an Interaction definition to a point award. When an interaction event fires that matches the rule's conditions, points are awarded automatically. |
17
+
18
+ ```text
19
+ ┌─────────────────────────────────────────────────────────────────────┐
20
+ │ User registers a product │
21
+ │ ↓ │
22
+ │ interactions.appendEvent(collectionId, { │
23
+ │ interactionId: 'product-registration', │
24
+ │ outcome: 'activated', │
25
+ │ contactId: '...' │
26
+ │ }) │
27
+ │ ↓ │
28
+ │ Platform evaluates earning rules for 'product-registration' │
29
+ │ ↓ │
30
+ │ Rule matches → contact awarded 50 points automatically │
31
+ │ ↓ │
32
+ │ loyalty.publicGetMe(collectionId) → balance: 50 │
33
+ └─────────────────────────────────────────────────────────────────────┘
34
+ ```
35
+
36
+ ---
37
+
38
+ ## Schemes
39
+
40
+ ### Create a Scheme
41
+
42
+ ```typescript
43
+ const scheme = await SL.loyalty.create(collectionId, {
44
+ name: 'Brand Rewards',
45
+ type: 'points',
46
+ data: {
47
+ pointName: 'Star', // Display name for one point
48
+ pointNamePlural: 'Stars',
49
+ currencySymbol: '⭐',
50
+ },
51
+ });
52
+ ```
53
+
54
+ ### List & Get
55
+
56
+ ```typescript
57
+ // Admin: all schemes including inactive/deleted
58
+ const schemes = await SL.loyalty.list(collectionId);
59
+ const scheme = await SL.loyalty.get(collectionId, schemeId);
60
+
61
+ // Public: active schemes only (no admin/owner data blocks)
62
+ const schemes = await SL.loyalty.publicList(collectionId);
63
+ const scheme = await SL.loyalty.publicGet(collectionId, schemeId);
64
+ ```
65
+
66
+ ### Update & Delete
67
+
68
+ ```typescript
69
+ await SL.loyalty.update(collectionId, schemeId, { active: false });
70
+ await SL.loyalty.remove(collectionId, schemeId); // soft-delete
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Getting a User's Loyalty Status
76
+
77
+ ### The one-call pattern
78
+
79
+ `publicGetMe` is the primary entry point for any loyalty UI. It returns all active schemes with the caller's membership embedded — one request, everything you need.
80
+
81
+ ```typescript
82
+ const schemes = await SL.loyalty.publicGetMe(collectionId);
83
+
84
+ // schemes[0] looks like:
85
+ // {
86
+ // id: 'abc-123',
87
+ // name: 'Brand Rewards',
88
+ // type: 'points',
89
+ // data: { pointName: 'Star', ... },
90
+ // member: {
91
+ // balance: 350,
92
+ // lifetimePoints: 820,
93
+ // contactId: '...',
94
+ // createdAt: '...',
95
+ // ...
96
+ // }
97
+ // }
98
+ //
99
+ // member is null if the user hasn't earned any points yet in that scheme
100
+ ```
101
+
102
+ Unauthenticated callers get `member: null` on every scheme — useful for previewing the programme before sign-in.
103
+
104
+ ### Scheme-specific membership
105
+
106
+ ```typescript
107
+ // Current balance + lifetime points
108
+ const member = await SL.loyalty.publicGetMine(collectionId, schemeId);
109
+
110
+ // Transaction history (newest first, paginated)
111
+ const { items } = await SL.loyalty.publicGetMineHistory(collectionId, schemeId, {
112
+ limit: 20,
113
+ offset: 0,
114
+ });
115
+ ```
116
+
117
+ ---
118
+
119
+ ## Earning Rules
120
+
121
+ Earning rules are the control plane that connects interactions to point awards. The server evaluates them automatically — your app never sets a point value directly.
122
+
123
+ Every `interactionId` in a loyalty rule must reference an existing interaction type definition in the same collection.
124
+
125
+ ### Create a Rule
126
+
127
+ ```typescript
128
+ // Award 50 points when a product is registered
129
+ await SL.loyalty.createEarningRule(collectionId, schemeId, {
130
+ interactionId: 'product-registration',
131
+ points: 50,
132
+ conditions: { outcome: 'activated' }, // only fires on this outcome
133
+ maxPerContact: 1, // once per contact lifetime
134
+ });
135
+
136
+ // Award 1 point for any vote, no limit, 24-hour cooldown
137
+ await SL.loyalty.createEarningRule(collectionId, schemeId, {
138
+ interactionId: 'competition-vote',
139
+ points: 1,
140
+ cooldownHours: 24,
141
+ });
142
+
143
+ // Award 10 points for winning — conditions match event fields
144
+ await SL.loyalty.createEarningRule(collectionId, schemeId, {
145
+ interactionId: 'spin-to-win',
146
+ points: 10,
147
+ conditions: { outcome: 'win' },
148
+ });
149
+
150
+ // Award 2 points for entering — same interaction, different rule
151
+ await SL.loyalty.createEarningRule(collectionId, schemeId, {
152
+ interactionId: 'spin-to-win',
153
+ points: 2,
154
+ conditions: { outcome: 'entered' },
155
+ cooldownHours: 24,
156
+ });
157
+ ```
158
+
159
+ Multiple rules can reference the same `interactionId`. All matching rules fire — so an event can earn points from several rules simultaneously if you design them that way.
160
+
161
+ ### Conditions
162
+
163
+ Conditions are key-value pairs matched against the interaction event before a rule fires. An empty `conditions` object means the rule always fires for any event on that interaction.
164
+
165
+ | Condition key | What it matches |
166
+ |---------------|-----------------|
167
+ | `outcome` | `event.outcome` |
168
+ | `scope` | `event.scope` |
169
+ | `status` | `event.status` |
170
+ | `eventType` | `event.eventType` |
171
+ | `metadata.tier` | `event.metadata.tier` |
172
+ | `metadata.region` | `event.metadata.region` |
173
+
174
+ ```typescript
175
+ // Only award points to gold-tier members in UK events
176
+ await SL.loyalty.createEarningRule(collectionId, schemeId, {
177
+ interactionId: 'competition-entry',
178
+ points: 5,
179
+ conditions: {
180
+ outcome: 'entered',
181
+ 'metadata.tier': 'gold',
182
+ 'metadata.region': 'UK',
183
+ },
184
+ });
185
+ ```
186
+
187
+ ### Rate Limiting
188
+
189
+ | Field | Effect |
190
+ |-------|--------|
191
+ | `maxPerContact` | Caps the total lifetime number of times this rule can fire per contact. `null` = unlimited. |
192
+ | `cooldownHours` | Minimum gap between triggers for the same contact. `null` = no cooldown. |
193
+
194
+ ### List, Update & Delete Rules
195
+
196
+ ```typescript
197
+ // List rules (admin)
198
+ const rules = await SL.loyalty.listEarningRules(collectionId, schemeId);
199
+
200
+ // Public: show "how to earn" in UI (active rules only)
201
+ const rules = await SL.loyalty.publicListEarningRules(collectionId, schemeId);
202
+
203
+ // Update
204
+ await SL.loyalty.updateEarningRule(collectionId, schemeId, ruleId, {
205
+ points: 75,
206
+ active: false,
207
+ });
208
+
209
+ // Delete
210
+ await SL.loyalty.removeEarningRule(collectionId, schemeId, ruleId);
211
+ ```
212
+
213
+ ---
214
+
215
+ ## Manual Transactions (Admin)
216
+
217
+ For welcome bonuses, corrections, or admin overrides — points that aren't tied to an interaction event.
218
+
219
+ ```typescript
220
+ // Award a welcome bonus
221
+ await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
222
+ points: 100,
223
+ reason: 'Welcome bonus',
224
+ idempotencyKey: `welcome-${contactId}`, // prevents double-award on retry
225
+ });
226
+
227
+ // Deduct points (spend)
228
+ await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
229
+ points: -50,
230
+ reason: 'Redeemed for discount',
231
+ metadata: { redemptionRef: 'DISC-2026-0042' },
232
+ });
233
+ ```
234
+
235
+ Deducting below zero returns HTTP 422 `INSUFFICIENT_BALANCE`. The transaction is rejected — the balance is never taken negative.
236
+
237
+ ### Idempotency
238
+
239
+ Supply `idempotencyKey` whenever there is any risk of the request being retried (network failures, client retries, webhook replays). The key is scoped per scheme — reusing it on a different scheme is fine.
240
+
241
+ ```typescript
242
+ await SL.loyalty.recordTransaction(collectionId, schemeId, contactId, {
243
+ points: 50,
244
+ reason: 'Referral reward',
245
+ idempotencyKey: `referral-${referrerId}-${refereeId}`,
246
+ });
247
+ // Calling again with the same key returns 409 — no duplicate transaction created
248
+ ```
249
+
250
+ ### Viewing Member History (Admin)
251
+
252
+ ```typescript
253
+ // All members in a scheme
254
+ const { items } = await SL.loyalty.listMembers(collectionId, schemeId, { limit: 50 });
255
+
256
+ // A specific member
257
+ const member = await SL.loyalty.getMember(collectionId, schemeId, contactId);
258
+
259
+ // Full transaction history for a member
260
+ const { items } = await SL.loyalty.getMemberHistory(collectionId, schemeId, contactId, {
261
+ limit: 100,
262
+ offset: 0,
263
+ });
264
+ ```
265
+
266
+ ---
267
+
268
+ ## balance vs lifetimePoints
269
+
270
+ | Field | What it tracks | Can it decrease? |
271
+ |-------|---------------|-----------------|
272
+ | `balance` | Current redeemable points | Yes — deducted on spend |
273
+ | `lifetimePoints` | Total ever earned | Never — only increases |
274
+
275
+ Use `lifetimePoints` for tier calculations (Bronze / Silver / Gold). Use `balance` for showing what a contact can currently spend.
276
+
277
+ ---
278
+
279
+ ## Integration with Interactions
280
+
281
+ Loyalty earning is a side-effect of the interaction system. Your app calls `interactions.appendEvent` exactly as it would without loyalty — the platform handles the rest.
282
+
283
+ ```typescript
284
+ // Your app logs an interaction event as normal
285
+ await SL.interactions.appendEvent(collectionId, {
286
+ appId: 'my-app',
287
+ interactionId: 'product-registration',
288
+ outcome: 'activated',
289
+ contactId: contact.contactId,
290
+ productId: product.id,
291
+ metadata: { serialNumber: 'SN-12345' },
292
+ });
293
+
294
+ // Behind the scenes (no app code needed):
295
+ // 1. Event is logged to BigQuery
296
+ // 2. Platform checks earning rules for 'product-registration'
297
+ // 3. Matching rules fire → contact's balance updated atomically
298
+ // 4. Transaction appended to ledger with ruleId in metadata
299
+ ```
300
+
301
+ A loyalty failure never causes the interaction event to fail — errors are caught and logged server-side so your app always gets a clean response.
302
+
303
+ ---
304
+
305
+ ## External loyalty platforms
306
+
307
+ The schemes above are SmartLinks' own points. When a brand runs its programme on an external loyalty or
308
+ engagement platform, the platform stays the record of truth and SmartLinks connects to it through a
309
+ **connector app** and the integration engine — no member base is mirrored here:
310
+
311
+ | Flow | How |
312
+ |---|---|
313
+ | **Earn** — what happens on a pack or in a Hub awards points there | an outbound flow with `sourceEntity: 'interaction' \| 'event'`, an `eventMapping` onto the provider's registered events, signed delivery, retries — [integrations.md](integrations.md#event-sourced-flows-and-the-envelope) |
314
+ | **Profile** — member id, tier and points on the contact | the connector's webhook function calls `ctx.sl.members.apply(...)`; the contact gets `customFields.loyalty` and flat `loyaltyTier / loyaltyPoints / loyaltyMemberId`, usable in segments and comms targeting — [connectors.md](connectors.md#loyalty-and-crm-connectors) |
315
+ | **Gate / display** — "Gold members only", live balance | the entitlement check, answered on demand from a signed claim, the connector's cached `lookup`, or the contact's fields — [entitlements.md](entitlements.md) |
316
+
317
+ A collection runs one loyalty source: the native schemes here, or an external provider through a
318
+ connector.
319
+
320
+ ---
321
+
322
+ ## TypeScript Types
323
+
324
+ ```typescript
325
+ import type {
326
+ LoyaltyScheme, // Scheme definition
327
+ LoyaltyMember, // Contact's enrolment + balance
328
+ LoyaltyTransaction, // Single ledger entry
329
+ LoyaltyEarningRule, // Interaction → points mapping
330
+ LoyaltySchemeWithMembership, // publicGetMe() response shape
331
+ LoyaltyTransactionResult, // recordTransaction() response
332
+ LoyaltyPaginatedResult, // { items, limit, offset }
333
+ LoyaltyPaginationParams, // { limit?, offset? }
334
+ CreateLoyaltySchemeBody,
335
+ UpdateLoyaltySchemeBody,
336
+ CreateLoyaltyEarningRuleBody,
337
+ UpdateLoyaltyEarningRuleBody,
338
+ RecordLoyaltyTransactionBody,
339
+ } from '@proveanything/smartlinks';
340
+ ```
341
+
342
+ ---
343
+
344
+ ## Best Practices
345
+
346
+ - Use `publicGetMe` as your single loyalty widget data source — one call, all schemes, membership embedded
347
+ - Always supply `idempotencyKey` on manual transactions that could be retried
348
+ - Use `maxPerContact: 1` on one-time actions (product registration, sign-up bonus)
349
+ - Use `cooldownHours` on repeating actions to prevent gaming (daily check-ins, votes)
350
+ - Store display config (`pointName`, `currencySymbol`, tier thresholds) in the scheme's `data` block — keeps the UI configurable without code changes
351
+ - Use `lifetimePoints` for tier logic, `balance` for spend eligibility
352
+ - Let interactions do the validation — don't award points via `recordTransaction` for events that should go through an earning rule; let the server be the arbiter of point values