@voltro/plugin-economy 0.0.0-stage → 0.88.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 (177) hide show
  1. package/CHANGELOG.md +24492 -0
  2. package/LICENSE +61 -0
  3. package/README.md +2719 -2
  4. package/SECURITY.md +56 -0
  5. package/THIRD-PARTY-NOTICES.md +9841 -0
  6. package/dist/amount.js +20 -0
  7. package/dist/appleIap.server.js +262 -0
  8. package/dist/appleIapNotifications.server.js +162 -0
  9. package/dist/appleIapTrust.server.js +30 -0
  10. package/dist/bundleValue.server.js +112 -0
  11. package/dist/canonicalDataJson.js +10 -0
  12. package/dist/capture.js +53 -0
  13. package/dist/codePort.fixture.js +123 -0
  14. package/dist/codeStore.server.js +439 -0
  15. package/dist/codeTables.entity.js +43 -0
  16. package/dist/codes.d.ts +150 -0
  17. package/dist/codes.js +82 -0
  18. package/dist/components.d.ts +397 -0
  19. package/dist/components.js +283 -0
  20. package/dist/consistency.server.js +115 -0
  21. package/dist/containerStore.server.js +687 -0
  22. package/dist/containerStore.testFixtures.js +75 -0
  23. package/dist/containerTables.entity.js +45 -0
  24. package/dist/containers.d.ts +311 -0
  25. package/dist/containers.fixture.js +128 -0
  26. package/dist/containers.js +214 -0
  27. package/dist/containers.server.js +39 -0
  28. package/dist/containersPort.fixture.js +74 -0
  29. package/dist/currency.js +32 -0
  30. package/dist/declarationFixtures.js +61 -0
  31. package/dist/economy-app/events/economy.refundReversed.event.ts +1 -0
  32. package/dist/economy-app/events/economy.refunded.event.ts +1 -0
  33. package/dist/economyPort.fixture.js +124 -0
  34. package/dist/errors.d.ts +14 -0
  35. package/dist/errors.js +21 -0
  36. package/dist/events.d.ts +46 -0
  37. package/dist/events.js +1 -0
  38. package/dist/googleIap.server.js +391 -0
  39. package/dist/googleIapNotifications.server.js +130 -0
  40. package/dist/googleIapSubscription.server.js +183 -0
  41. package/dist/iap.d.ts +309 -0
  42. package/dist/iap.js +303 -0
  43. package/dist/iap.testFixtures.js +144 -0
  44. package/dist/iapAccountTables.entity.js +39 -0
  45. package/dist/iapAccounts.server.js +200 -0
  46. package/dist/iapBinding.server.js +523 -0
  47. package/dist/iapCheckout.server.js +97 -0
  48. package/dist/iapCompletion.server.js +55 -0
  49. package/dist/iapCurrentState.server.js +107 -0
  50. package/dist/iapCurrentState.testFixtures.js +22 -0
  51. package/dist/iapCurrentStatePort.fixture.js +63 -0
  52. package/dist/iapEntitlements.d.ts +79 -0
  53. package/dist/iapEntitlements.js +57 -0
  54. package/dist/iapEntitlements.server.js +48 -0
  55. package/dist/iapEntitlementsBinding.server.js +105 -0
  56. package/dist/iapEntitlementsPort.fixture.js +80 -0
  57. package/dist/iapInstalledEntitlements.testFixtures.js +75 -0
  58. package/dist/iapInstalledNotifications.testFixtures.js +93 -0
  59. package/dist/iapInventoryRefunds.server.js +261 -0
  60. package/dist/iapNotificationCustodyPort.fixture.js +67 -0
  61. package/dist/iapNotificationPort.fixture.js +73 -0
  62. package/dist/iapNotificationProcessor.server.js +134 -0
  63. package/dist/iapNotificationProcessor.testFixtures.js +63 -0
  64. package/dist/iapNotificationProcessorPort.fixture.js +55 -0
  65. package/dist/iapNotificationSchedule.server.js +69 -0
  66. package/dist/iapNotificationStore.server.js +352 -0
  67. package/dist/iapNotificationStore.testFixtures.js +31 -0
  68. package/dist/iapNotificationTables.entity.js +48 -0
  69. package/dist/iapNotificationTarget.server.js +36 -0
  70. package/dist/iapNotificationTarget.testFixtures.js +29 -0
  71. package/dist/iapNotifications.d.ts +644 -0
  72. package/dist/iapNotifications.js +6 -0
  73. package/dist/iapNotifications.server.js +95 -0
  74. package/dist/iapNotificationsBinding.server.js +232 -0
  75. package/dist/iapNotificationsSystemPort.fixture.js +50 -0
  76. package/dist/iapPlugin.testFixtures.js +59 -0
  77. package/dist/iapPort.fixture.js +74 -0
  78. package/dist/iapProviderCapture.server.js +17 -0
  79. package/dist/iapRecovery.d.ts +146 -0
  80. package/dist/iapRecovery.js +89 -0
  81. package/dist/iapRefundEventDelivery.server.js +82 -0
  82. package/dist/iapRefundEvents.js +44 -0
  83. package/dist/iapRefundEventsPort.fixture.js +59 -0
  84. package/dist/iapRefundPort.fixture.js +54 -0
  85. package/dist/iapRefundTables.entity.js +55 -0
  86. package/dist/iapRefunds.d.ts +755 -0
  87. package/dist/iapRefunds.js +6 -0
  88. package/dist/iapRefunds.server.js +553 -0
  89. package/dist/iapRefunds.testFixtures.js +64 -0
  90. package/dist/iapSpendAdmission.server.js +98 -0
  91. package/dist/iapStore.server.js +740 -0
  92. package/dist/iapStore.testFixtures.js +127 -0
  93. package/dist/iapTables.entity.js +80 -0
  94. package/dist/iapVerification.server.js +120 -0
  95. package/dist/index.d.ts +2984 -0
  96. package/dist/index.js +15 -0
  97. package/dist/intentionRecovery.js +133 -0
  98. package/dist/ledger.js +77 -0
  99. package/dist/loyalty.d.ts +274 -0
  100. package/dist/loyalty.fixture.js +92 -0
  101. package/dist/loyalty.js +311 -0
  102. package/dist/loyaltyBinding.server.js +203 -0
  103. package/dist/loyaltyPort.fixture.js +86 -0
  104. package/dist/loyaltyShopSource.server.js +90 -0
  105. package/dist/loyaltyStore.server.js +552 -0
  106. package/dist/loyaltyStore.testFixtures.js +82 -0
  107. package/dist/loyaltyTables.entity.js +49 -0
  108. package/dist/offerMerchandising.fixture.js +114 -0
  109. package/dist/offerMerchandising.js +282 -0
  110. package/dist/offerPolicies.d.ts +441 -0
  111. package/dist/offerPolicies.fixture.js +53 -0
  112. package/dist/offerPolicies.js +267 -0
  113. package/dist/piggyBanks.d.ts +272 -0
  114. package/dist/piggyBanks.fixture.js +70 -0
  115. package/dist/piggyBanks.js +200 -0
  116. package/dist/piggyBinding.server.js +204 -0
  117. package/dist/piggyPort.fixture.js +72 -0
  118. package/dist/piggyStore.server.js +610 -0
  119. package/dist/piggyStore.testFixtures.js +97 -0
  120. package/dist/piggyTables.entity.js +40 -0
  121. package/dist/plugin.js +1047 -0
  122. package/dist/port.js +12 -0
  123. package/dist/price.d.ts +99 -0
  124. package/dist/price.js +143 -0
  125. package/dist/purchaseRecovery.js +55 -0
  126. package/dist/reports.server.js +114 -0
  127. package/dist/rpc.d.ts +3201 -0
  128. package/dist/rpc.js +1200 -0
  129. package/dist/sanctionsTradeAuthority.server.js +79 -0
  130. package/dist/server.d.ts +3856 -0
  131. package/dist/server.js +43 -0
  132. package/dist/shop.d.ts +279 -0
  133. package/dist/shop.js +195 -0
  134. package/dist/shop.testFixtures.js +113 -0
  135. package/dist/shopPort.fixture.js +71 -0
  136. package/dist/shopPresentation.js +67 -0
  137. package/dist/shopStore.server.js +623 -0
  138. package/dist/shopTables.entity.js +62 -0
  139. package/dist/shopUiCopy.js +56 -0
  140. package/dist/spendLimits.d.ts +140 -0
  141. package/dist/spendLimits.fixture.js +52 -0
  142. package/dist/spendLimits.js +154 -0
  143. package/dist/spendLimitsPort.fixture.js +119 -0
  144. package/dist/subscriptionBinding.server.js +210 -0
  145. package/dist/subscriptionStore.server.js +642 -0
  146. package/dist/subscriptionStore.testFixtures.js +71 -0
  147. package/dist/subscriptionTables.entity.js +36 -0
  148. package/dist/subscriptions.d.ts +394 -0
  149. package/dist/subscriptions.fixture.js +96 -0
  150. package/dist/subscriptions.js +212 -0
  151. package/dist/subscriptionsPort.fixture.js +75 -0
  152. package/dist/systemFixtures.js +88 -0
  153. package/dist/tables.entity.js +82 -0
  154. package/dist/testing.d.ts +4615 -0
  155. package/dist/testing.js +29 -0
  156. package/dist/tradeAuthority.server.js +171 -0
  157. package/dist/tradeBinding.server.js +200 -0
  158. package/dist/tradeComponents.js +341 -0
  159. package/dist/tradeEscrow.server.js +231 -0
  160. package/dist/tradeEscrow.testFixtures.js +132 -0
  161. package/dist/tradeExpiry.server.js +42 -0
  162. package/dist/tradeRecovery.js +47 -0
  163. package/dist/tradeStore.server.js +749 -0
  164. package/dist/tradeStore.testFixtures.js +72 -0
  165. package/dist/tradeTables.entity.js +65 -0
  166. package/dist/tradeUiCopy.js +78 -0
  167. package/dist/trades.d.ts +246 -0
  168. package/dist/trades.fixture.js +102 -0
  169. package/dist/trades.js +288 -0
  170. package/dist/tradesPort.fixture.js +93 -0
  171. package/dist/walletEscrow.js +105 -0
  172. package/dist/walletEscrow.server.js +375 -0
  173. package/dist/walletKeys.server.js +4 -0
  174. package/dist/walletStore.js +570 -0
  175. package/dist/web.d.ts +2257 -0
  176. package/dist/web.js +8 -0
  177. package/package.json +161 -4
@@ -0,0 +1,552 @@
1
+ import { EconomyError as e, economyError as t } from "./errors.js";
2
+ import { captureBoundMethods as n, dataList as r, dataObject as i, identifier as a } from "./capture.js";
3
+ import { economyAmount as o, nonNegativeAmount as s } from "./amount.js";
4
+ import { captureCurrencies as c } from "./currency.js";
5
+ import { shopInteger as l } from "./shop.js";
6
+ import { defaultLoyaltyPerks as u, defaultLoyaltyTier as d, defineLoyalty as f, loyaltyCreditIntent as p, loyaltyMineIntent as m, loyaltyRebuildIntent as h, loyaltyReceiptIntent as g, loyaltyReverseIntent as _, projectLoyaltyPoints as v, resolveLoyaltyPerks as y, resolveLoyaltyTier as b } from "./loyalty.js";
7
+ import { loyaltyDefinitionsTable as x, loyaltyEntriesTable as S, loyaltySeasonsTable as C, loyaltySubjectsTable as w, loyaltyTenantsTable as T } from "./loyaltyTables.entity.js";
8
+ import { Effect as E, Result as D } from "effect";
9
+ import { createHash as O } from "node:crypto";
10
+ import { and as k, eq as A, queryFor as j } from "@voltro/database";
11
+ // src/loyaltyStore.server.ts
12
+ var M = (e) => Array.isArray(e) ? "[" + e.map(M).join(",") + "]" : typeof e == "object" && e ? "{" + Object.keys(e).sort().map((t) => JSON.stringify(t) + ":" + M(e[t])).join(",") + "}" : JSON.stringify(e), N = (e) => O("sha256").update(M(e)).digest("hex"), P = (e, ...t) => e + N(t).slice(0, 56), F = (n) => n instanceof e ? n : t("unavailable"), I = (e) => E.tryPromise({
13
+ try: e,
14
+ catch: F
15
+ }), L = (n) => {
16
+ try {
17
+ return n();
18
+ } catch (n) {
19
+ return E.fail(n instanceof e ? n : t("invalid_input"));
20
+ }
21
+ }, R = async (e) => {
22
+ let t = await E.runPromise(E.result(e));
23
+ if (D.isFailure(t)) throw t.failure;
24
+ return t.success;
25
+ }, z = (e) => l(e, 0, 864e13), B = (e) => z(e instanceof Date ? e.getTime() : typeof e == "string" ? Date.parse(e) : NaN), V = (e) => {
26
+ if (typeof e != "string" || s(e).toString() !== e) throw t("invalid_record");
27
+ return e;
28
+ }, H = (e) => {
29
+ let n = i(e, [
30
+ "tenantId",
31
+ "ownerId",
32
+ "authorityId",
33
+ "purchaseId",
34
+ "kind",
35
+ "currency",
36
+ "amount",
37
+ "settledAt",
38
+ "refundedAmount"
39
+ ], "invalid_record");
40
+ if (n.kind !== "purchase.real" && n.kind !== "purchase.virtual" || n.refundedAmount !== "0") throw t("invalid_record");
41
+ return Object.freeze({
42
+ tenantId: a(n.tenantId),
43
+ ownerId: a(n.ownerId),
44
+ authorityId: a(n.authorityId),
45
+ purchaseId: a(n.purchaseId),
46
+ kind: n.kind,
47
+ currency: a(n.currency),
48
+ amount: V(n.amount),
49
+ settledAt: z(n.settledAt),
50
+ refundedAmount: "0"
51
+ });
52
+ }, U = (e) => {
53
+ let t = i(e, [
54
+ "tenantId",
55
+ "ownerId",
56
+ "authorityId",
57
+ "purchaseId",
58
+ "refundId",
59
+ "totalRefunded",
60
+ "refundedAt"
61
+ ], "invalid_record");
62
+ return Object.freeze({
63
+ tenantId: a(t.tenantId),
64
+ ownerId: a(t.ownerId),
65
+ authorityId: a(t.authorityId),
66
+ purchaseId: a(t.purchaseId),
67
+ refundId: a(t.refundId),
68
+ totalRefunded: V(t.totalRefunded),
69
+ refundedAt: z(t.refundedAt)
70
+ });
71
+ }, W = (e, n) => {
72
+ let r = i(e, [
73
+ "id",
74
+ "startsAt",
75
+ "endsAt"
76
+ ], "invalid_record"), o = z(r.startsAt), s = z(r.endsAt);
77
+ if (o >= s || n !== void 0 && (n < o || n >= s)) throw t("invalid_record");
78
+ return Object.freeze({
79
+ id: a(r.id),
80
+ startsAt: o,
81
+ endsAt: s
82
+ });
83
+ }, G = (e) => {
84
+ let o = i(e, [
85
+ "loyalty",
86
+ "currencies",
87
+ "realMoney",
88
+ "receiptSource",
89
+ "seasonSource",
90
+ "version",
91
+ "tier",
92
+ "perks",
93
+ "allowedServices",
94
+ "maxHistoryRows",
95
+ "maxDefinitionRows",
96
+ "maxSeasonRows",
97
+ "now"
98
+ ]), s = c(o.currencies), p = o.realMoney ?? !1;
99
+ if (typeof p != "boolean") throw t("invalid_input");
100
+ let m = Object.freeze(r(o.loyalty, 32).map((e) => f(e, s, p)));
101
+ if (!m.length || new Set(m.map((e) => e.id)).size !== m.length) throw t("invalid_input");
102
+ let h = n(o.receiptSource, ["purchase", "refund"]), g = o.seasonSource === void 0 ? void 0 : n(o.seasonSource, ["read"]);
103
+ if (m.some((e) => e.decay === "seasonal") && !g) throw t("invalid_input");
104
+ let _ = a(o.version), v = o.tier ?? d, y = o.perks ?? u, b = o.now ?? Date.now;
105
+ if (_ === "default.v1" || [
106
+ v,
107
+ y,
108
+ b
109
+ ].some((e) => typeof e != "function")) throw t("invalid_input");
110
+ let x = Object.freeze(r(o.allowedServices ?? [], 256).map((e) => a(e)));
111
+ if (new Set(x).size !== x.length) throw t("invalid_input");
112
+ return Object.freeze({
113
+ loyalty: m,
114
+ currencies: s,
115
+ realMoney: p,
116
+ receiptSource: h,
117
+ seasonSource: g,
118
+ version: _,
119
+ tier: v,
120
+ perks: y,
121
+ now: b,
122
+ allowedServices: x,
123
+ maxHistoryRows: l(o.maxHistoryRows ?? 1e4, 1, 1e5),
124
+ maxDefinitionRows: l(o.maxDefinitionRows ?? 1024, 1, 1e5),
125
+ maxSeasonRows: l(o.maxSeasonRows ?? 1024, 1, 1e5)
126
+ });
127
+ }, K = (e, n) => {
128
+ let r = G(n), u = new Set(r.allowedServices), d = () => z(r.now()), E = (e, t) => P("els_", e, t), D = (e, t, n) => P("ele_", e, t, n), O = (e, t, n, r) => N([
129
+ e,
130
+ t,
131
+ n,
132
+ r
133
+ ]), M = (e, t, n, r) => N([
134
+ e,
135
+ t,
136
+ n,
137
+ r
138
+ ]), F = (e) => {
139
+ let n = structuredClone(e);
140
+ if (n.type !== "user") throw t("forbidden");
141
+ return Object.freeze({
142
+ tenantId: a(n.tenantId),
143
+ ownerId: a(n.id)
144
+ });
145
+ }, K = (e) => {
146
+ let n = structuredClone(e);
147
+ if (n.type !== "system" && (n.type !== "service" || !u.has(n.service))) throw t("forbidden");
148
+ }, q = async (e, n, r, i = !1) => {
149
+ let a = (await e.query(j(w).where(A("id", E(n, r))).limit(1).descriptor))[0];
150
+ if (a) {
151
+ if (a.tenantId !== n || a.admission !== 0 || typeof a.erased != "boolean" || a.ownerId !== (a.erased ? null : r)) throw t("invalid_record");
152
+ if (l(a.entriesCount, 0, 1e5), a.erased && !i) throw t("erased");
153
+ return a;
154
+ }
155
+ }, J = async (t, n) => {
156
+ await e.insertIgnore(T.tableName, {
157
+ id: P("elt_", t),
158
+ tenantId: t,
159
+ admission: 0
160
+ }, { conflictColumns: ["id"] }), await e.insertIgnore(w.tableName, {
161
+ id: E(t, n),
162
+ tenantId: t,
163
+ ownerId: n,
164
+ erased: !1,
165
+ admission: 0,
166
+ entriesCount: 0
167
+ }, { conflictColumns: ["id"] });
168
+ }, Y = async (e, n, r, i = !1) => {
169
+ let a = P("elt_", n);
170
+ if (await e.updateMany(T.tableName, { admission: 0 }, { where: A("id", a) }) !== 1) throw t("unavailable");
171
+ let o = (await e.query(j(T).where(A("id", a)).limit(1).descriptor))[0];
172
+ if (!o || o.tenantId !== n || o.admission !== 0) throw t("invalid_record");
173
+ if (await e.updateMany(w.tableName, { admission: 0 }, { where: A("id", E(n, r)) }) !== 1 || !await q(e, n, r, i)) throw t("unavailable");
174
+ }, X = async (e, n, i) => {
175
+ let o = await e.query(j(C).where(k(A("tenantId", n), A("loyaltyId", i))).limit(r.maxSeasonRows + 1).descriptor);
176
+ if (o.length > r.maxSeasonRows) throw t("limit_exceeded");
177
+ let s = o.map((e) => {
178
+ let r = B(e.startsAt), o = B(e.endsAt), s = a(e.seasonId);
179
+ if (e.id !== P("elp_", n, i, s) || r >= o) throw t("invalid_record");
180
+ return Object.freeze({
181
+ id: s,
182
+ startsAt: r,
183
+ endsAt: o
184
+ });
185
+ }).sort((e, t) => e.startsAt - t.startsAt);
186
+ if (s.some((e, t) => t > 0 && e.startsAt < s[t - 1].endsAt)) throw t("invalid_record");
187
+ return s;
188
+ }, ee = async (e, n, i, a, o) => {
189
+ let s = await X(e, n, i), c = s.find((e) => e.id === a.id);
190
+ if (c) {
191
+ if (N(c) !== N(a)) throw t("conflict");
192
+ } else {
193
+ if (s.some((e) => a.startsAt < e.endsAt && a.endsAt > e.startsAt)) throw t("conflict");
194
+ if (o) {
195
+ if (s.length >= r.maxSeasonRows) throw t("limit_exceeded");
196
+ await e.insert(C.tableName, {
197
+ id: P("elp_", n, i, a.id),
198
+ tenantId: n,
199
+ loyaltyId: i,
200
+ seasonId: a.id,
201
+ startsAt: new Date(a.startsAt),
202
+ endsAt: new Date(a.endsAt)
203
+ });
204
+ }
205
+ }
206
+ }, te = (e, t) => ({
207
+ id: P("eld_", e, t.loyalty.id, t.loyalty.version, t.rulesVersion),
208
+ tenantId: e,
209
+ loyaltyId: t.loyalty.id,
210
+ definition: t.loyalty,
211
+ currencies: t.currencies,
212
+ realMoney: t.realMoney,
213
+ rulesVersion: t.rulesVersion
214
+ }), ne = async (e, n, i) => {
215
+ let a = te(n, i), o = await e.query(j(x).where(k(A("tenantId", n), A("loyaltyId", i.loyalty.id))).limit(r.maxDefinitionRows + 1).descriptor);
216
+ if (o.length > r.maxDefinitionRows) throw t("limit_exceeded");
217
+ for (let e of o) if (f(e.definition, e.currencies, e.realMoney).decay !== i.loyalty.decay) throw t("conflict");
218
+ let s = o.find((e) => e.id === a.id);
219
+ if (s) {
220
+ if (N(s) !== N(a)) throw t("conflict");
221
+ } else {
222
+ if (o.length >= r.maxDefinitionRows) throw t("limit_exceeded");
223
+ await e.insert(x.tableName, a);
224
+ }
225
+ }, re = async (e, n, r, s) => {
226
+ if (s.tenantId !== n || s.ownerId !== r || s.ownerKey !== E(n, r) || s.state !== "fulfilled") throw t("invalid_record");
227
+ let u = i(s.body, [
228
+ "kind",
229
+ "request",
230
+ "loyalty",
231
+ "currencies",
232
+ "realMoney",
233
+ "rulesVersion",
234
+ "evidence",
235
+ "season",
236
+ "entry",
237
+ "points"
238
+ ], "invalid_record");
239
+ if (u.kind !== "credit" && u.kind !== "reverse" || typeof u.realMoney != "boolean") throw t("invalid_record");
240
+ let d = u.kind, m = d === "credit" ? p(u.request) : _(u.request), h = c(u.currencies), g = f(u.loyalty, h, u.realMoney), v = a(u.rulesVersion), y = i(u.entry, d === "credit" ? [
241
+ "id",
242
+ "sequence",
243
+ "kind",
244
+ "at",
245
+ "sourceId",
246
+ "purchaseId",
247
+ "seasonId",
248
+ "purchaseAmount",
249
+ "numerator",
250
+ "denominator",
251
+ "delta"
252
+ ] : [
253
+ "id",
254
+ "sequence",
255
+ "kind",
256
+ "at",
257
+ "originalId",
258
+ "refundId",
259
+ "seasonId",
260
+ "totalRefunded",
261
+ "delta"
262
+ ], "invalid_record");
263
+ if (typeof y.delta != "string" || o(y.delta).toString() !== y.delta) throw t("invalid_record");
264
+ let b = Object.freeze({
265
+ ...y,
266
+ sequence: l(y.sequence, 1, 1e5),
267
+ at: z(y.at)
268
+ }), S = d === "credit" ? H(u.evidence) : U(u.evidence), C = d === "credit" ? S.settledAt : S.refundedAt, w = u.season === null ? null : W(u.season, d === "credit" ? C : void 0), T = V(u.points), k = z(b.at);
269
+ if (m.tenantId !== n || m.ownerId !== r || m.loyaltyId !== g.id || s.loyaltyId !== g.id || S.tenantId !== n || S.ownerId !== r || s.id !== D(n, r, m.requestId) || s.digest !== N([d, m]) || b.id !== s.id || b.kind !== d || B(s.createdAt) !== k || C > k || b.seasonId !== (w?.id ?? null) || g.decay === "none" && w !== null || g.decay === "seasonal" && w === null || v === "default.v1" || s.purchaseKey !== O(n, g.id, S.authorityId, S.purchaseId) || s.refundKey !== (d === "credit" ? null : M(n, g.id, S.authorityId, S.refundId))) throw t("invalid_record");
270
+ if (d === "credit") {
271
+ let e = S, n = m, r = b, i = g.pointsFrom.find((e) => e.id === n.sourceId);
272
+ if (!i || i.kind !== e.kind || i.currency !== e.currency || n.purchaseId !== e.purchaseId || r.sourceId !== i.id || r.purchaseId !== e.purchaseId || r.purchaseAmount !== e.amount || r.numerator !== i.numerator || r.denominator !== i.denominator) throw t("invalid_record");
273
+ } else {
274
+ let e = S, n = m, r = b;
275
+ if (r.originalId !== n.originalId || r.refundId !== n.refundId || e.refundId !== n.refundId || r.totalRefunded !== e.totalRefunded) throw t("invalid_record");
276
+ }
277
+ let P = Object.freeze({
278
+ kind: d,
279
+ request: m,
280
+ loyalty: g,
281
+ currencies: h,
282
+ realMoney: u.realMoney,
283
+ rulesVersion: v,
284
+ evidence: S,
285
+ season: w,
286
+ entry: b,
287
+ points: T
288
+ }), F = te(n, P), I = (await e.query(j(x).where(A("id", F.id)).limit(1).descriptor))[0];
289
+ if (!I || N(I) !== N(F)) throw t("invalid_record");
290
+ if (w) {
291
+ let r = (await X(e, n, g.id)).find((e) => e.id === w.id);
292
+ if (!r || N(r) !== N(w)) throw t("invalid_record");
293
+ }
294
+ return P;
295
+ }, Z = async (e, n, i) => {
296
+ let a = await q(e, n, i), o = await e.query(j(S).where(k(A("tenantId", n), A("ownerKey", E(n, i)))).limit(r.maxHistoryRows + 1).descriptor);
297
+ if (o.length > r.maxHistoryRows) throw t("limit_exceeded");
298
+ if (o.length !== (a?.entriesCount ?? 0)) throw t("invalid_record");
299
+ o.sort((e, t) => Number(e.sequence) - Number(t.sequence));
300
+ let c = [], l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set();
301
+ for (let [r, a] of o.entries()) {
302
+ if (a.sequence !== r + 1) throw t("invalid_record");
303
+ let o = await re(e, n, i, a), p = l.get(o.loyalty.id) ?? [];
304
+ if (o.entry.at < (c.at(-1)?.entry.at ?? 0) || p.length && p[0].loyalty.decay !== o.loyalty.decay) throw t("invalid_record");
305
+ if (o.kind === "credit") {
306
+ if (d.has(String(a.purchaseKey))) throw t("invalid_record");
307
+ d.add(String(a.purchaseKey));
308
+ } else {
309
+ let e = o.entry, n = p.find((t) => t.entry.id === e.originalId);
310
+ if (!n || n.kind !== "credit" || N(n.loyalty) !== N(o.loyalty) || n.rulesVersion !== o.rulesVersion || N(n.season) !== N(o.season) || n.evidence.authorityId !== o.evidence.authorityId || n.evidence.purchaseId !== o.evidence.purchaseId || o.evidence.refundedAt < n.evidence.settledAt || f.has(String(a.refundKey))) throw t("invalid_record");
311
+ f.add(String(a.refundKey));
312
+ }
313
+ let m = JSON.stringify([o.loyalty.id, o.entry.seasonId]), h = s((u.get(m) ?? 0n) + BigInt(o.entry.delta));
314
+ if (o.points !== h.toString()) throw t("invalid_record");
315
+ u.set(m, h), p.push(o), l.set(o.loyalty.id, p), c.push(o);
316
+ }
317
+ let p = /* @__PURE__ */ new Map();
318
+ for (let [e, t] of l) p.set(e, v(t.map((e) => e.entry), t[0].loyalty.decay));
319
+ if ((await q(e, n, i))?.entriesCount !== a?.entriesCount) throw t("conflict");
320
+ return Object.freeze({
321
+ accepted: c,
322
+ programs: l,
323
+ projections: p,
324
+ count: o.length
325
+ });
326
+ }, Q = (e) => Object.freeze({
327
+ operationId: e.entry.id,
328
+ requestId: e.request.requestId,
329
+ loyaltyId: e.loyalty.id,
330
+ entry: e.entry,
331
+ points: e.points
332
+ }), $ = async (e, n, r, i, a, o) => {
333
+ let s = (await Z(e, n, r)).accepted.find((e) => e.entry.id === i);
334
+ if (s && a && (s.kind !== a || N(s.request) !== N(o))) throw t("conflict");
335
+ return s ? Q(s) : void 0;
336
+ }, ie = (n, i) => I(async () => {
337
+ let { tenantId: a, ownerId: o, loyaltyId: c } = i, l = D(a, o, i.requestId), u = await e.transactional((e) => $(e, a, o, l, n, i));
338
+ if (u) return u;
339
+ await J(a, o);
340
+ let f = await e.transactional((e) => Z(e, a, o));
341
+ if (f.count >= r.maxHistoryRows) throw t("limit_exceeded");
342
+ let p = d();
343
+ if (p < (f.accepted.at(-1)?.entry.at ?? 0)) throw t("invalid_record");
344
+ let m = f.programs.get(c) ?? [], h = f.projections.get(c), g, _, y, b, x, C, T;
345
+ if (n === "credit") {
346
+ let e = i, n = r.loyalty.find((e) => e.id === c);
347
+ if (!n) throw t("not_found");
348
+ g = n, _ = r.currencies, y = r.realMoney, b = r.version;
349
+ let u = g.pointsFrom.find((t) => t.id === e.sourceId);
350
+ if (!u) throw t("not_found");
351
+ let d = H(await R(r.receiptSource.purchase(Object.freeze({
352
+ tenantId: a,
353
+ ownerId: o,
354
+ source: u,
355
+ purchaseId: e.purchaseId
356
+ }))));
357
+ if (d.tenantId !== a || d.ownerId !== o || d.purchaseId !== e.purchaseId || d.kind !== u.kind || d.currency !== u.currency || d.settledAt > p) throw t("invalid_record");
358
+ if (x = d, C = g.decay === "seasonal" ? W(await R(r.seasonSource.read(Object.freeze({
359
+ tenantId: a,
360
+ loyaltyId: c,
361
+ at: d.settledAt
362
+ }))), d.settledAt) : null, m.some((e) => e.entry.kind === "credit" && e.entry.sourceId === u.id && e.entry.purchaseId === d.purchaseId)) throw t("conflict");
363
+ T = Object.freeze({
364
+ id: l,
365
+ sequence: m.length + 1,
366
+ kind: "credit",
367
+ at: p,
368
+ sourceId: u.id,
369
+ purchaseId: d.purchaseId,
370
+ seasonId: C?.id ?? null,
371
+ purchaseAmount: d.amount,
372
+ numerator: u.numerator,
373
+ denominator: u.denominator,
374
+ delta: s(BigInt(d.amount) * BigInt(u.numerator) / BigInt(u.denominator)).toString()
375
+ });
376
+ } else {
377
+ let e = i, n = m.find((t) => t.entry.id === e.originalId);
378
+ if (!n || n.kind !== "credit") throw t("not_found");
379
+ g = n.loyalty, _ = n.currencies, y = n.realMoney, b = n.rulesVersion, C = n.season;
380
+ let s = H(n.evidence), c = U(await R(r.receiptSource.refund(Object.freeze({
381
+ tenantId: a,
382
+ ownerId: o,
383
+ purchase: s,
384
+ refundId: e.refundId
385
+ }))));
386
+ if (c.tenantId !== a || c.ownerId !== o || c.authorityId !== s.authorityId || c.purchaseId !== s.purchaseId || c.refundId !== e.refundId || c.refundedAt < s.settledAt || c.refundedAt > p) throw t("invalid_record");
387
+ let u = n.entry, d = h.credits.find((t) => t.id === e.originalId);
388
+ if (BigInt(c.totalRefunded) <= BigInt(d.refundedAmount) || BigInt(c.totalRefunded) > BigInt(s.amount)) throw t("conflict");
389
+ let f = (BigInt(s.amount) - BigInt(c.totalRefunded)) * BigInt(u.numerator) / BigInt(u.denominator);
390
+ x = c, T = Object.freeze({
391
+ id: l,
392
+ sequence: m.length + 1,
393
+ kind: "reverse",
394
+ at: p,
395
+ originalId: u.id,
396
+ refundId: c.refundId,
397
+ seasonId: u.seasonId,
398
+ totalRefunded: c.totalRefunded,
399
+ delta: (f - BigInt(d.remainingPoints)).toString()
400
+ });
401
+ }
402
+ let P = v([...m.map((e) => e.entry), T], g.decay).balances.find((e) => e.seasonId === T.seasonId).points, F = Object.freeze({
403
+ kind: n,
404
+ request: i,
405
+ loyalty: g,
406
+ currencies: _,
407
+ realMoney: y,
408
+ rulesVersion: b,
409
+ evidence: x,
410
+ season: C,
411
+ entry: T,
412
+ points: P
413
+ }), I = O(a, c, x.authorityId, x.purchaseId), L = n === "reverse" ? M(a, c, x.authorityId, x.refundId) : null;
414
+ return e.transactional(async (e) => {
415
+ await Y(e, a, o);
416
+ let s = await $(e, a, o, l, n, i);
417
+ if (s) return s;
418
+ if ((await Z(e, a, o)).count !== f.count) throw t("conflict");
419
+ let u = await e.query(j(S).where(k(A("tenantId", a), A("purchaseKey", I))).limit(r.maxHistoryRows + 1).descriptor);
420
+ if (u.length > r.maxHistoryRows) throw t("limit_exceeded");
421
+ if (n === "credit" && u.length || n === "reverse" && !u.some((e) => e.id === i.originalId && e.ownerKey === E(a, o) && e.state === "fulfilled") || L && (await e.query(j(S).where(k(A("tenantId", a), A("refundKey", L))).limit(1).descriptor)).length) throw t("conflict");
422
+ await ne(e, a, F), C && await ee(e, a, c, C, !0), await e.insert(S.tableName, {
423
+ id: l,
424
+ tenantId: a,
425
+ ownerId: o,
426
+ ownerKey: E(a, o),
427
+ loyaltyId: c,
428
+ sequence: f.count + 1,
429
+ state: "fulfilled",
430
+ purchaseKey: I,
431
+ refundKey: L,
432
+ digest: N([n, i]),
433
+ body: F,
434
+ createdAt: new Date(p)
435
+ }), await e.update(w.tableName, E(a, o), { entriesCount: f.count + 1 });
436
+ let d = (await Z(e, a, o)).accepted.find((e) => e.entry.id === l);
437
+ if (!d) throw t("invalid_record");
438
+ return Q(d);
439
+ });
440
+ }), ae = (t) => L(() => {
441
+ let n = F(t);
442
+ return I(async () => (await q(e, n.tenantId, n.ownerId), r.loyalty));
443
+ }), oe = (n, i) => L(() => {
444
+ let a = F(n), o = m(i);
445
+ return I(async () => {
446
+ let n = r.loyalty.find((e) => e.id === o.loyaltyId);
447
+ if (!n) throw t("not_found");
448
+ let i = d(), s = await e.transactional((e) => Z(e, a.tenantId, a.ownerId));
449
+ if (i < (s.accepted.at(-1)?.entry.at ?? 0) || s.programs.get(n.id)?.some((e) => e.loyalty.decay !== n.decay)) throw t("conflict");
450
+ let c = n.decay === "seasonal" ? W(await R(r.seasonSource.read(Object.freeze({
451
+ tenantId: a.tenantId,
452
+ loyaltyId: n.id,
453
+ at: i
454
+ }))), i) : null;
455
+ c && await e.transactional((e) => ee(e, a.tenantId, n.id, c, !1));
456
+ let l = s.projections.get(n.id)?.balances.find((e) => e.seasonId === (c?.id ?? null))?.points ?? "0", u = Object.freeze({
457
+ loyalty: n,
458
+ currencies: r.currencies,
459
+ realMoney: r.realMoney,
460
+ points: l,
461
+ rulesVersion: r.version
462
+ }), f = b(u, r.tier), p = y({
463
+ ...u,
464
+ tierId: f.id
465
+ }, r.perks);
466
+ if (((await q(e, a.tenantId, a.ownerId))?.entriesCount ?? 0) !== s.count) throw t("conflict");
467
+ return Object.freeze({
468
+ loyalty: n,
469
+ rulesVersion: r.version,
470
+ seasonId: c?.id ?? null,
471
+ points: l,
472
+ tierId: f.id,
473
+ perks: p
474
+ });
475
+ });
476
+ }), se = (e, t) => L(() => (K(e), ie("credit", p(t)))), ce = (e, t) => L(() => (K(e), ie("reverse", _(t)))), le = (t, n) => L(() => {
477
+ let r = F(t), i = g(n);
478
+ return I(() => e.transactional(async (e) => {
479
+ let t = await $(e, r.tenantId, r.ownerId, D(r.tenantId, r.ownerId, i.requestId));
480
+ return Object.freeze(t ? {
481
+ requestId: i.requestId,
482
+ state: "fulfilled",
483
+ receipt: t
484
+ } : {
485
+ requestId: i.requestId,
486
+ state: "not-observed"
487
+ });
488
+ }));
489
+ }), ue = (t, n) => L(() => {
490
+ K(t);
491
+ let r = h(n);
492
+ return I(() => e.transactional(async (e) => (await Z(e, r.tenantId, r.ownerId)).projections.get(r.loyaltyId) ?? v([])));
493
+ }), de = (e) => {
494
+ let n = i(e, [
495
+ "tenantId",
496
+ "subjectId",
497
+ "kind"
498
+ ]);
499
+ if (n.kind !== "guest" && n.kind !== "user") throw t("forbidden");
500
+ return Object.freeze({
501
+ tenantId: a(n.tenantId),
502
+ ownerId: a(n.subjectId)
503
+ });
504
+ };
505
+ return Object.freeze({
506
+ list: ae,
507
+ mine: oe,
508
+ credit: se,
509
+ reverse: ce,
510
+ receipt: le,
511
+ rebuild: ue,
512
+ exportSubject: (t) => L(() => {
513
+ let n = de(t);
514
+ return I(() => e.transactional(async (e) => {
515
+ if ((await q(e, n.tenantId, n.ownerId, !0))?.erased) return Object.freeze({ loyalty: [] });
516
+ let t = await Z(e, n.tenantId, n.ownerId);
517
+ return Object.freeze({ loyalty: Object.freeze(t.accepted.map((e) => Object.freeze({
518
+ receipt: Q(e),
519
+ definition: e.loyalty,
520
+ evidence: e.evidence,
521
+ season: e.season
522
+ }))) });
523
+ }));
524
+ }),
525
+ eraseSubject: (n) => L(() => {
526
+ let i = de(n);
527
+ return I(async () => {
528
+ await J(i.tenantId, i.ownerId), await e.transactional(async (e) => {
529
+ await Y(e, i.tenantId, i.ownerId, !0);
530
+ let n = await q(e, i.tenantId, i.ownerId, !0), a = await e.query(j(S).where(k(A("tenantId", i.tenantId), A("ownerKey", E(i.tenantId, i.ownerId)))).limit(r.maxHistoryRows + 1).descriptor);
531
+ if (a.length > r.maxHistoryRows) throw t("limit_exceeded");
532
+ if (a.length !== n?.entriesCount) throw t("invalid_record");
533
+ a.sort((e, t) => Number(e.sequence) - Number(t.sequence));
534
+ for (let [n, r] of a.entries()) {
535
+ if (!/^ele_[a-f0-9]{56}$/.test(String(r.id)) || r.sequence !== n + 1 || r.ownerId !== i.ownerId && r.ownerId !== null || r.state !== "fulfilled" && r.state !== "erased" || !/^[a-f0-9]{64}$/.test(String(r.purchaseKey)) || r.refundKey !== null && !/^[a-f0-9]{64}$/.test(String(r.refundKey))) throw t("invalid_record");
536
+ await e.update(S.tableName, String(r.id), {
537
+ ownerId: null,
538
+ state: "erased",
539
+ digest: null,
540
+ body: null
541
+ });
542
+ }
543
+ await e.update(w.tableName, E(i.tenantId, i.ownerId), {
544
+ ownerId: null,
545
+ erased: !0
546
+ });
547
+ });
548
+ });
549
+ })
550
+ });
551
+ };
552
+ export { K as dataStoreLoyalty, G as resolveLoyaltyStoreOptions };
@@ -0,0 +1,82 @@
1
+ import { loyaltyTables as e } from "./loyaltyTables.entity.js";
2
+ import { dataStoreLoyalty as t } from "./loyaltyStore.server.js";
3
+ import { shopLoyaltyReceiptSource as n } from "./loyaltyShopSource.server.js";
4
+ import { shopAt as r, shopFixture as i } from "./shop.testFixtures.js";
5
+ import { Effect as a } from "effect";
6
+ import { ensureTableRegistered as o } from "@voltro/database";
7
+ // src/loyaltyStore.testFixtures.ts
8
+ var s = async (s, c = "tenant", l = {}) => {
9
+ e.forEach(o);
10
+ let u = await i(s, c), d = r, f = {
11
+ currencies: [{
12
+ id: "test.gold",
13
+ kind: "soft"
14
+ }],
15
+ loyalty: [{
16
+ id: "vip",
17
+ titleKey: "test.vip",
18
+ decay: "seasonal",
19
+ pointsFrom: [{
20
+ id: "virtual.gold",
21
+ kind: "purchase.virtual",
22
+ currency: "test.gold",
23
+ numerator: "3",
24
+ denominator: "2"
25
+ }],
26
+ tiers: [{
27
+ id: "base",
28
+ at: "0",
29
+ perks: []
30
+ }, {
31
+ id: "silver",
32
+ at: "9",
33
+ perks: [{
34
+ id: "discount",
35
+ kind: "discount",
36
+ bps: 100
37
+ }]
38
+ }]
39
+ }],
40
+ receiptSource: n(s, {
41
+ shop: u.shop,
42
+ refunds: { read: (e) => a.succeed({
43
+ tenantId: e.tenantId,
44
+ ownerId: e.ownerId,
45
+ authorityId: e.purchase.authorityId,
46
+ purchaseId: e.purchase.purchaseId,
47
+ refundId: e.refundId,
48
+ totalRefunded: e.refundId === "partial" ? "2" : e.purchase.amount,
49
+ refundedAt: d
50
+ }) }
51
+ }),
52
+ seasonSource: { read: (e) => a.succeed(e.at < r + 864e5 ? {
53
+ id: "old",
54
+ startsAt: r,
55
+ endsAt: r + 864e5
56
+ } : {
57
+ id: "next",
58
+ startsAt: r + 864e5,
59
+ endsAt: r + 1728e5
60
+ }) },
61
+ version: "fixture.loyalty.v1",
62
+ now: () => d,
63
+ ...l
64
+ };
65
+ return {
66
+ base: u,
67
+ options: f,
68
+ service: t(s, f),
69
+ credit: (e, t = "credit") => ({
70
+ tenantId: c,
71
+ ownerId: "a",
72
+ loyaltyId: "vip",
73
+ sourceId: "virtual.gold",
74
+ purchaseId: e,
75
+ requestId: t
76
+ }),
77
+ setAt: (e) => {
78
+ d = e;
79
+ }
80
+ };
81
+ };
82
+ export { s as loyaltyStoreFixture };
@@ -0,0 +1,49 @@
1
+ import { boolean as e, id as t, integer as n, json as r, table as i, text as a, timestamp as o } from "@voltro/database";
2
+ // src/loyaltyTables.entity.ts
3
+ var s = () => a().maxLength(120).externalId().sensitive("pii"), c = i("_voltro_eco_loyalty_tenants", {
4
+ id: t({ prefix: "elt" }),
5
+ tenantId: s(),
6
+ admission: n().serverOnly()
7
+ }).index(["tenantId"]), l = i("_voltro_eco_loyalty_definitions", {
8
+ id: t({ prefix: "eld" }),
9
+ tenantId: s(),
10
+ loyaltyId: a().maxLength(120).serverOnly(),
11
+ definition: r().serverOnly(),
12
+ currencies: r().serverOnly(),
13
+ realMoney: e().serverOnly(),
14
+ rulesVersion: a().maxLength(120).serverOnly()
15
+ }).index(["tenantId", "loyaltyId"]), u = i("_voltro_eco_loyalty_subjects", {
16
+ id: t({ prefix: "els" }),
17
+ tenantId: s(),
18
+ ownerId: a().maxLength(120).nullable().externalId().sensitive("pii"),
19
+ erased: e().serverOnly(),
20
+ admission: n().serverOnly(),
21
+ entriesCount: n().serverOnly()
22
+ }).index(["tenantId", "ownerId"]), d = i("_voltro_eco_loyalty_entries", {
23
+ id: t({ prefix: "ele" }),
24
+ tenantId: s(),
25
+ ownerId: a().maxLength(120).nullable().externalId().sensitive("pii"),
26
+ ownerKey: a().maxLength(64).serverOnly(),
27
+ loyaltyId: a().maxLength(120).serverOnly(),
28
+ sequence: n().serverOnly(),
29
+ state: a().maxLength(16).oneOf(["fulfilled", "erased"]).serverOnly(),
30
+ purchaseKey: a().maxLength(64).serverOnly(),
31
+ refundKey: a().maxLength(64).nullable().serverOnly(),
32
+ digest: a().maxLength(64).nullable().serverOnly(),
33
+ body: r().nullable().serverOnly(),
34
+ createdAt: o().serverOnly()
35
+ }).index(["tenantId", "ownerKey"]).index(["tenantId", "purchaseKey"]).index(["tenantId", "refundKey"]), f = i("_voltro_eco_loyalty_seasons", {
36
+ id: t({ prefix: "elp" }),
37
+ tenantId: s(),
38
+ loyaltyId: a().maxLength(120).serverOnly(),
39
+ seasonId: a().maxLength(120).serverOnly(),
40
+ startsAt: o().serverOnly(),
41
+ endsAt: o().serverOnly()
42
+ }).index(["tenantId", "loyaltyId"]), p = [
43
+ c,
44
+ l,
45
+ u,
46
+ d,
47
+ f
48
+ ];
49
+ export { l as loyaltyDefinitionsTable, d as loyaltyEntriesTable, f as loyaltySeasonsTable, u as loyaltySubjectsTable, p as loyaltyTables, c as loyaltyTenantsTable };