@dapplelight/signet-db 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1556 -2
  3. package/dist/admin.d.ts +266 -0
  4. package/dist/admin.d.ts.map +1 -0
  5. package/dist/admin.js +671 -0
  6. package/dist/admin.js.map +1 -0
  7. package/dist/agent.d.ts +27 -0
  8. package/dist/agent.d.ts.map +1 -0
  9. package/dist/agent.js +117 -0
  10. package/dist/agent.js.map +1 -0
  11. package/dist/ai-cache.d.ts +9 -0
  12. package/dist/ai-cache.d.ts.map +1 -0
  13. package/dist/ai-cache.js +42 -0
  14. package/dist/ai-cache.js.map +1 -0
  15. package/dist/ai-spend.d.ts +91 -0
  16. package/dist/ai-spend.d.ts.map +1 -0
  17. package/dist/ai-spend.js +207 -0
  18. package/dist/ai-spend.js.map +1 -0
  19. package/dist/analytics-tools.d.ts +7 -0
  20. package/dist/analytics-tools.d.ts.map +1 -0
  21. package/dist/analytics-tools.js +110 -0
  22. package/dist/analytics-tools.js.map +1 -0
  23. package/dist/analytics.d.ts +92 -0
  24. package/dist/analytics.d.ts.map +1 -0
  25. package/dist/analytics.js +275 -0
  26. package/dist/analytics.js.map +1 -0
  27. package/dist/charts.d.ts +96 -0
  28. package/dist/charts.d.ts.map +1 -0
  29. package/dist/charts.js +457 -0
  30. package/dist/charts.js.map +1 -0
  31. package/dist/cipher.d.ts +24 -0
  32. package/dist/cipher.d.ts.map +1 -0
  33. package/dist/cipher.js +69 -0
  34. package/dist/cipher.js.map +1 -0
  35. package/dist/collab.d.ts +159 -0
  36. package/dist/collab.d.ts.map +1 -0
  37. package/dist/collab.js +492 -0
  38. package/dist/collab.js.map +1 -0
  39. package/dist/columns/pg.d.ts +6254 -0
  40. package/dist/columns/pg.d.ts.map +1 -0
  41. package/dist/columns/pg.js +507 -0
  42. package/dist/columns/pg.js.map +1 -0
  43. package/dist/columns/shared.d.ts +2 -0
  44. package/dist/columns/shared.d.ts.map +1 -0
  45. package/dist/columns/shared.js +2 -0
  46. package/dist/columns/shared.js.map +1 -0
  47. package/dist/columns/sqlite.d.ts +6680 -0
  48. package/dist/columns/sqlite.d.ts.map +1 -0
  49. package/dist/columns/sqlite.js +507 -0
  50. package/dist/columns/sqlite.js.map +1 -0
  51. package/dist/crypt.d.ts +5 -0
  52. package/dist/crypt.d.ts.map +1 -0
  53. package/dist/crypt.js +37 -0
  54. package/dist/crypt.js.map +1 -0
  55. package/dist/customers.d.ts +339 -0
  56. package/dist/customers.d.ts.map +1 -0
  57. package/dist/customers.js +714 -0
  58. package/dist/customers.js.map +1 -0
  59. package/dist/d1.d.ts +6 -0
  60. package/dist/d1.d.ts.map +1 -0
  61. package/dist/d1.js +11 -0
  62. package/dist/d1.js.map +1 -0
  63. package/dist/db.d.ts +33 -0
  64. package/dist/db.d.ts.map +1 -0
  65. package/dist/db.js +28 -0
  66. package/dist/db.js.map +1 -0
  67. package/dist/describe.d.ts +37 -0
  68. package/dist/describe.d.ts.map +1 -0
  69. package/dist/describe.js +79 -0
  70. package/dist/describe.js.map +1 -0
  71. package/dist/entitlement-tools.d.ts +17 -0
  72. package/dist/entitlement-tools.d.ts.map +1 -0
  73. package/dist/entitlement-tools.js +226 -0
  74. package/dist/entitlement-tools.js.map +1 -0
  75. package/dist/entitlements.d.ts +166 -0
  76. package/dist/entitlements.d.ts.map +1 -0
  77. package/dist/entitlements.js +493 -0
  78. package/dist/entitlements.js.map +1 -0
  79. package/dist/errors.d.ts +7 -0
  80. package/dist/errors.d.ts.map +1 -0
  81. package/dist/errors.js +12 -0
  82. package/dist/errors.js.map +1 -0
  83. package/dist/experiments.d.ts +97 -0
  84. package/dist/experiments.d.ts.map +1 -0
  85. package/dist/experiments.js +253 -0
  86. package/dist/experiments.js.map +1 -0
  87. package/dist/flags.d.ts +74 -0
  88. package/dist/flags.d.ts.map +1 -0
  89. package/dist/flags.js +127 -0
  90. package/dist/flags.js.map +1 -0
  91. package/dist/funnels.d.ts +236 -0
  92. package/dist/funnels.d.ts.map +1 -0
  93. package/dist/funnels.js +478 -0
  94. package/dist/funnels.js.map +1 -0
  95. package/dist/growth-tools.d.ts +10 -0
  96. package/dist/growth-tools.d.ts.map +1 -0
  97. package/dist/growth-tools.js +132 -0
  98. package/dist/growth-tools.js.map +1 -0
  99. package/dist/growth.d.ts +168 -0
  100. package/dist/growth.d.ts.map +1 -0
  101. package/dist/growth.js +406 -0
  102. package/dist/growth.js.map +1 -0
  103. package/dist/id.d.ts +3 -0
  104. package/dist/id.d.ts.map +1 -0
  105. package/dist/id.js +32 -0
  106. package/dist/id.js.map +1 -0
  107. package/dist/idempotency.d.ts +8 -0
  108. package/dist/idempotency.d.ts.map +1 -0
  109. package/dist/idempotency.js +66 -0
  110. package/dist/idempotency.js.map +1 -0
  111. package/dist/import.d.ts +33 -0
  112. package/dist/import.d.ts.map +1 -0
  113. package/dist/import.js +75 -0
  114. package/dist/import.js.map +1 -0
  115. package/dist/index.d.ts +15 -0
  116. package/dist/index.d.ts.map +1 -0
  117. package/dist/index.js +15 -0
  118. package/dist/index.js.map +1 -0
  119. package/dist/migrations/check.d.ts +11 -0
  120. package/dist/migrations/check.d.ts.map +1 -0
  121. package/dist/migrations/check.js +68 -0
  122. package/dist/migrations/check.js.map +1 -0
  123. package/dist/migrations/cli.d.ts +3 -0
  124. package/dist/migrations/cli.d.ts.map +1 -0
  125. package/dist/migrations/cli.js +30 -0
  126. package/dist/migrations/cli.js.map +1 -0
  127. package/dist/money.d.ts +16 -0
  128. package/dist/money.d.ts.map +1 -0
  129. package/dist/money.js +50 -0
  130. package/dist/money.js.map +1 -0
  131. package/dist/offerings.d.ts +133 -0
  132. package/dist/offerings.d.ts.map +1 -0
  133. package/dist/offerings.js +337 -0
  134. package/dist/offerings.js.map +1 -0
  135. package/dist/orgs.d.ts +144 -0
  136. package/dist/orgs.d.ts.map +1 -0
  137. package/dist/orgs.js +536 -0
  138. package/dist/orgs.js.map +1 -0
  139. package/dist/outbox.d.ts +23 -0
  140. package/dist/outbox.d.ts.map +1 -0
  141. package/dist/outbox.js +60 -0
  142. package/dist/outbox.js.map +1 -0
  143. package/dist/postgres.d.ts +7 -0
  144. package/dist/postgres.d.ts.map +1 -0
  145. package/dist/postgres.js +9 -0
  146. package/dist/postgres.js.map +1 -0
  147. package/dist/pricing.d.ts +79 -0
  148. package/dist/pricing.d.ts.map +1 -0
  149. package/dist/pricing.js +208 -0
  150. package/dist/pricing.js.map +1 -0
  151. package/dist/privacy-tools.d.ts +9 -0
  152. package/dist/privacy-tools.d.ts.map +1 -0
  153. package/dist/privacy-tools.js +51 -0
  154. package/dist/privacy-tools.js.map +1 -0
  155. package/dist/privacy.d.ts +71 -0
  156. package/dist/privacy.d.ts.map +1 -0
  157. package/dist/privacy.js +176 -0
  158. package/dist/privacy.js.map +1 -0
  159. package/dist/query.d.ts +6 -0
  160. package/dist/query.d.ts.map +1 -0
  161. package/dist/query.js +4 -0
  162. package/dist/query.js.map +1 -0
  163. package/dist/scoped.d.ts +51 -0
  164. package/dist/scoped.d.ts.map +1 -0
  165. package/dist/scoped.js +148 -0
  166. package/dist/scoped.js.map +1 -0
  167. package/dist/seed.d.ts +5 -0
  168. package/dist/seed.d.ts.map +1 -0
  169. package/dist/seed.js +195 -0
  170. package/dist/seed.js.map +1 -0
  171. package/dist/sequence.d.ts +4 -0
  172. package/dist/sequence.d.ts.map +1 -0
  173. package/dist/sequence.js +14 -0
  174. package/dist/sequence.js.map +1 -0
  175. package/dist/sqlite.d.ts +7 -0
  176. package/dist/sqlite.d.ts.map +1 -0
  177. package/dist/sqlite.js +13 -0
  178. package/dist/sqlite.js.map +1 -0
  179. package/dist/status.d.ts +101 -0
  180. package/dist/status.d.ts.map +1 -0
  181. package/dist/status.js +198 -0
  182. package/dist/status.js.map +1 -0
  183. package/dist/tool-kit.d.ts +44 -0
  184. package/dist/tool-kit.d.ts.map +1 -0
  185. package/dist/tool-kit.js +34 -0
  186. package/dist/tool-kit.js.map +1 -0
  187. package/dist/user-data.d.ts +9 -0
  188. package/dist/user-data.d.ts.map +1 -0
  189. package/dist/user-data.js +50 -0
  190. package/dist/user-data.js.map +1 -0
  191. package/dist/versions.d.ts +12 -0
  192. package/dist/versions.d.ts.map +1 -0
  193. package/dist/versions.js +44 -0
  194. package/dist/versions.js.map +1 -0
  195. package/dist/webhooks.d.ts +95 -0
  196. package/dist/webhooks.d.ts.map +1 -0
  197. package/dist/webhooks.js +342 -0
  198. package/dist/webhooks.js.map +1 -0
  199. package/dist/workflows.d.ts +186 -0
  200. package/dist/workflows.d.ts.map +1 -0
  201. package/dist/workflows.js +563 -0
  202. package/dist/workflows.js.map +1 -0
  203. package/dist/zod.d.ts +14 -0
  204. package/dist/zod.d.ts.map +1 -0
  205. package/dist/zod.js +48 -0
  206. package/dist/zod.js.map +1 -0
  207. package/package.json +205 -4
@@ -0,0 +1,714 @@
1
+ import { and, desc, eq, isNull, ne } from "drizzle-orm";
2
+ import { PROMOTIONAL } from "./entitlements.js";
3
+ import { SignetDbError } from "./errors.js";
4
+ import { newId } from "./id.js";
5
+ import { offerEligible, } from "./offerings.js";
6
+ import { audited } from "./scoped.js";
7
+ const PAID = new Set(["active", "trialing"]);
8
+ const STORES = new Set(["appstore", "googleplay"]);
9
+ const UNPAID = new Set(["manual", PROMOTIONAL]);
10
+ const SUBSCRIBED = new Set(["trial", "purchase", "renewal"]);
11
+ const COUNTRY = /^[A-Z]{2}$/;
12
+ const DAY = 86_400_000;
13
+ export function isTrial(e) {
14
+ const t = e.raw?.transaction;
15
+ return e.amount === 0 || t?.offerDiscountType === "FREE_TRIAL";
16
+ }
17
+ export function timelineKind(e) {
18
+ switch (e.type) {
19
+ case "subscription.created":
20
+ case "subscription.activated":
21
+ case "payment.captured":
22
+ return isTrial(e) ? "trial" : "purchase";
23
+ case "subscription.charged":
24
+ return "renewal";
25
+ case "refund.processed":
26
+ return "refund";
27
+ case "subscription.cancelled":
28
+ return "cancellation";
29
+ case "subscription.resumed":
30
+ return "uncancellation";
31
+ case "subscription.paused":
32
+ return "paused";
33
+ case "subscription.expired":
34
+ return "expiration";
35
+ case "payment.failed":
36
+ return "billing_issue";
37
+ case "subscription.past_due": {
38
+ const r = e.raw;
39
+ const grace = r?.payload?.data?.status === 4 ||
40
+ r?.subscription?.subscriptionState === "SUBSCRIPTION_STATE_IN_GRACE_PERIOD";
41
+ return grace ? "grace_period" : "billing_issue";
42
+ }
43
+ default:
44
+ if (e.gatewayType === "CONSUMPTION_REQUEST")
45
+ return "refund_request";
46
+ return e.type.startsWith("dispute.") ? "dispute" : undefined;
47
+ }
48
+ }
49
+ const bad = (m) => new SignetDbError("BAD_VALUE", m);
50
+ const text = (v, name, max) => {
51
+ if (typeof v !== "string" || !v.trim() || v.length > max)
52
+ throw bad(`${name} is required, at most ${max} characters.`);
53
+ return v.trim();
54
+ };
55
+ export function createCustomers(db, options) {
56
+ const T = options.tables;
57
+ const ic = T.customerIdentities;
58
+ const ec = T.customerEvents;
59
+ const rc = T.customerRequests;
60
+ const pc = T.subjectPlans;
61
+ const xc = T.entitlementOverrides;
62
+ const o = db.orm;
63
+ const now = options.now ?? (() => new Date());
64
+ const pay = options.payments;
65
+ async function identity(id) {
66
+ return (await o.select().from(T.customerIdentities).where(eq(ic.id, id)).limit(1))[0];
67
+ }
68
+ async function anonymousId(opts = {}) {
69
+ const id = `anon_${crypto.randomUUID()}`;
70
+ await o.insert(T.customerIdentities).values({ id, orgId: opts.orgId ?? null, subject: null });
71
+ return id;
72
+ }
73
+ async function resolve(id) {
74
+ return (await identity(id))?.subject ?? id;
75
+ }
76
+ async function merge(input, opts = {}) {
77
+ const { anonymousId: from, userId: to } = input;
78
+ if (!from || !to)
79
+ throw bad("merge needs anonymousId and userId.");
80
+ if (from === to)
81
+ return { merged: false, reason: "same_subject" };
82
+ const row = await identity(from);
83
+ if (!row)
84
+ return { merged: false, reason: "not_anonymous" };
85
+ if ((row.orgId ?? null) !== (input.orgId ?? null))
86
+ return { merged: false, reason: "other_org" };
87
+ if (await identity(to))
88
+ return { merged: false, reason: "target_is_anonymous" };
89
+ if (input.orgId && options.isMember && !(await options.isMember(to, input.orgId)))
90
+ return { merged: false, reason: "not_member" };
91
+ const claimed = await o
92
+ .update(T.customerIdentities)
93
+ .set({ subject: to, mergedAt: now() })
94
+ .where(and(eq(ic.id, from), isNull(ic.subject)))
95
+ .returning();
96
+ if (!claimed.length && (await identity(from))?.subject !== to)
97
+ return { merged: false, reason: "already_merged" };
98
+ const actor = opts.actor ?? { type: "system", id: "identity-merge" };
99
+ const w = audited(db, { actor });
100
+ const subscriptions = (await w.update(T.subjectPlans, { subject: to }, and(eq(pc.subject, from), ne(pc.gateway, "manual")))).length;
101
+ const overrides = (await w.update(T.entitlementOverrides, { subject: to }, eq(xc.subject, from))).length;
102
+ const events = (await o.update(T.customerEvents).set({ subject: to }).where(eq(ec.subject, from)).returning()).length;
103
+ const requests = (await o
104
+ .update(T.customerRequests)
105
+ .set({ subject: to })
106
+ .where(eq(rc.subject, from))
107
+ .returning()).length;
108
+ const payments = (await pay?.reassignUser?.(from, to)) ?? 0;
109
+ return {
110
+ merged: true,
111
+ already: !claimed.length,
112
+ moved: { subscriptions, overrides, events, requests, payments },
113
+ };
114
+ }
115
+ async function subjectOf(e) {
116
+ if (e.subscriptionId) {
117
+ const [src] = await o
118
+ .select()
119
+ .from(T.subjectPlans)
120
+ .where(eq(pc.id, `${e.gateway}|${e.subscriptionId}`))
121
+ .limit(1);
122
+ if (src)
123
+ return src.subject;
124
+ }
125
+ if (!pay)
126
+ return undefined;
127
+ if (e.paymentId) {
128
+ const p = await pay.getPayment(e.gateway, e.paymentId);
129
+ if (p?.userId)
130
+ return p.userId;
131
+ }
132
+ const link = e.orderId ?? e.subscriptionId;
133
+ return link ? (await pay.findLinked(e.gateway, { orderId: link }))?.userId : undefined;
134
+ }
135
+ const country = (c) => {
136
+ if (c === undefined)
137
+ return null;
138
+ const up = typeof c === "string" ? c.toUpperCase() : "";
139
+ if (!COUNTRY.test(up))
140
+ throw bad("country is an ISO 3166-1 alpha-2 code, e.g. IN.");
141
+ return up;
142
+ };
143
+ const entryOf = (e, kind) => ({
144
+ id: `${e.gateway}|${e.id}`,
145
+ kind,
146
+ gateway: e.gateway,
147
+ eventType: e.gatewayType ?? e.type,
148
+ subscriptionId: e.subscriptionId ?? null,
149
+ paymentId: e.paymentId ?? null,
150
+ productId: e.productId ?? null,
151
+ amount: e.amount ?? null,
152
+ currency: e.currency ?? null,
153
+ approximate: !!e.approximate,
154
+ occurredAt: e.occurredAt,
155
+ });
156
+ async function record(event, opts = {}) {
157
+ const kind = timelineKind(event);
158
+ if (!kind)
159
+ return { recorded: false, reason: "not_on_timeline" };
160
+ const found = opts.subject ?? (await subjectOf(event));
161
+ if (!found)
162
+ return { recorded: false, kind, reason: "no_subject" };
163
+ const subject = await resolve(found);
164
+ const done = await o
165
+ .insert(T.customerEvents)
166
+ .values({ ...entryOf(event, kind), subject, country: country(opts.country) })
167
+ .onConflictDoNothing()
168
+ .returning();
169
+ return done.length
170
+ ? { recorded: true, kind, subject }
171
+ : { recorded: false, kind, subject, reason: "duplicate" };
172
+ }
173
+ const viewEntry = (r) => ({
174
+ id: r.id,
175
+ kind: r.kind,
176
+ gateway: r.gateway,
177
+ eventType: r.eventType,
178
+ subscriptionId: r.subscriptionId ?? null,
179
+ paymentId: r.paymentId ?? null,
180
+ productId: r.productId ?? null,
181
+ amount: r.amount == null ? null : Number(r.amount),
182
+ currency: r.currency ?? null,
183
+ approximate: !!r.approximate,
184
+ occurredAt: r.occurredAt,
185
+ });
186
+ async function timeline(subject, opts = {}) {
187
+ const limit = Math.min(Math.max(opts.limit ?? 200, 1), 1000);
188
+ const byId = new Map();
189
+ for (const r of await o
190
+ .select()
191
+ .from(T.customerEvents)
192
+ .where(and(eq(ec.subject, subject), ne(ec.kind, "impression")))
193
+ .orderBy(desc(ec.occurredAt))
194
+ .limit(limit))
195
+ byId.set(r.id, viewEntry(r));
196
+ const at = now();
197
+ for (const p of await o
198
+ .select()
199
+ .from(T.subjectPlans)
200
+ .where(and(eq(pc.subject, subject), eq(pc.gateway, PROMOTIONAL)))) {
201
+ const end = p.currentPeriodEnd;
202
+ const id = `${PROMOTIONAL}|${p.subscriptionId}|end`;
203
+ if (end && end <= at && !byId.has(id))
204
+ byId.set(id, {
205
+ id,
206
+ kind: "expiration",
207
+ gateway: PROMOTIONAL,
208
+ eventType: "promotional.expired",
209
+ subscriptionId: p.subscriptionId,
210
+ paymentId: null,
211
+ productId: p.plan,
212
+ amount: null,
213
+ currency: null,
214
+ approximate: false,
215
+ occurredAt: end,
216
+ });
217
+ }
218
+ const totals = new Map();
219
+ if (pay) {
220
+ for (const p of await pay.listPayments({ userId: subject, limit })) {
221
+ for (const e of await pay.eventsFor(p.gateway, p.gatewayId)) {
222
+ const kind = timelineKind(e);
223
+ const id = `${e.gateway}|${e.id}`;
224
+ if (kind && !byId.has(id))
225
+ byId.set(id, entryOf(e, kind));
226
+ }
227
+ for (const l of await pay.entries({ ref: p.gatewayId, gateway: p.gateway })) {
228
+ const t = totals.get(l.currency) ?? {
229
+ currency: l.currency,
230
+ paid: 0,
231
+ refunded: 0,
232
+ approximate: false,
233
+ };
234
+ if (l.account === "revenue")
235
+ t.paid -= l.amount;
236
+ else if (l.account === "refunds")
237
+ t.refunded += l.amount;
238
+ else
239
+ continue;
240
+ if (l.kind.endsWith(":approximate"))
241
+ t.approximate = true;
242
+ totals.set(l.currency, t);
243
+ }
244
+ }
245
+ }
246
+ const entries = [...byId.values()]
247
+ .sort((a, b) => b.occurredAt.getTime() - a.occurredAt.getTime() || b.id.localeCompare(a.id))
248
+ .slice(0, limit);
249
+ return { subject, entries, totals: [...totals.values()] };
250
+ }
251
+ function manageUrl(source) {
252
+ const custom = options.manageUrl?.(source);
253
+ if (custom !== undefined)
254
+ return custom;
255
+ if (source.gateway === "appstore")
256
+ return "https://apps.apple.com/account/subscriptions";
257
+ if (source.gateway === "googleplay") {
258
+ const base = "https://play.google.com/store/account/subscriptions";
259
+ return source.productId && options.googlePlayPackage
260
+ ? `${base}?sku=${encodeURIComponent(source.productId)}&package=${encodeURIComponent(options.googlePlayPackage)}`
261
+ : base;
262
+ }
263
+ return null;
264
+ }
265
+ async function productOf(s) {
266
+ const [r] = await o
267
+ .select()
268
+ .from(T.customerEvents)
269
+ .where(and(eq(ec.gateway, s.gateway), eq(ec.subscriptionId, s.subscriptionId)))
270
+ .orderBy(desc(ec.occurredAt))
271
+ .limit(1);
272
+ return r?.productId ?? undefined;
273
+ }
274
+ async function base(subject) {
275
+ if (!subject)
276
+ throw bad("A subject id is required.");
277
+ const r = await options.entitlements.get(subject);
278
+ const paid = r.source && !UNPAID.has(r.source.gateway) ? r.source : null;
279
+ const productId = paid ? await productOf(paid) : undefined;
280
+ const source = paid ? { ...paid, ...(productId ? { productId } : {}) } : null;
281
+ const store = !!source && STORES.has(source.gateway);
282
+ const cancelled = !!source && !store && !!(await request(`cancel|${source.gateway}|${source.subscriptionId}`));
283
+ const renews = !!source && PAID.has(r.status ?? "") && !cancelled;
284
+ return {
285
+ subject,
286
+ plan: r.plan,
287
+ status: r.status,
288
+ currentPeriodEnd: r.currentPeriodEnd,
289
+ graceUntil: r.graceUntil,
290
+ renews,
291
+ source,
292
+ store,
293
+ manageUrl: source && store ? manageUrl(source) : null,
294
+ canCancel: renews && !store && !!options.cancel,
295
+ };
296
+ }
297
+ async function request(id) {
298
+ const [r] = await o.select().from(T.customerRequests).where(eq(rc.id, id)).limit(1);
299
+ return r ? viewRequest(r) : null;
300
+ }
301
+ const viewRequest = (r) => ({
302
+ id: r.id,
303
+ subject: r.subject,
304
+ kind: r.kind,
305
+ status: r.status,
306
+ gateway: r.gateway ?? null,
307
+ reference: r.reference ?? null,
308
+ message: r.message ?? null,
309
+ data: r.data ?? null,
310
+ createdAt: r.createdAt,
311
+ updatedAt: r.updatedAt,
312
+ });
313
+ async function offerFor(ov) {
314
+ const cfg = options.retention;
315
+ if (!cfg || !ov.source || !ov.renews)
316
+ return null;
317
+ const used = await o
318
+ .select()
319
+ .from(T.customerRequests)
320
+ .where(and(eq(rc.subject, ov.subject), eq(rc.kind, "retention")))
321
+ .limit(1);
322
+ if (used.length)
323
+ return null;
324
+ const ok = cfg.eligible ? await cfg.eligible({ subject: ov.subject, overview: ov }) : !ov.store;
325
+ return ok ? cfg.offer : null;
326
+ }
327
+ async function overview(subject) {
328
+ const ov = await base(subject);
329
+ return { ...ov, retention: await offerFor(ov) };
330
+ }
331
+ async function cancel(subject, opts = {}) {
332
+ const ov = await base(subject);
333
+ if (!ov.source || !ov.renews)
334
+ return { cancelled: false, reason: "no_subscription" };
335
+ if (ov.store)
336
+ return { cancelled: false, reason: "store", manageUrl: ov.manageUrl };
337
+ if (!options.cancel)
338
+ return { cancelled: false, reason: "not_cancellable" };
339
+ await options.cancel(ov.source);
340
+ await o
341
+ .insert(T.customerRequests)
342
+ .values({
343
+ id: `cancel|${ov.source.gateway}|${ov.source.subscriptionId}`,
344
+ subject,
345
+ kind: "cancel",
346
+ status: "done",
347
+ gateway: ov.source.gateway,
348
+ reference: ov.source.subscriptionId,
349
+ message: opts.reason ? text(opts.reason, "reason", 2000) : null,
350
+ data: null,
351
+ })
352
+ .onConflictDoNothing();
353
+ return { cancelled: true, source: ov.source };
354
+ }
355
+ async function acceptRetention(subject) {
356
+ const ov = await base(subject);
357
+ const offer = await offerFor(ov);
358
+ if (!offer || !ov.source || !options.retention)
359
+ return { accepted: false, reason: "not_eligible" };
360
+ const id = `retention|${subject}`;
361
+ const mine = await o
362
+ .insert(T.customerRequests)
363
+ .values({
364
+ id,
365
+ subject,
366
+ kind: "retention",
367
+ status: "open",
368
+ gateway: ov.source.gateway,
369
+ reference: ov.source.subscriptionId,
370
+ message: null,
371
+ data: { offer },
372
+ })
373
+ .onConflictDoNothing()
374
+ .returning();
375
+ if (!mine.length)
376
+ return { accepted: false, reason: "already_used" };
377
+ try {
378
+ await options.retention.apply({ subject, source: ov.source, offer });
379
+ }
380
+ catch (err) {
381
+ await o.delete(T.customerRequests).where(eq(rc.id, id));
382
+ throw err;
383
+ }
384
+ await o.update(T.customerRequests).set({ status: "done" }).where(eq(rc.id, id));
385
+ return { accepted: true, offer };
386
+ }
387
+ async function send(kind, req, line) {
388
+ if (!options.notify || req.data?.notified)
389
+ return;
390
+ await options.notify({ kind, subject: req.subject, request: req, text: line });
391
+ await o
392
+ .update(T.customerRequests)
393
+ .set({ data: { ...req.data, notified: true } })
394
+ .where(eq(rc.id, req.id));
395
+ }
396
+ async function requestRefund(subject, input) {
397
+ const gateway = text(input.gateway, "gateway", 40);
398
+ const paymentId = text(input.paymentId, "paymentId", 200);
399
+ const reason = text(input.reason, "reason", 2000);
400
+ const owned = pay
401
+ ? (await pay.getPayment(gateway, paymentId))?.userId === subject
402
+ : (await o
403
+ .select()
404
+ .from(T.customerEvents)
405
+ .where(and(eq(ec.subject, subject), eq(ec.gateway, gateway), eq(ec.paymentId, paymentId)))
406
+ .limit(1)).length > 0;
407
+ if (!owned)
408
+ throw new SignetDbError("NOT_FOUND", "No such payment for this customer.");
409
+ const id = `refund|${gateway}|${paymentId}`;
410
+ const created = await o
411
+ .insert(T.customerRequests)
412
+ .values({
413
+ id,
414
+ subject,
415
+ kind: "refund",
416
+ status: "open",
417
+ gateway,
418
+ reference: paymentId,
419
+ message: reason,
420
+ data: {},
421
+ })
422
+ .onConflictDoNothing()
423
+ .returning();
424
+ const req = (await request(id));
425
+ await send("refund_request", req, `Refund requested for ${gateway} ${paymentId} by ${subject}: ${reason}`);
426
+ return {
427
+ request: (await request(id)),
428
+ created: created.length > 0,
429
+ ...(gateway === "appstore" ? { storeUrl: "https://reportaproblem.apple.com" } : {}),
430
+ };
431
+ }
432
+ async function contactSupport(subject, input) {
433
+ if (!subject)
434
+ throw bad("A subject id is required.");
435
+ const message = text(input.message, "message", 5000);
436
+ const data = {};
437
+ if (input.email !== undefined)
438
+ data.email = text(input.email, "email", 320);
439
+ if (input.topic !== undefined)
440
+ data.topic = text(input.topic, "topic", 100);
441
+ const id = newId(now().getTime());
442
+ await o.insert(T.customerRequests).values({
443
+ id,
444
+ subject,
445
+ kind: "support",
446
+ status: "open",
447
+ gateway: null,
448
+ reference: null,
449
+ message,
450
+ data,
451
+ });
452
+ const req = (await request(id));
453
+ await send("support", req, `Support message from ${subject}${data.topic ? ` (${data.topic})` : ""}: ${message}`);
454
+ return (await request(id));
455
+ }
456
+ async function requests(filter = {}) {
457
+ const conds = [
458
+ filter.subject ? eq(rc.subject, filter.subject) : undefined,
459
+ filter.kind ? eq(rc.kind, filter.kind) : undefined,
460
+ filter.status ? eq(rc.status, filter.status) : undefined,
461
+ ].filter(Boolean);
462
+ const rows = await o
463
+ .select()
464
+ .from(T.customerRequests)
465
+ .where(conds.length ? and(...conds) : undefined)
466
+ .orderBy(desc(rc.createdAt), desc(rc.id))
467
+ .limit(Math.min(Math.max(filter.limit ?? 100, 1), 500));
468
+ return rows.map(viewRequest);
469
+ }
470
+ async function setRequestStatus(id, status, { actor }) {
471
+ if (!["open", "done", "declined"].includes(status))
472
+ throw bad("status is open, done or declined.");
473
+ await audited(db, { actor }).update(T.customerRequests, { status }, eq(rc.id, id));
474
+ return request(id);
475
+ }
476
+ async function logImpression(subject, input) {
477
+ if (!subject)
478
+ throw bad("A subject id is required.");
479
+ const offering = text(input.offering, "offering", 64);
480
+ const at = now();
481
+ const day = at.toISOString().slice(0, 10);
482
+ const who = await resolve(subject);
483
+ const done = await o
484
+ .insert(T.customerEvents)
485
+ .values({
486
+ id: `impression|${who}|${offering}|${day}`,
487
+ subject: who,
488
+ kind: "impression",
489
+ gateway: "paywall",
490
+ eventType: input.placement ? `impression:${input.placement}` : "impression",
491
+ subscriptionId: null,
492
+ paymentId: null,
493
+ productId: input.version === undefined ? null : `${offering}@${input.version}`,
494
+ amount: null,
495
+ currency: null,
496
+ approximate: false,
497
+ occurredAt: at,
498
+ country: country(input.country),
499
+ offering,
500
+ })
501
+ .onConflictDoNothing()
502
+ .returning();
503
+ return { logged: done.length > 0 };
504
+ }
505
+ async function grantPromotional(subject, input, { actor }) {
506
+ const grant = options.entitlements.grantPromotional;
507
+ if (!grant)
508
+ throw new SignetDbError("FORBIDDEN", "Pass createEntitlements(...) to grant promotional plans.");
509
+ if (!subject)
510
+ throw bad("A subject id is required.");
511
+ const expiresAt = input.expiresAt ??
512
+ (Number.isSafeInteger(input.days) &&
513
+ input.days > 0 &&
514
+ input.days <= 3660
515
+ ? new Date(now().getTime() + input.days * DAY)
516
+ : undefined);
517
+ if (!expiresAt)
518
+ throw bad("Give expiresAt, or days from 1 to 3660.");
519
+ const note = input.note === undefined ? null : text(input.note, "note", 500);
520
+ const r = await grant.call(options.entitlements, subject, input.plan, {
521
+ actor,
522
+ expiresAt,
523
+ });
524
+ await o
525
+ .insert(T.customerEvents)
526
+ .values({
527
+ id: `${PROMOTIONAL}|${r.id}`,
528
+ subject,
529
+ kind: "promotional",
530
+ gateway: PROMOTIONAL,
531
+ eventType: note ? `promotional.granted: ${note}` : "promotional.granted",
532
+ subscriptionId: r.id,
533
+ paymentId: null,
534
+ productId: input.plan,
535
+ amount: null,
536
+ currency: null,
537
+ approximate: false,
538
+ occurredAt: now(),
539
+ })
540
+ .onConflictDoNothing();
541
+ return { id: r.id, plan: input.plan, expiresAt: r.expiresAt };
542
+ }
543
+ async function endPromotional(subject, id, { actor }) {
544
+ const end = options.entitlements.endPromotional;
545
+ if (!end)
546
+ throw new SignetDbError("FORBIDDEN", "Pass createEntitlements(...) to end grants.");
547
+ if (!(await end.call(options.entitlements, subject, id, { actor })))
548
+ return false;
549
+ await o
550
+ .insert(T.customerEvents)
551
+ .values({
552
+ id: `${PROMOTIONAL}|${id}|end`,
553
+ subject,
554
+ kind: "expiration",
555
+ gateway: PROMOTIONAL,
556
+ eventType: "promotional.ended",
557
+ subscriptionId: id,
558
+ paymentId: null,
559
+ productId: null,
560
+ amount: null,
561
+ currency: null,
562
+ approximate: false,
563
+ occurredAt: now(),
564
+ })
565
+ .onConflictDoNothing();
566
+ return true;
567
+ }
568
+ async function offerHistory(subject) {
569
+ const r = await options.entitlements.get(subject);
570
+ const subs = (r.entitlements ?? [])
571
+ .flatMap((e) => e.sources)
572
+ .filter((x) => !UNPAID.has(x.gateway));
573
+ const events = await o
574
+ .select()
575
+ .from(T.customerEvents)
576
+ .where(eq(ec.subject, subject))
577
+ .orderBy(desc(ec.occurredAt));
578
+ const ends = subs.flatMap((x) => (x.currentPeriodEnd ? [x.currentPeriodEnd.getTime()] : []));
579
+ const lastEnd = events.find((e) => e.kind === "expiration" && e.gateway !== PROMOTIONAL)?.occurredAt;
580
+ const lapsed = ends.length ? Math.max(...ends) : lastEnd ? lastEnd.getTime() : null;
581
+ const redeemed = await o
582
+ .select()
583
+ .from(T.customerRequests)
584
+ .where(and(eq(rc.subject, subject), eq(rc.kind, "offer")));
585
+ return {
586
+ subscribed: subs.length > 0 || events.some((e) => SUBSCRIBED.has(e.kind)),
587
+ active: subs.some((x) => x.active),
588
+ lapsedAt: lapsed === null ? null : new Date(lapsed),
589
+ trialed: events.some((e) => e.kind === "trial"),
590
+ redeemed: new Set(redeemed.map((x) => x.data?.offer)),
591
+ };
592
+ }
593
+ const NEW_CUSTOMER = {
594
+ subscribed: false,
595
+ active: false,
596
+ lapsedAt: null,
597
+ trialed: false,
598
+ redeemed: new Set(),
599
+ };
600
+ async function withOffers(subject, offering) {
601
+ const h = subject ? await offerHistory(await resolve(subject)) : NEW_CUSTOMER;
602
+ const at = now();
603
+ return {
604
+ ...offering,
605
+ products: offering.products.map((p) => {
606
+ if (!p.offers)
607
+ return { ...p };
608
+ const offers = p.offers.filter((x) => offerEligible(x, h, at));
609
+ const { offers: _all, ...rest } = p;
610
+ return offers.length ? { ...rest, offers } : rest;
611
+ }),
612
+ };
613
+ }
614
+ async function redeemOffer(subject, offering, offerId) {
615
+ const who = await resolve(subject);
616
+ const product = offering.products.find((p) => p.offers?.some((x) => x.id === offerId));
617
+ const offer = product?.offers?.find((x) => x.id === offerId);
618
+ if (!product || !offer)
619
+ return { redeemed: false, reason: "no_such_offer" };
620
+ const h = await offerHistory(who);
621
+ if (h.redeemed.has(offerId) && (offer.eligibility?.once ?? true))
622
+ return { redeemed: false, reason: "already_used" };
623
+ if (!offerEligible(offer, h, now()))
624
+ return { redeemed: false, reason: "not_eligible" };
625
+ const once = offer.eligibility?.once ?? true;
626
+ const mine = await o
627
+ .insert(T.customerRequests)
628
+ .values({
629
+ id: once ? `offer|${who}|${offerId}` : newId(now().getTime()),
630
+ subject: who,
631
+ kind: "offer",
632
+ status: "done",
633
+ gateway: product.store,
634
+ reference: product.id,
635
+ message: null,
636
+ data: { offer: offerId, type: offer.type, offering: offering.key },
637
+ })
638
+ .onConflictDoNothing()
639
+ .returning();
640
+ if (!mine.length)
641
+ return { redeemed: false, reason: "already_used" };
642
+ return { redeemed: true, offer, product };
643
+ }
644
+ async function consumptionInfo(event, opts = {}) {
645
+ if (event.gateway !== "appstore" ||
646
+ event.gatewayType !== "CONSUMPTION_REQUEST" ||
647
+ !event.paymentId)
648
+ return { respond: false, reason: "not_consumption_request" };
649
+ const cfg = options.consumption;
650
+ if (!cfg)
651
+ return { respond: false, reason: "not_configured" };
652
+ const found = opts.subject ?? (await subjectOf(event));
653
+ if (!found)
654
+ return { respond: false, reason: "no_subject" };
655
+ const subject = await resolve(found);
656
+ if ((await cfg.consented(subject)) !== true)
657
+ return { respond: false, reason: "no_consent" };
658
+ const transactionId = event.paymentId;
659
+ const { entries } = await timeline(subject, { limit: 1000 });
660
+ const reason = event.raw?.payload?.data?.consumptionRequestReason ?? null;
661
+ const ctx = { subject, transactionId, reason, entries, event };
662
+ const bought = entries.find((e) => e.gateway === "appstore" &&
663
+ (e.paymentId === transactionId ||
664
+ (!!event.subscriptionId && e.subscriptionId === event.subscriptionId)) &&
665
+ (SUBSCRIBED.has(e.kind) || e.kind === "purchase"));
666
+ const deliveryStatus = cfg.deliveryStatus?.(ctx) ?? (bought ? "DELIVERED" : "UNDELIVERED_OTHER");
667
+ const refundPreference = cfg.refundPreference?.(ctx);
668
+ let pct = cfg.consumptionPercentage?.(ctx);
669
+ if (pct === undefined && deliveryStatus === "DELIVERED" && event.subscriptionId) {
670
+ const r = await options.entitlements.get(subject);
671
+ const end = (r.entitlements ?? [])
672
+ .flatMap((e) => e.sources)
673
+ .find((x) => x.gateway === "appstore" && x.subscriptionId === event.subscriptionId)?.currentPeriodEnd;
674
+ const start = entries.find((e) => e.subscriptionId === event.subscriptionId && SUBSCRIBED.has(e.kind))?.occurredAt;
675
+ if (start && end && end > start) {
676
+ const used = (now().getTime() - start.getTime()) / (end.getTime() - start.getTime());
677
+ pct = Math.round(Math.min(Math.max(used, 0), 1) * 100000);
678
+ }
679
+ }
680
+ if (deliveryStatus !== "DELIVERED")
681
+ pct = 0;
682
+ if (refundPreference === "GRANT_PRORATED")
683
+ pct = undefined;
684
+ const body = {
685
+ customerConsented: true,
686
+ deliveryStatus,
687
+ sampleContentProvided: cfg.sampleContentProvided?.(ctx) ?? entries.some((e) => e.kind === "trial"),
688
+ ...(pct !== undefined ? { consumptionPercentage: pct } : {}),
689
+ ...(refundPreference ? { refundPreference } : {}),
690
+ };
691
+ return { respond: true, subject, transactionId, body };
692
+ }
693
+ return {
694
+ anonymousId,
695
+ resolve,
696
+ merge,
697
+ record,
698
+ timeline,
699
+ overview,
700
+ cancel,
701
+ acceptRetention,
702
+ requestRefund,
703
+ contactSupport,
704
+ requests,
705
+ setRequestStatus,
706
+ logImpression,
707
+ grantPromotional,
708
+ endPromotional,
709
+ withOffers,
710
+ redeemOffer,
711
+ consumptionInfo,
712
+ };
713
+ }
714
+ //# sourceMappingURL=customers.js.map