billfn 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +73 -0
- package/dist/errors.js.map +1 -0
- package/dist/helpers.d.ts +13 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/helpers.js +102 -0
- package/dist/helpers.js.map +1 -0
- package/dist/http.d.ts +5 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +33 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/router.d.ts +3 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +293 -0
- package/dist/router.js.map +1 -0
- package/dist/schema.d.ts +10 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +243 -0
- package/dist/schema.js.map +1 -0
- package/dist/service.d.ts +58 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +1699 -0
- package/dist/service.js.map +1 -0
- package/dist/types.d.ts +604 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +42 -0
package/dist/service.js
ADDED
|
@@ -0,0 +1,1699 @@
|
|
|
1
|
+
import { AdapterErrorCode, DuplicateKeyError, NotFoundError } from '@superfunctions/db';
|
|
2
|
+
import { ok } from '@superfunctions/envelope';
|
|
3
|
+
import { createNamespacedEmitter, createMetricsEmitter } from '@superfunctions/metrics';
|
|
4
|
+
import { createBillFnError } from './errors.js';
|
|
5
|
+
import { createDefaultBillingAccountResolver, defaultIdFactory, resolvePlan, resolvePrice, toIsoString } from './helpers.js';
|
|
6
|
+
const TABLES = {
|
|
7
|
+
billingAccounts: 'billingAccounts',
|
|
8
|
+
subscriptions: 'subscriptions',
|
|
9
|
+
checkoutSessions: 'checkoutSessions',
|
|
10
|
+
entitlementSnapshots: 'entitlementSnapshots',
|
|
11
|
+
usageMeters: 'usageMeters',
|
|
12
|
+
usageLedger: 'usageLedger',
|
|
13
|
+
webhookReceipts: 'webhookReceipts',
|
|
14
|
+
billingEvents: 'billingEvents',
|
|
15
|
+
refunds: 'refunds',
|
|
16
|
+
subscriptionChangeRequests: 'subscriptionChangeRequests',
|
|
17
|
+
reconciliationJobs: 'reconciliationJobs',
|
|
18
|
+
reconciliationCursors: 'reconciliationCursors'
|
|
19
|
+
};
|
|
20
|
+
export function createBillFnService(config) {
|
|
21
|
+
const namespace = config.namespace ?? 'billfn';
|
|
22
|
+
const now = config.now ?? (() => new Date());
|
|
23
|
+
const generateId = config.generateId ?? defaultIdFactory;
|
|
24
|
+
const resolveBillingAccount = config.billingAccountResolver ?? createDefaultBillingAccountResolver();
|
|
25
|
+
const metrics = createNamespacedEmitter('billfn', config.metrics ?? createMetricsEmitter());
|
|
26
|
+
const deps = {
|
|
27
|
+
db: config.db,
|
|
28
|
+
namespace,
|
|
29
|
+
catalog: config.catalog,
|
|
30
|
+
providers: config.providers ?? {},
|
|
31
|
+
resolveBillingAccount,
|
|
32
|
+
now,
|
|
33
|
+
generateId,
|
|
34
|
+
metrics,
|
|
35
|
+
queue: config.queue
|
|
36
|
+
};
|
|
37
|
+
const subscriptionProvider = {
|
|
38
|
+
getActiveSubscription: async (subject) => {
|
|
39
|
+
const { billingAccount, existed } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
40
|
+
if (!existed) {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
return findActiveSubscription(deps, billingAccount.id);
|
|
44
|
+
},
|
|
45
|
+
getEntitlementSnapshot: async (subject) => {
|
|
46
|
+
const { billingAccount, existed } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
47
|
+
if (!existed) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return findEntitlementSnapshot(deps, billingAccount.id);
|
|
51
|
+
},
|
|
52
|
+
isActive: async (subject) => {
|
|
53
|
+
const snapshot = await subscriptionProvider.getEntitlementSnapshot(subject);
|
|
54
|
+
return snapshot?.status === 'active' || snapshot?.status === 'trialing' || snapshot?.status === 'grace';
|
|
55
|
+
},
|
|
56
|
+
hasFeature: async (subject, feature) => {
|
|
57
|
+
const snapshot = await subscriptionProvider.getEntitlementSnapshot(subject);
|
|
58
|
+
return Boolean(snapshot?.features[feature]);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const quotaProvider = {
|
|
62
|
+
checkQuota: async (input) => {
|
|
63
|
+
assertNonNegativeFiniteAmount(input.requestedBytes, 'requestedBytes');
|
|
64
|
+
const subject = {
|
|
65
|
+
principalId: input.principalId,
|
|
66
|
+
tenantId: input.tenantId
|
|
67
|
+
};
|
|
68
|
+
const resource = input.resource ?? 'storage';
|
|
69
|
+
const entitlements = await subscriptionProvider.getEntitlementSnapshot(subject);
|
|
70
|
+
if (!entitlements || entitlements.status === 'inactive') {
|
|
71
|
+
return {
|
|
72
|
+
allowed: false,
|
|
73
|
+
current: 0,
|
|
74
|
+
limit: 0,
|
|
75
|
+
reason: 'subscription_inactive'
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const usage = await quotaProvider.getUsage(input.principalId, input.tenantId, resource);
|
|
79
|
+
const limit = usage.limit;
|
|
80
|
+
if (limit >= 0 && usage.current + input.requestedBytes > limit) {
|
|
81
|
+
return {
|
|
82
|
+
allowed: false,
|
|
83
|
+
current: usage.current,
|
|
84
|
+
limit,
|
|
85
|
+
reason: 'quota_exceeded'
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
allowed: true,
|
|
90
|
+
current: usage.current,
|
|
91
|
+
limit
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
recordUsage: async (input) => {
|
|
95
|
+
const subject = {
|
|
96
|
+
principalId: input.principalId,
|
|
97
|
+
tenantId: input.tenantId
|
|
98
|
+
};
|
|
99
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
100
|
+
await incrementUsage(deps, billingAccount.id, input.resource ?? 'storage', input.bytes);
|
|
101
|
+
},
|
|
102
|
+
getUsage: async (principalId, tenantId, resource = 'storage') => {
|
|
103
|
+
const subject = {
|
|
104
|
+
principalId,
|
|
105
|
+
tenantId
|
|
106
|
+
};
|
|
107
|
+
const { billingAccount, existed } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
108
|
+
const meter = existed ? await findUsageMeter(deps, billingAccount.id, resource) : null;
|
|
109
|
+
const entitlements = existed ? await findEntitlementSnapshot(deps, billingAccount.id) : null;
|
|
110
|
+
return {
|
|
111
|
+
current: meter?.current ?? 0,
|
|
112
|
+
limit: entitlements?.limits[resource] ?? 0
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
async function syncSubscriptionById(subscriptionId) {
|
|
117
|
+
const subscription = await getSubscriptionById(deps, subscriptionId);
|
|
118
|
+
if (!subscription) {
|
|
119
|
+
throw createBillFnError({
|
|
120
|
+
code: 'BILLFN_NOT_FOUND',
|
|
121
|
+
message: 'Subscription not found'
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const billingAccount = await getBillingAccountById(deps, subscription.billingAccountId);
|
|
125
|
+
if (!billingAccount) {
|
|
126
|
+
throw createBillFnError({
|
|
127
|
+
code: 'BILLFN_NOT_FOUND',
|
|
128
|
+
message: 'Billing account not found'
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
132
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
133
|
+
const provider = requireProvider(deps, subscription.provider, 'fetchSubscription');
|
|
134
|
+
const verification = await provider.fetchSubscription({
|
|
135
|
+
subscription,
|
|
136
|
+
plan,
|
|
137
|
+
price
|
|
138
|
+
});
|
|
139
|
+
if (!verification) {
|
|
140
|
+
throw createBillFnError({
|
|
141
|
+
code: 'BILLFN_NOT_FOUND',
|
|
142
|
+
message: 'Provider did not return subscription state'
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return applyVerificationState(deps, {
|
|
146
|
+
billingAccount,
|
|
147
|
+
plan,
|
|
148
|
+
price,
|
|
149
|
+
subscription,
|
|
150
|
+
state: verification
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
async function createReconciliationJobRecord(input) {
|
|
154
|
+
const timestamp = toIsoString(deps.now());
|
|
155
|
+
const job = {
|
|
156
|
+
id: deps.generateId('rcj'),
|
|
157
|
+
kind: input.kind,
|
|
158
|
+
status: 'pending',
|
|
159
|
+
provider: input.provider,
|
|
160
|
+
billingAccountId: input.billingAccountId,
|
|
161
|
+
subscriptionId: input.subscriptionId,
|
|
162
|
+
providerEventId: input.providerEventId,
|
|
163
|
+
cursor: input.cursor,
|
|
164
|
+
attempts: 0,
|
|
165
|
+
payload: input.payload,
|
|
166
|
+
createdAt: timestamp,
|
|
167
|
+
updatedAt: timestamp
|
|
168
|
+
};
|
|
169
|
+
await deps.db.create({
|
|
170
|
+
model: TABLES.reconciliationJobs,
|
|
171
|
+
data: job,
|
|
172
|
+
namespace: deps.namespace
|
|
173
|
+
});
|
|
174
|
+
return job;
|
|
175
|
+
}
|
|
176
|
+
async function enqueueReconciliationJobInternal(input) {
|
|
177
|
+
const job = await createReconciliationJobRecord(input);
|
|
178
|
+
const queuedJob = jobToQueuePayload(job);
|
|
179
|
+
if (deps.queue) {
|
|
180
|
+
await deps.queue.enqueue('billfn-reconciliation', queuedJob);
|
|
181
|
+
}
|
|
182
|
+
await recordBillingEvent(deps, {
|
|
183
|
+
id: deps.generateId('evt'),
|
|
184
|
+
billingAccountId: input.billingAccountId ?? 'ops',
|
|
185
|
+
type: `billfn.reconciliation.${job.kind}.queued`,
|
|
186
|
+
payload: {
|
|
187
|
+
jobId: job.id,
|
|
188
|
+
provider: job.provider,
|
|
189
|
+
subscriptionId: job.subscriptionId,
|
|
190
|
+
providerEventId: job.providerEventId
|
|
191
|
+
},
|
|
192
|
+
createdAt: toIsoString(deps.now())
|
|
193
|
+
});
|
|
194
|
+
return job;
|
|
195
|
+
}
|
|
196
|
+
async function runReconciliationJobInternal(jobId) {
|
|
197
|
+
let job = await getReconciliationJobRecord(deps, jobId);
|
|
198
|
+
if (!job) {
|
|
199
|
+
throw createBillFnError({
|
|
200
|
+
code: 'BILLFN_NOT_FOUND',
|
|
201
|
+
message: 'Reconciliation job not found'
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
if (job.status === 'succeeded') {
|
|
205
|
+
return job;
|
|
206
|
+
}
|
|
207
|
+
const runningAt = toIsoString(deps.now());
|
|
208
|
+
job = await deps.db.update({
|
|
209
|
+
model: TABLES.reconciliationJobs,
|
|
210
|
+
where: [{ field: 'id', operator: 'eq', value: job.id }],
|
|
211
|
+
data: {
|
|
212
|
+
status: 'running',
|
|
213
|
+
attempts: job.attempts + 1,
|
|
214
|
+
error: undefined,
|
|
215
|
+
updatedAt: runningAt
|
|
216
|
+
},
|
|
217
|
+
namespace: deps.namespace
|
|
218
|
+
});
|
|
219
|
+
try {
|
|
220
|
+
await processReconciliationJob(deps, job);
|
|
221
|
+
job = await deps.db.update({
|
|
222
|
+
model: TABLES.reconciliationJobs,
|
|
223
|
+
where: [{ field: 'id', operator: 'eq', value: job.id }],
|
|
224
|
+
data: {
|
|
225
|
+
status: 'succeeded',
|
|
226
|
+
completedAt: toIsoString(deps.now()),
|
|
227
|
+
updatedAt: toIsoString(deps.now())
|
|
228
|
+
},
|
|
229
|
+
namespace: deps.namespace
|
|
230
|
+
});
|
|
231
|
+
return job;
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
job = await deps.db.update({
|
|
235
|
+
model: TABLES.reconciliationJobs,
|
|
236
|
+
where: [{ field: 'id', operator: 'eq', value: job.id }],
|
|
237
|
+
data: {
|
|
238
|
+
status: 'failed',
|
|
239
|
+
error: error instanceof Error ? error.message : String(error),
|
|
240
|
+
updatedAt: toIsoString(deps.now())
|
|
241
|
+
},
|
|
242
|
+
namespace: deps.namespace
|
|
243
|
+
});
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
namespace,
|
|
249
|
+
async getCatalog() {
|
|
250
|
+
return deps.catalog;
|
|
251
|
+
},
|
|
252
|
+
async createCheckout(input) {
|
|
253
|
+
const subject = requireSubject(input.subject);
|
|
254
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
255
|
+
const plan = requirePlan(deps.catalog, input.planKey);
|
|
256
|
+
const price = requirePrice(plan, input.provider, input.interval);
|
|
257
|
+
const provider = requireProvider(deps, input.provider, 'createCheckout');
|
|
258
|
+
const checkoutSessionId = deps.generateId('chk');
|
|
259
|
+
const timestamp = toIsoString(deps.now());
|
|
260
|
+
const created = await createCheckoutSessionRecord(deps, {
|
|
261
|
+
checkoutSessionId,
|
|
262
|
+
billingAccountId: billingAccount.id,
|
|
263
|
+
planKey: plan.planKey,
|
|
264
|
+
priceId: price.priceId,
|
|
265
|
+
provider: price.provider,
|
|
266
|
+
status: 'pending',
|
|
267
|
+
metadata: input.metadata,
|
|
268
|
+
createdAt: timestamp,
|
|
269
|
+
updatedAt: timestamp
|
|
270
|
+
});
|
|
271
|
+
const providerResult = await provider.createCheckout({
|
|
272
|
+
checkoutSessionId,
|
|
273
|
+
billingAccount,
|
|
274
|
+
plan,
|
|
275
|
+
price,
|
|
276
|
+
metadata: input.metadata,
|
|
277
|
+
customer: input.customer,
|
|
278
|
+
returnUrl: input.returnUrl,
|
|
279
|
+
successUrl: input.successUrl,
|
|
280
|
+
cancelUrl: input.cancelUrl
|
|
281
|
+
});
|
|
282
|
+
const checkoutSession = await updateCheckoutSession(deps, checkoutSessionId, {
|
|
283
|
+
providerCheckoutId: providerResult.providerCheckoutId,
|
|
284
|
+
providerSubscriptionId: providerResult.providerSubscriptionId,
|
|
285
|
+
providerChargeId: providerResult.providerChargeId,
|
|
286
|
+
status: providerResult.status,
|
|
287
|
+
checkoutUrl: providerResult.checkoutUrl,
|
|
288
|
+
clientAction: providerResult.clientAction,
|
|
289
|
+
metadata: mergeJson(created.metadata, providerResult.raw),
|
|
290
|
+
updatedAt: timestamp
|
|
291
|
+
});
|
|
292
|
+
deps.metrics.track('checkout.created', {
|
|
293
|
+
provider: input.provider,
|
|
294
|
+
planKey: input.planKey
|
|
295
|
+
});
|
|
296
|
+
const response = {
|
|
297
|
+
checkoutSession,
|
|
298
|
+
billingAccount,
|
|
299
|
+
plan: {
|
|
300
|
+
planKey: plan.planKey,
|
|
301
|
+
productKey: plan.productKey,
|
|
302
|
+
displayName: plan.displayName
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
return ok(response);
|
|
306
|
+
},
|
|
307
|
+
async verifyCheckout(input) {
|
|
308
|
+
const checkoutSession = await getCheckoutSession(deps, input.checkoutSessionId);
|
|
309
|
+
if (!checkoutSession) {
|
|
310
|
+
throw createBillFnError({
|
|
311
|
+
code: 'BILLFN_NOT_FOUND',
|
|
312
|
+
message: 'Checkout session not found'
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
const subject = requireSubject(input.subject);
|
|
316
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
317
|
+
if (billingAccount.id !== checkoutSession.billingAccountId) {
|
|
318
|
+
throw createBillFnError({
|
|
319
|
+
code: 'BILLFN_CONFLICT',
|
|
320
|
+
message: 'Checkout session does not belong to the resolved billing account'
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
const plan = requirePlan(deps.catalog, checkoutSession.planKey);
|
|
324
|
+
const price = requirePriceById(plan, checkoutSession.priceId);
|
|
325
|
+
const provider = requireProvider(deps, checkoutSession.provider, 'verifyCheckout');
|
|
326
|
+
const verification = await provider.verifyCheckout({
|
|
327
|
+
checkoutSession,
|
|
328
|
+
billingAccount,
|
|
329
|
+
plan,
|
|
330
|
+
price,
|
|
331
|
+
payload: input.payload
|
|
332
|
+
});
|
|
333
|
+
const result = await applyVerificationState(deps, {
|
|
334
|
+
billingAccount,
|
|
335
|
+
plan,
|
|
336
|
+
price,
|
|
337
|
+
checkoutSession,
|
|
338
|
+
state: verification
|
|
339
|
+
});
|
|
340
|
+
if (!result.checkoutSession) {
|
|
341
|
+
throw createBillFnError({
|
|
342
|
+
code: 'BILLFN_INTERNAL_ERROR',
|
|
343
|
+
message: 'Checkout verification completed without a checkout session snapshot'
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
return ok({
|
|
347
|
+
checkoutSession: result.checkoutSession,
|
|
348
|
+
subscription: result.subscription,
|
|
349
|
+
entitlements: result.entitlements
|
|
350
|
+
});
|
|
351
|
+
},
|
|
352
|
+
async cancelSubscription(input) {
|
|
353
|
+
const subject = requireSubject(input.subject);
|
|
354
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
355
|
+
const subscription = await getSubscriptionForAccount(deps, billingAccount.id, input.subscriptionId);
|
|
356
|
+
if (!subscription) {
|
|
357
|
+
throw createBillFnError({
|
|
358
|
+
code: 'BILLFN_NOT_FOUND',
|
|
359
|
+
message: 'Subscription not found'
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
363
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
364
|
+
const provider = requireProvider(deps, subscription.provider, 'cancelSubscription');
|
|
365
|
+
const operation = (await provider.cancelSubscription({
|
|
366
|
+
subscription,
|
|
367
|
+
reason: input.reason
|
|
368
|
+
})) ?? {
|
|
369
|
+
operationStatus: 'applied',
|
|
370
|
+
billingState: {
|
|
371
|
+
subscriptionStatus: 'canceled',
|
|
372
|
+
checkoutStatus: 'succeeded',
|
|
373
|
+
providerSubscriptionId: subscription.providerSubscriptionId,
|
|
374
|
+
providerChargeId: subscription.providerChargeId,
|
|
375
|
+
autoRenew: false,
|
|
376
|
+
currentPeriodStart: subscription.currentPeriodStart,
|
|
377
|
+
currentPeriodEnd: subscription.currentPeriodEnd
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
const projection = operation.billingState
|
|
381
|
+
? await applyVerificationState(deps, {
|
|
382
|
+
billingAccount,
|
|
383
|
+
plan,
|
|
384
|
+
price,
|
|
385
|
+
subscription,
|
|
386
|
+
state: operation.billingState
|
|
387
|
+
})
|
|
388
|
+
: {
|
|
389
|
+
subscription,
|
|
390
|
+
entitlements: (await findEntitlementSnapshot(deps, billingAccount.id)) ?? await upsertEntitlements(deps, billingAccount.id, plan, subscription, toIsoString(deps.now()))
|
|
391
|
+
};
|
|
392
|
+
await recordBillingEvent(deps, {
|
|
393
|
+
id: deps.generateId('evt'),
|
|
394
|
+
billingAccountId: billingAccount.id,
|
|
395
|
+
type: 'billfn.subscription.cancel.requested',
|
|
396
|
+
payload: {
|
|
397
|
+
subscriptionId: subscription.id,
|
|
398
|
+
operationStatus: operation.operationStatus,
|
|
399
|
+
reason: input.reason
|
|
400
|
+
},
|
|
401
|
+
createdAt: toIsoString(deps.now())
|
|
402
|
+
});
|
|
403
|
+
return ok({
|
|
404
|
+
subscription: projection.subscription,
|
|
405
|
+
entitlements: projection.entitlements,
|
|
406
|
+
operationStatus: operation.operationStatus,
|
|
407
|
+
clientAction: operation.clientAction
|
|
408
|
+
});
|
|
409
|
+
},
|
|
410
|
+
async changeSubscription(input) {
|
|
411
|
+
const subject = requireSubject(input.subject);
|
|
412
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
413
|
+
const subscription = await getSubscriptionForAccount(deps, billingAccount.id, input.subscriptionId);
|
|
414
|
+
if (!subscription) {
|
|
415
|
+
throw createBillFnError({
|
|
416
|
+
code: 'BILLFN_NOT_FOUND',
|
|
417
|
+
message: 'Subscription not found'
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
const currentPlan = requirePlan(deps.catalog, subscription.planKey);
|
|
421
|
+
const currentPrice = requirePriceById(currentPlan, subscription.priceId);
|
|
422
|
+
const target = requirePriceReference(deps.catalog, input.targetPriceId);
|
|
423
|
+
const provider = requireProvider(deps, subscription.provider, 'changeSubscription');
|
|
424
|
+
const effectiveAt = input.effectiveAt ?? 'immediate';
|
|
425
|
+
const prorationBehavior = input.prorationBehavior ?? 'provider_default';
|
|
426
|
+
const operation = await provider.changeSubscription({
|
|
427
|
+
subscription,
|
|
428
|
+
currentPlan,
|
|
429
|
+
currentPrice,
|
|
430
|
+
targetPlan: target.plan,
|
|
431
|
+
targetPrice: target.price,
|
|
432
|
+
effectiveAt,
|
|
433
|
+
prorationBehavior,
|
|
434
|
+
reason: input.reason
|
|
435
|
+
});
|
|
436
|
+
const timestamp = toIsoString(deps.now());
|
|
437
|
+
const changeRequest = await createSubscriptionChangeRequestRecord(deps, {
|
|
438
|
+
billingAccountId: billingAccount.id,
|
|
439
|
+
subscriptionId: subscription.id,
|
|
440
|
+
provider: subscription.provider,
|
|
441
|
+
currentPriceId: subscription.priceId,
|
|
442
|
+
targetPriceId: target.price.priceId,
|
|
443
|
+
effectiveAt,
|
|
444
|
+
prorationBehavior,
|
|
445
|
+
status: operation.operationStatus === 'applied' ? 'applied' : 'requires_action',
|
|
446
|
+
operationStatus: operation.operationStatus,
|
|
447
|
+
clientAction: operation.clientAction,
|
|
448
|
+
metadata: operation.raw,
|
|
449
|
+
createdAt: timestamp,
|
|
450
|
+
updatedAt: timestamp
|
|
451
|
+
});
|
|
452
|
+
const projection = operation.billingState
|
|
453
|
+
? await applyVerificationState(deps, {
|
|
454
|
+
billingAccount,
|
|
455
|
+
plan: operation.operationStatus === 'applied' ? target.plan : currentPlan,
|
|
456
|
+
price: operation.operationStatus === 'applied' ? target.price : currentPrice,
|
|
457
|
+
subscription,
|
|
458
|
+
state: operation.billingState
|
|
459
|
+
})
|
|
460
|
+
: {
|
|
461
|
+
subscription,
|
|
462
|
+
entitlements: (await findEntitlementSnapshot(deps, billingAccount.id)) ?? await upsertEntitlements(deps, billingAccount.id, currentPlan, subscription, timestamp)
|
|
463
|
+
};
|
|
464
|
+
await recordBillingEvent(deps, {
|
|
465
|
+
id: deps.generateId('evt'),
|
|
466
|
+
billingAccountId: billingAccount.id,
|
|
467
|
+
type: 'billfn.subscription.change.requested',
|
|
468
|
+
payload: {
|
|
469
|
+
subscriptionId: subscription.id,
|
|
470
|
+
currentPriceId: currentPrice.priceId,
|
|
471
|
+
targetPriceId: target.price.priceId,
|
|
472
|
+
operationStatus: operation.operationStatus
|
|
473
|
+
},
|
|
474
|
+
createdAt: timestamp
|
|
475
|
+
});
|
|
476
|
+
return ok({
|
|
477
|
+
subscription: projection.subscription,
|
|
478
|
+
entitlements: projection.entitlements,
|
|
479
|
+
operationStatus: operation.operationStatus,
|
|
480
|
+
clientAction: operation.clientAction,
|
|
481
|
+
changeRequest
|
|
482
|
+
});
|
|
483
|
+
},
|
|
484
|
+
async resumeSubscription(input) {
|
|
485
|
+
const subject = requireSubject(input.subject);
|
|
486
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
487
|
+
const subscription = await getSubscriptionForAccount(deps, billingAccount.id, input.subscriptionId);
|
|
488
|
+
if (!subscription) {
|
|
489
|
+
throw createBillFnError({
|
|
490
|
+
code: 'BILLFN_NOT_FOUND',
|
|
491
|
+
message: 'Subscription not found'
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
495
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
496
|
+
const provider = requireProvider(deps, subscription.provider, 'resumeSubscription');
|
|
497
|
+
const operation = await provider.resumeSubscription({
|
|
498
|
+
subscription
|
|
499
|
+
});
|
|
500
|
+
const projection = operation.billingState
|
|
501
|
+
? await applyVerificationState(deps, {
|
|
502
|
+
billingAccount,
|
|
503
|
+
plan,
|
|
504
|
+
price,
|
|
505
|
+
subscription,
|
|
506
|
+
state: operation.billingState
|
|
507
|
+
})
|
|
508
|
+
: {
|
|
509
|
+
subscription,
|
|
510
|
+
entitlements: (await findEntitlementSnapshot(deps, billingAccount.id)) ?? await upsertEntitlements(deps, billingAccount.id, plan, subscription, toIsoString(deps.now()))
|
|
511
|
+
};
|
|
512
|
+
await recordBillingEvent(deps, {
|
|
513
|
+
id: deps.generateId('evt'),
|
|
514
|
+
billingAccountId: billingAccount.id,
|
|
515
|
+
type: 'billfn.subscription.resume.requested',
|
|
516
|
+
payload: {
|
|
517
|
+
subscriptionId: subscription.id,
|
|
518
|
+
operationStatus: operation.operationStatus
|
|
519
|
+
},
|
|
520
|
+
createdAt: toIsoString(deps.now())
|
|
521
|
+
});
|
|
522
|
+
return ok({
|
|
523
|
+
subscription: projection.subscription,
|
|
524
|
+
entitlements: projection.entitlements,
|
|
525
|
+
operationStatus: operation.operationStatus,
|
|
526
|
+
clientAction: operation.clientAction
|
|
527
|
+
});
|
|
528
|
+
},
|
|
529
|
+
async refundCharge(input) {
|
|
530
|
+
const subject = requireSubject(input.subject);
|
|
531
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
532
|
+
const subscription = input.subscriptionId
|
|
533
|
+
? await getSubscriptionForAccount(deps, billingAccount.id, input.subscriptionId)
|
|
534
|
+
: await findActiveSubscription(deps, billingAccount.id);
|
|
535
|
+
const providerName = subscription?.provider;
|
|
536
|
+
if (!providerName) {
|
|
537
|
+
throw createBillFnError({
|
|
538
|
+
code: 'BILLFN_NOT_FOUND',
|
|
539
|
+
message: 'Subscription not found for refund'
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
const provider = requireProvider(deps, providerName, 'refundCharge');
|
|
543
|
+
const mode = input.mode ?? 'full';
|
|
544
|
+
const providerChargeId = input.providerChargeId ?? subscription?.providerChargeId;
|
|
545
|
+
const operation = await provider.refundCharge({
|
|
546
|
+
subscription: subscription ?? undefined,
|
|
547
|
+
billingAccount,
|
|
548
|
+
providerChargeId,
|
|
549
|
+
mode,
|
|
550
|
+
amount: input.amount,
|
|
551
|
+
reason: input.reason
|
|
552
|
+
});
|
|
553
|
+
const timestamp = toIsoString(deps.now());
|
|
554
|
+
const refund = await createRefundRecord(deps, {
|
|
555
|
+
billingAccountId: billingAccount.id,
|
|
556
|
+
subscriptionId: subscription?.id,
|
|
557
|
+
provider: providerName,
|
|
558
|
+
providerChargeId,
|
|
559
|
+
providerRefundId: operation.providerRefundId,
|
|
560
|
+
mode,
|
|
561
|
+
amount: input.amount,
|
|
562
|
+
currency: subscription ? requirePriceById(requirePlan(deps.catalog, subscription.planKey), subscription.priceId).currency : undefined,
|
|
563
|
+
reason: input.reason,
|
|
564
|
+
status: operation.operationStatus === 'applied' ? 'succeeded' : 'requires_action',
|
|
565
|
+
operationStatus: operation.operationStatus,
|
|
566
|
+
metadata: operation.raw,
|
|
567
|
+
createdAt: timestamp,
|
|
568
|
+
updatedAt: timestamp
|
|
569
|
+
});
|
|
570
|
+
let projectedSubscription = subscription ?? null;
|
|
571
|
+
let projectedEntitlements = subscription ? await findEntitlementSnapshot(deps, billingAccount.id) : null;
|
|
572
|
+
if (subscription && operation.billingState) {
|
|
573
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
574
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
575
|
+
const projection = await applyVerificationState(deps, {
|
|
576
|
+
billingAccount,
|
|
577
|
+
plan,
|
|
578
|
+
price,
|
|
579
|
+
subscription,
|
|
580
|
+
state: operation.billingState
|
|
581
|
+
});
|
|
582
|
+
projectedSubscription = projection.subscription;
|
|
583
|
+
projectedEntitlements = projection.entitlements;
|
|
584
|
+
}
|
|
585
|
+
await recordBillingEvent(deps, {
|
|
586
|
+
id: deps.generateId('evt'),
|
|
587
|
+
billingAccountId: billingAccount.id,
|
|
588
|
+
type: 'billfn.refund.requested',
|
|
589
|
+
payload: {
|
|
590
|
+
refundId: refund.id,
|
|
591
|
+
subscriptionId: subscription?.id,
|
|
592
|
+
operationStatus: operation.operationStatus,
|
|
593
|
+
mode
|
|
594
|
+
},
|
|
595
|
+
createdAt: timestamp
|
|
596
|
+
});
|
|
597
|
+
return ok({
|
|
598
|
+
refund,
|
|
599
|
+
subscription: projectedSubscription,
|
|
600
|
+
entitlements: projectedEntitlements,
|
|
601
|
+
operationStatus: operation.operationStatus,
|
|
602
|
+
clientAction: operation.clientAction
|
|
603
|
+
});
|
|
604
|
+
},
|
|
605
|
+
async syncSubscription(input) {
|
|
606
|
+
const subject = requireSubject(input.subject);
|
|
607
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
608
|
+
const subscription = await getSubscriptionForAccount(deps, billingAccount.id, input.subscriptionId);
|
|
609
|
+
if (!subscription) {
|
|
610
|
+
throw createBillFnError({
|
|
611
|
+
code: 'BILLFN_NOT_FOUND',
|
|
612
|
+
message: 'Subscription not found'
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
const applied = await syncSubscriptionById(subscription.id);
|
|
616
|
+
const response = {
|
|
617
|
+
subscription: applied.subscription,
|
|
618
|
+
entitlements: applied.entitlements
|
|
619
|
+
};
|
|
620
|
+
return ok(response);
|
|
621
|
+
},
|
|
622
|
+
async restorePurchases(input) {
|
|
623
|
+
const subject = requireSubject(input.subject);
|
|
624
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, subject);
|
|
625
|
+
const plan = requirePlan(deps.catalog, input.planKey);
|
|
626
|
+
const price = requirePrice(plan, input.provider, undefined);
|
|
627
|
+
const provider = requireProvider(deps, input.provider, 'restorePurchases');
|
|
628
|
+
const states = await provider.restorePurchases({
|
|
629
|
+
billingAccount,
|
|
630
|
+
plan,
|
|
631
|
+
price,
|
|
632
|
+
purchaseReference: input.purchaseReference,
|
|
633
|
+
payload: input.payload
|
|
634
|
+
});
|
|
635
|
+
if (states.length === 0) {
|
|
636
|
+
throw createBillFnError({
|
|
637
|
+
code: 'BILLFN_NOT_FOUND',
|
|
638
|
+
message: 'No purchases were restored'
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
for (const state of states) {
|
|
642
|
+
const projection = await resolveProjectionContextForProviderState(deps, {
|
|
643
|
+
provider: input.provider,
|
|
644
|
+
state,
|
|
645
|
+
checkoutReferenceId: input.purchaseReference
|
|
646
|
+
});
|
|
647
|
+
if (!projection) {
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
if (projection.billingAccount.id !== billingAccount.id) {
|
|
651
|
+
throw createBillFnError({
|
|
652
|
+
code: 'BILLFN_CONFLICT',
|
|
653
|
+
message: 'Restored purchase is linked to a different billing account'
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
const applied = await applyVerificationState(deps, {
|
|
657
|
+
billingAccount: projection.billingAccount,
|
|
658
|
+
plan: projection.plan,
|
|
659
|
+
price: projection.price,
|
|
660
|
+
checkoutSession: projection.checkoutSession ?? undefined,
|
|
661
|
+
subscription: projection.subscription ?? undefined,
|
|
662
|
+
state
|
|
663
|
+
});
|
|
664
|
+
const response = {
|
|
665
|
+
subscription: applied.subscription,
|
|
666
|
+
entitlements: applied.entitlements
|
|
667
|
+
};
|
|
668
|
+
return ok(response);
|
|
669
|
+
}
|
|
670
|
+
throw createBillFnError({
|
|
671
|
+
code: 'BILLFN_CONFLICT',
|
|
672
|
+
message: 'No restored purchase could be linked to the resolved billing account'
|
|
673
|
+
});
|
|
674
|
+
},
|
|
675
|
+
async getEntitlements(subject) {
|
|
676
|
+
const { billingAccount, existed } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
677
|
+
if (!existed) {
|
|
678
|
+
return ok({
|
|
679
|
+
billingAccount,
|
|
680
|
+
entitlements: null,
|
|
681
|
+
subscription: null
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
const entitlements = await findEntitlementSnapshot(deps, billingAccount.id);
|
|
685
|
+
const subscription = await findActiveSubscription(deps, billingAccount.id);
|
|
686
|
+
const response = {
|
|
687
|
+
billingAccount,
|
|
688
|
+
entitlements,
|
|
689
|
+
subscription
|
|
690
|
+
};
|
|
691
|
+
return ok(response);
|
|
692
|
+
},
|
|
693
|
+
async getUsage(subject, resource) {
|
|
694
|
+
const { billingAccount } = await getOrCreateBillingAccount(deps, requireSubject(subject));
|
|
695
|
+
const entitlements = await findEntitlementSnapshot(deps, billingAccount.id);
|
|
696
|
+
const meters = resource
|
|
697
|
+
? await findUsageMeters(deps, billingAccount.id, resource)
|
|
698
|
+
: await deps.db.findMany({
|
|
699
|
+
model: TABLES.usageMeters,
|
|
700
|
+
where: [{ field: 'billingAccountId', operator: 'eq', value: billingAccount.id }],
|
|
701
|
+
namespace: deps.namespace
|
|
702
|
+
});
|
|
703
|
+
const usage = meters.map((meter) => ({
|
|
704
|
+
resource: meter.resource,
|
|
705
|
+
current: meter.current,
|
|
706
|
+
limit: entitlements?.limits[meter.resource] ?? 0
|
|
707
|
+
}));
|
|
708
|
+
const response = {
|
|
709
|
+
billingAccount,
|
|
710
|
+
usage
|
|
711
|
+
};
|
|
712
|
+
return ok(response);
|
|
713
|
+
},
|
|
714
|
+
async handleWebhook(input) {
|
|
715
|
+
const provider = requireProvider(deps, input.provider, 'parseWebhook');
|
|
716
|
+
const events = await provider.parseWebhook({
|
|
717
|
+
headers: input.headers,
|
|
718
|
+
rawBody: input.rawBody
|
|
719
|
+
});
|
|
720
|
+
let processed = 0;
|
|
721
|
+
for (const event of events) {
|
|
722
|
+
const receiptId = buildWebhookReceiptId(input.provider, event.providerEventId);
|
|
723
|
+
const receipt = {
|
|
724
|
+
id: receiptId,
|
|
725
|
+
provider: input.provider,
|
|
726
|
+
providerEventId: event.providerEventId,
|
|
727
|
+
eventType: event.type,
|
|
728
|
+
signatureVerified: event.signatureVerified,
|
|
729
|
+
rawPayload: {
|
|
730
|
+
raw: event.raw,
|
|
731
|
+
parsed: serializeParsedWebhookEvent(event)
|
|
732
|
+
},
|
|
733
|
+
createdAt: toIsoString(deps.now())
|
|
734
|
+
};
|
|
735
|
+
let created = false;
|
|
736
|
+
try {
|
|
737
|
+
await deps.db.create({
|
|
738
|
+
model: TABLES.webhookReceipts,
|
|
739
|
+
data: receipt,
|
|
740
|
+
namespace: deps.namespace
|
|
741
|
+
});
|
|
742
|
+
created = true;
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
if (!isDuplicateRecordError(error)) {
|
|
746
|
+
throw error;
|
|
747
|
+
}
|
|
748
|
+
const existingReceipt = await deps.db.findOne({
|
|
749
|
+
model: TABLES.webhookReceipts,
|
|
750
|
+
where: [{ field: 'id', operator: 'eq', value: receiptId }],
|
|
751
|
+
namespace: deps.namespace
|
|
752
|
+
});
|
|
753
|
+
if (existingReceipt?.processedAt) {
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
const job = await enqueueReconciliationJobInternal({
|
|
758
|
+
kind: 'webhook-event',
|
|
759
|
+
provider: input.provider,
|
|
760
|
+
providerEventId: event.providerEventId,
|
|
761
|
+
payload: {
|
|
762
|
+
parsedEvent: serializeParsedWebhookEvent(event)
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
if (!deps.queue) {
|
|
766
|
+
await runReconciliationJobInternal(job.id);
|
|
767
|
+
}
|
|
768
|
+
if (created) {
|
|
769
|
+
processed += 1;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
const response = {
|
|
773
|
+
accepted: true,
|
|
774
|
+
processed
|
|
775
|
+
};
|
|
776
|
+
return ok(response);
|
|
777
|
+
},
|
|
778
|
+
async enqueueReconciliationJob(input) {
|
|
779
|
+
const job = await enqueueReconciliationJobInternal(input);
|
|
780
|
+
return ok({ job });
|
|
781
|
+
},
|
|
782
|
+
async getReconciliationJob(input) {
|
|
783
|
+
const job = await getReconciliationJobRecord(deps, input.jobId);
|
|
784
|
+
if (!job) {
|
|
785
|
+
throw createBillFnError({
|
|
786
|
+
code: 'BILLFN_NOT_FOUND',
|
|
787
|
+
message: 'Reconciliation job not found'
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
return ok({ job });
|
|
791
|
+
},
|
|
792
|
+
async runReconciliationJob(input) {
|
|
793
|
+
const job = await runReconciliationJobInternal(input.jobId);
|
|
794
|
+
return ok({ job });
|
|
795
|
+
},
|
|
796
|
+
subscriptionProvider,
|
|
797
|
+
quotaProvider
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
export function createBillFnReconciliationWorker(config) {
|
|
801
|
+
const service = createBillFnService(config);
|
|
802
|
+
const queue = config.queue;
|
|
803
|
+
return {
|
|
804
|
+
async run(job) {
|
|
805
|
+
if (job.jobId) {
|
|
806
|
+
const result = await service.runReconciliationJob({ jobId: job.jobId });
|
|
807
|
+
return result.ok ? result.data.job : null;
|
|
808
|
+
}
|
|
809
|
+
const enqueued = await service.enqueueReconciliationJob({
|
|
810
|
+
kind: job.type,
|
|
811
|
+
provider: 'provider' in job ? job.provider : undefined,
|
|
812
|
+
billingAccountId: 'billingAccountId' in job ? job.billingAccountId : undefined,
|
|
813
|
+
subscriptionId: 'subscriptionId' in job ? job.subscriptionId : undefined,
|
|
814
|
+
providerEventId: 'providerEventId' in job ? job.providerEventId : undefined,
|
|
815
|
+
cursor: 'cursor' in job ? job.cursor : undefined
|
|
816
|
+
});
|
|
817
|
+
if (!enqueued.ok) {
|
|
818
|
+
return null;
|
|
819
|
+
}
|
|
820
|
+
const ran = await service.runReconciliationJob({ jobId: enqueued.data.job.id });
|
|
821
|
+
return ran.ok ? ran.data.job : null;
|
|
822
|
+
},
|
|
823
|
+
async runNext() {
|
|
824
|
+
if (!queue) {
|
|
825
|
+
return null;
|
|
826
|
+
}
|
|
827
|
+
const job = await queue.dequeue('billfn-reconciliation');
|
|
828
|
+
if (!job) {
|
|
829
|
+
return null;
|
|
830
|
+
}
|
|
831
|
+
return this.run(job);
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
async function processReconciliationJob(deps, job) {
|
|
836
|
+
switch (job.kind) {
|
|
837
|
+
case 'webhook-event':
|
|
838
|
+
case 'webhook-replay': {
|
|
839
|
+
if (!job.provider || !job.providerEventId) {
|
|
840
|
+
throw createBillFnError({
|
|
841
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
842
|
+
message: 'Webhook reconciliation requires provider and providerEventId'
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
const receipt = await deps.db.findOne({
|
|
846
|
+
model: TABLES.webhookReceipts,
|
|
847
|
+
where: [
|
|
848
|
+
{ field: 'provider', operator: 'eq', value: job.provider },
|
|
849
|
+
{ field: 'providerEventId', operator: 'eq', value: job.providerEventId }
|
|
850
|
+
],
|
|
851
|
+
namespace: deps.namespace
|
|
852
|
+
});
|
|
853
|
+
if (!receipt) {
|
|
854
|
+
throw createBillFnError({
|
|
855
|
+
code: 'BILLFN_NOT_FOUND',
|
|
856
|
+
message: 'Webhook receipt not found'
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
if (receipt.processedAt && job.kind === 'webhook-event') {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
const parsed = deserializeParsedWebhookEvent(asRecord(receipt.rawPayload)?.parsed);
|
|
863
|
+
if (parsed?.billingState) {
|
|
864
|
+
await processParsedWebhookEvent(deps, job.provider, parsed);
|
|
865
|
+
}
|
|
866
|
+
await deps.db.update({
|
|
867
|
+
model: TABLES.webhookReceipts,
|
|
868
|
+
where: [{ field: 'id', operator: 'eq', value: receipt.id }],
|
|
869
|
+
data: {
|
|
870
|
+
processedAt: toIsoString(deps.now())
|
|
871
|
+
},
|
|
872
|
+
namespace: deps.namespace
|
|
873
|
+
});
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
case 'subscription-sync': {
|
|
877
|
+
if (!job.subscriptionId) {
|
|
878
|
+
throw createBillFnError({
|
|
879
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
880
|
+
message: 'Subscription sync job requires subscriptionId'
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
await syncSubscriptionByIdForJob(deps, job.subscriptionId);
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
case 'account-scan': {
|
|
887
|
+
if (!job.billingAccountId) {
|
|
888
|
+
throw createBillFnError({
|
|
889
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
890
|
+
message: 'Account scan job requires billingAccountId'
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
const where = [{ field: 'billingAccountId', operator: 'eq', value: job.billingAccountId }];
|
|
894
|
+
if (job.provider) {
|
|
895
|
+
where.push({ field: 'provider', operator: 'eq', value: job.provider });
|
|
896
|
+
}
|
|
897
|
+
const subscriptions = await deps.db.findMany({
|
|
898
|
+
model: TABLES.subscriptions,
|
|
899
|
+
where,
|
|
900
|
+
orderBy: [{ field: 'updatedAt', direction: 'desc' }],
|
|
901
|
+
namespace: deps.namespace
|
|
902
|
+
});
|
|
903
|
+
for (const subscription of subscriptions) {
|
|
904
|
+
await syncSubscriptionByIdForJob(deps, subscription.id);
|
|
905
|
+
}
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
case 'notification-history-backfill': {
|
|
909
|
+
if (!job.provider) {
|
|
910
|
+
throw createBillFnError({
|
|
911
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
912
|
+
message: 'Notification history backfill requires provider'
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
const provider = requireProvider(deps, job.provider, 'fetchNotificationHistory');
|
|
916
|
+
const cursorKey = 'default';
|
|
917
|
+
const cursorRecord = await findReconciliationCursor(deps, job.provider, cursorKey);
|
|
918
|
+
const history = await provider.fetchNotificationHistory({
|
|
919
|
+
cursor: job.cursor ?? cursorRecord?.cursor,
|
|
920
|
+
limit: 20
|
|
921
|
+
});
|
|
922
|
+
for (const event of history.events) {
|
|
923
|
+
const receiptId = buildWebhookReceiptId(job.provider, event.providerEventId);
|
|
924
|
+
const receipt = {
|
|
925
|
+
id: receiptId,
|
|
926
|
+
provider: job.provider,
|
|
927
|
+
providerEventId: event.providerEventId,
|
|
928
|
+
eventType: event.type,
|
|
929
|
+
signatureVerified: event.signatureVerified,
|
|
930
|
+
rawPayload: {
|
|
931
|
+
raw: event.raw,
|
|
932
|
+
parsed: serializeParsedWebhookEvent(event)
|
|
933
|
+
},
|
|
934
|
+
createdAt: toIsoString(deps.now()),
|
|
935
|
+
processedAt: undefined
|
|
936
|
+
};
|
|
937
|
+
try {
|
|
938
|
+
await deps.db.create({
|
|
939
|
+
model: TABLES.webhookReceipts,
|
|
940
|
+
data: receipt,
|
|
941
|
+
namespace: deps.namespace
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
catch (error) {
|
|
945
|
+
if (!isDuplicateRecordError(error)) {
|
|
946
|
+
throw error;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
await processParsedWebhookEvent(deps, job.provider, event);
|
|
950
|
+
await deps.db.update({
|
|
951
|
+
model: TABLES.webhookReceipts,
|
|
952
|
+
where: [{ field: 'id', operator: 'eq', value: receiptId }],
|
|
953
|
+
data: {
|
|
954
|
+
processedAt: toIsoString(deps.now())
|
|
955
|
+
},
|
|
956
|
+
namespace: deps.namespace
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
await upsertReconciliationCursor(deps, {
|
|
960
|
+
provider: job.provider,
|
|
961
|
+
cursorKey,
|
|
962
|
+
cursor: history.nextCursor,
|
|
963
|
+
metadata: {
|
|
964
|
+
jobId: job.id
|
|
965
|
+
}
|
|
966
|
+
});
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
async function syncSubscriptionByIdForJob(deps, subscriptionId) {
|
|
972
|
+
const subscription = await getSubscriptionById(deps, subscriptionId);
|
|
973
|
+
if (!subscription) {
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
const billingAccount = await getBillingAccountById(deps, subscription.billingAccountId);
|
|
977
|
+
if (!billingAccount) {
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
981
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
982
|
+
const provider = requireProvider(deps, subscription.provider, 'fetchSubscription');
|
|
983
|
+
const verification = await provider.fetchSubscription({
|
|
984
|
+
subscription,
|
|
985
|
+
plan,
|
|
986
|
+
price
|
|
987
|
+
});
|
|
988
|
+
if (!verification) {
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
await applyVerificationState(deps, {
|
|
992
|
+
billingAccount,
|
|
993
|
+
plan,
|
|
994
|
+
price,
|
|
995
|
+
subscription,
|
|
996
|
+
state: verification
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
async function getOrCreateBillingAccount(deps, subject) {
|
|
1000
|
+
const resolved = await deps.resolveBillingAccount.resolve(subject);
|
|
1001
|
+
if (!resolved) {
|
|
1002
|
+
throw createBillFnError({
|
|
1003
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
1004
|
+
message: 'Unable to resolve a billing account from the provided subject'
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
const existing = await deps.db.findOne({
|
|
1008
|
+
model: TABLES.billingAccounts,
|
|
1009
|
+
where: [{ field: 'id', operator: 'eq', value: resolved.billingAccountId }],
|
|
1010
|
+
namespace: deps.namespace
|
|
1011
|
+
});
|
|
1012
|
+
if (existing) {
|
|
1013
|
+
return {
|
|
1014
|
+
billingAccount: existing,
|
|
1015
|
+
existed: true
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
const timestamp = toIsoString(deps.now());
|
|
1019
|
+
const created = {
|
|
1020
|
+
id: resolved.billingAccountId,
|
|
1021
|
+
ownerType: resolved.ownerType,
|
|
1022
|
+
ownerId: resolved.ownerId,
|
|
1023
|
+
createdAt: timestamp,
|
|
1024
|
+
updatedAt: timestamp
|
|
1025
|
+
};
|
|
1026
|
+
await deps.db.create({
|
|
1027
|
+
model: TABLES.billingAccounts,
|
|
1028
|
+
data: created,
|
|
1029
|
+
namespace: deps.namespace
|
|
1030
|
+
});
|
|
1031
|
+
return {
|
|
1032
|
+
billingAccount: created,
|
|
1033
|
+
existed: false
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
function requirePlan(catalog, planKey) {
|
|
1037
|
+
const plan = resolvePlan(catalog, planKey);
|
|
1038
|
+
if (!plan) {
|
|
1039
|
+
throw createBillFnError({
|
|
1040
|
+
code: 'BILLFN_NOT_FOUND',
|
|
1041
|
+
message: `Plan not found: ${planKey}`
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
return plan;
|
|
1045
|
+
}
|
|
1046
|
+
function requirePrice(plan, provider, interval) {
|
|
1047
|
+
const price = resolvePrice(plan, provider, interval);
|
|
1048
|
+
if (!price) {
|
|
1049
|
+
throw createBillFnError({
|
|
1050
|
+
code: 'BILLFN_CATALOG_PRICE_NOT_FOUND',
|
|
1051
|
+
message: `No configured price for ${plan.planKey} on ${provider}${interval ? ` (${interval})` : ''}`
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
return price;
|
|
1055
|
+
}
|
|
1056
|
+
function requirePriceById(plan, priceId) {
|
|
1057
|
+
const price = plan.prices.find((candidate) => candidate.priceId === priceId);
|
|
1058
|
+
if (!price) {
|
|
1059
|
+
throw createBillFnError({
|
|
1060
|
+
code: 'BILLFN_CATALOG_PRICE_NOT_FOUND',
|
|
1061
|
+
message: `No configured price found for ${priceId}`
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
return price;
|
|
1065
|
+
}
|
|
1066
|
+
function requirePriceReference(catalog, priceId) {
|
|
1067
|
+
for (const plan of catalog.plans) {
|
|
1068
|
+
const price = plan.prices.find((candidate) => candidate.priceId === priceId);
|
|
1069
|
+
if (price) {
|
|
1070
|
+
return { plan, price };
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
throw createBillFnError({
|
|
1074
|
+
code: 'BILLFN_CATALOG_PRICE_NOT_FOUND',
|
|
1075
|
+
message: `No configured price found for ${priceId}`
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
function requireProvider(deps, providerName, capability) {
|
|
1079
|
+
const provider = deps.providers[providerName];
|
|
1080
|
+
if (!provider) {
|
|
1081
|
+
throw createBillFnError({
|
|
1082
|
+
code: 'BILLFN_PROVIDER_UNSUPPORTED',
|
|
1083
|
+
message: `Provider is not configured: ${providerName}`
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
const capabilityValue = provider[capability];
|
|
1087
|
+
if (typeof capabilityValue !== 'function') {
|
|
1088
|
+
throw createBillFnError({
|
|
1089
|
+
code: 'BILLFN_PROVIDER_UNSUPPORTED',
|
|
1090
|
+
message: `Provider does not support ${String(capability)}: ${providerName}`
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
return provider;
|
|
1094
|
+
}
|
|
1095
|
+
function requireSubject(subject) {
|
|
1096
|
+
if (!subject) {
|
|
1097
|
+
throw createBillFnError({
|
|
1098
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
1099
|
+
message: 'A billing subject is required'
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
const hasIdentifier = Boolean(subject.actorId || subject.principalId || subject.organizationId || subject.tenantId);
|
|
1103
|
+
if (!hasIdentifier) {
|
|
1104
|
+
throw createBillFnError({
|
|
1105
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
1106
|
+
message: 'A billing subject must include an actor, principal, tenant, or organization identifier'
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
return subject;
|
|
1110
|
+
}
|
|
1111
|
+
async function createCheckoutSessionRecord(deps, session) {
|
|
1112
|
+
await deps.db.create({
|
|
1113
|
+
model: TABLES.checkoutSessions,
|
|
1114
|
+
data: session,
|
|
1115
|
+
namespace: deps.namespace
|
|
1116
|
+
});
|
|
1117
|
+
return session;
|
|
1118
|
+
}
|
|
1119
|
+
async function updateCheckoutSession(deps, checkoutSessionId, patch) {
|
|
1120
|
+
return deps.db.update({
|
|
1121
|
+
model: TABLES.checkoutSessions,
|
|
1122
|
+
where: [{ field: 'checkoutSessionId', operator: 'eq', value: checkoutSessionId }],
|
|
1123
|
+
data: patch,
|
|
1124
|
+
namespace: deps.namespace
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
async function getCheckoutSession(deps, checkoutSessionId) {
|
|
1128
|
+
return deps.db.findOne({
|
|
1129
|
+
model: TABLES.checkoutSessions,
|
|
1130
|
+
where: [{ field: 'checkoutSessionId', operator: 'eq', value: checkoutSessionId }],
|
|
1131
|
+
namespace: deps.namespace
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
async function getBillingAccountById(deps, id) {
|
|
1135
|
+
return deps.db.findOne({
|
|
1136
|
+
model: TABLES.billingAccounts,
|
|
1137
|
+
where: [{ field: 'id', operator: 'eq', value: id }],
|
|
1138
|
+
namespace: deps.namespace
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
async function getSubscriptionById(deps, id) {
|
|
1142
|
+
return deps.db.findOne({
|
|
1143
|
+
model: TABLES.subscriptions,
|
|
1144
|
+
where: [{ field: 'id', operator: 'eq', value: id }],
|
|
1145
|
+
namespace: deps.namespace
|
|
1146
|
+
});
|
|
1147
|
+
}
|
|
1148
|
+
async function getSubscriptionForAccount(deps, billingAccountId, subscriptionId) {
|
|
1149
|
+
if (subscriptionId) {
|
|
1150
|
+
return deps.db.findOne({
|
|
1151
|
+
model: TABLES.subscriptions,
|
|
1152
|
+
where: [
|
|
1153
|
+
{ field: 'id', operator: 'eq', value: subscriptionId },
|
|
1154
|
+
{ field: 'billingAccountId', operator: 'eq', value: billingAccountId }
|
|
1155
|
+
],
|
|
1156
|
+
namespace: deps.namespace
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
return findActiveSubscription(deps, billingAccountId);
|
|
1160
|
+
}
|
|
1161
|
+
async function findActiveSubscription(deps, billingAccountId) {
|
|
1162
|
+
const candidates = await deps.db.findMany({
|
|
1163
|
+
model: TABLES.subscriptions,
|
|
1164
|
+
where: [
|
|
1165
|
+
{ field: 'billingAccountId', operator: 'eq', value: billingAccountId },
|
|
1166
|
+
{ field: 'status', operator: 'in', value: ['trialing', 'active', 'grace', 'past_due', 'pending', 'paused'] }
|
|
1167
|
+
],
|
|
1168
|
+
orderBy: [{ field: 'updatedAt', direction: 'desc' }],
|
|
1169
|
+
namespace: deps.namespace
|
|
1170
|
+
});
|
|
1171
|
+
return candidates[0] ?? null;
|
|
1172
|
+
}
|
|
1173
|
+
async function findSubscriptionByProviderRef(deps, provider, providerSubscriptionId, providerChargeId, checkoutReferenceId) {
|
|
1174
|
+
const whereSets = [];
|
|
1175
|
+
if (providerSubscriptionId) {
|
|
1176
|
+
whereSets.push([
|
|
1177
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1178
|
+
{ field: 'providerSubscriptionId', operator: 'eq', value: providerSubscriptionId }
|
|
1179
|
+
]);
|
|
1180
|
+
}
|
|
1181
|
+
if (providerChargeId) {
|
|
1182
|
+
whereSets.push([
|
|
1183
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1184
|
+
{ field: 'providerChargeId', operator: 'eq', value: providerChargeId }
|
|
1185
|
+
]);
|
|
1186
|
+
}
|
|
1187
|
+
if (checkoutReferenceId) {
|
|
1188
|
+
const session = await deps.db.findOne({
|
|
1189
|
+
model: TABLES.checkoutSessions,
|
|
1190
|
+
where: [{ field: 'checkoutSessionId', operator: 'eq', value: checkoutReferenceId }],
|
|
1191
|
+
namespace: deps.namespace
|
|
1192
|
+
});
|
|
1193
|
+
if (session?.providerSubscriptionId) {
|
|
1194
|
+
whereSets.push([
|
|
1195
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1196
|
+
{ field: 'providerSubscriptionId', operator: 'eq', value: session.providerSubscriptionId }
|
|
1197
|
+
]);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
for (const where of whereSets) {
|
|
1201
|
+
const found = await deps.db.findOne({
|
|
1202
|
+
model: TABLES.subscriptions,
|
|
1203
|
+
where,
|
|
1204
|
+
namespace: deps.namespace
|
|
1205
|
+
});
|
|
1206
|
+
if (found) {
|
|
1207
|
+
return found;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
return null;
|
|
1211
|
+
}
|
|
1212
|
+
async function findCheckoutSessionByProviderRef(deps, provider, providerSubscriptionId, providerChargeId, checkoutReferenceId) {
|
|
1213
|
+
const whereSets = [];
|
|
1214
|
+
if (checkoutReferenceId) {
|
|
1215
|
+
whereSets.push([{ field: 'checkoutSessionId', operator: 'eq', value: checkoutReferenceId }]);
|
|
1216
|
+
whereSets.push([
|
|
1217
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1218
|
+
{ field: 'providerCheckoutId', operator: 'eq', value: checkoutReferenceId }
|
|
1219
|
+
]);
|
|
1220
|
+
}
|
|
1221
|
+
if (providerSubscriptionId) {
|
|
1222
|
+
whereSets.push([
|
|
1223
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1224
|
+
{ field: 'providerSubscriptionId', operator: 'eq', value: providerSubscriptionId }
|
|
1225
|
+
]);
|
|
1226
|
+
}
|
|
1227
|
+
if (providerChargeId) {
|
|
1228
|
+
whereSets.push([
|
|
1229
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1230
|
+
{ field: 'providerChargeId', operator: 'eq', value: providerChargeId }
|
|
1231
|
+
]);
|
|
1232
|
+
}
|
|
1233
|
+
for (const where of whereSets) {
|
|
1234
|
+
const found = await deps.db.findOne({
|
|
1235
|
+
model: TABLES.checkoutSessions,
|
|
1236
|
+
where,
|
|
1237
|
+
namespace: deps.namespace
|
|
1238
|
+
});
|
|
1239
|
+
if (found) {
|
|
1240
|
+
return found;
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
return null;
|
|
1244
|
+
}
|
|
1245
|
+
async function findEntitlementSnapshot(deps, billingAccountId) {
|
|
1246
|
+
return deps.db.findOne({
|
|
1247
|
+
model: TABLES.entitlementSnapshots,
|
|
1248
|
+
where: [{ field: 'billingAccountId', operator: 'eq', value: billingAccountId }],
|
|
1249
|
+
namespace: deps.namespace
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
async function findUsageMeter(deps, billingAccountId, resource) {
|
|
1253
|
+
return deps.db.findOne({
|
|
1254
|
+
model: TABLES.usageMeters,
|
|
1255
|
+
where: [
|
|
1256
|
+
{ field: 'billingAccountId', operator: 'eq', value: billingAccountId },
|
|
1257
|
+
{ field: 'resource', operator: 'eq', value: resource }
|
|
1258
|
+
],
|
|
1259
|
+
namespace: deps.namespace
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
async function findUsageMeters(deps, billingAccountId, resource) {
|
|
1263
|
+
return deps.db.findMany({
|
|
1264
|
+
model: TABLES.usageMeters,
|
|
1265
|
+
where: [
|
|
1266
|
+
{ field: 'billingAccountId', operator: 'eq', value: billingAccountId },
|
|
1267
|
+
{ field: 'resource', operator: 'eq', value: resource }
|
|
1268
|
+
],
|
|
1269
|
+
namespace: deps.namespace
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
async function getReconciliationJobRecord(deps, id) {
|
|
1273
|
+
return deps.db.findOne({
|
|
1274
|
+
model: TABLES.reconciliationJobs,
|
|
1275
|
+
where: [{ field: 'id', operator: 'eq', value: id }],
|
|
1276
|
+
namespace: deps.namespace
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
async function findReconciliationCursor(deps, provider, cursorKey) {
|
|
1280
|
+
return deps.db.findOne({
|
|
1281
|
+
model: TABLES.reconciliationCursors,
|
|
1282
|
+
where: [
|
|
1283
|
+
{ field: 'provider', operator: 'eq', value: provider },
|
|
1284
|
+
{ field: 'cursorKey', operator: 'eq', value: cursorKey }
|
|
1285
|
+
],
|
|
1286
|
+
namespace: deps.namespace
|
|
1287
|
+
});
|
|
1288
|
+
}
|
|
1289
|
+
async function upsertReconciliationCursor(deps, input) {
|
|
1290
|
+
const existing = await findReconciliationCursor(deps, input.provider, input.cursorKey);
|
|
1291
|
+
const record = {
|
|
1292
|
+
id: existing?.id ?? input.id ?? deps.generateId('rcc'),
|
|
1293
|
+
provider: input.provider,
|
|
1294
|
+
cursorKey: input.cursorKey,
|
|
1295
|
+
cursor: input.cursor,
|
|
1296
|
+
metadata: input.metadata,
|
|
1297
|
+
updatedAt: input.updatedAt ?? toIsoString(deps.now())
|
|
1298
|
+
};
|
|
1299
|
+
if (existing) {
|
|
1300
|
+
return deps.db.update({
|
|
1301
|
+
model: TABLES.reconciliationCursors,
|
|
1302
|
+
where: [{ field: 'id', operator: 'eq', value: existing.id }],
|
|
1303
|
+
data: record,
|
|
1304
|
+
namespace: deps.namespace
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
return deps.db.create({
|
|
1308
|
+
model: TABLES.reconciliationCursors,
|
|
1309
|
+
data: record,
|
|
1310
|
+
namespace: deps.namespace
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
function mapSubscriptionToEntitlementStatus(status) {
|
|
1314
|
+
switch (status) {
|
|
1315
|
+
case 'trialing':
|
|
1316
|
+
return 'trialing';
|
|
1317
|
+
case 'active':
|
|
1318
|
+
return 'active';
|
|
1319
|
+
case 'grace':
|
|
1320
|
+
case 'past_due':
|
|
1321
|
+
return 'grace';
|
|
1322
|
+
default:
|
|
1323
|
+
return 'inactive';
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
async function applyVerificationState(deps, input) {
|
|
1327
|
+
const timestamp = toIsoString(deps.now());
|
|
1328
|
+
const checkoutSession = input.checkoutSession
|
|
1329
|
+
? await updateCheckoutSession(deps, input.checkoutSession.checkoutSessionId, {
|
|
1330
|
+
status: input.state.checkoutStatus,
|
|
1331
|
+
providerSubscriptionId: input.state.providerSubscriptionId ?? input.checkoutSession.providerSubscriptionId,
|
|
1332
|
+
providerChargeId: input.state.providerChargeId ?? input.checkoutSession.providerChargeId,
|
|
1333
|
+
updatedAt: timestamp,
|
|
1334
|
+
metadata: mergeJson(input.checkoutSession.metadata, input.state.raw)
|
|
1335
|
+
})
|
|
1336
|
+
: input.checkoutSession;
|
|
1337
|
+
const baseSubscription = input.subscription ??
|
|
1338
|
+
(await findSubscriptionByProviderRef(deps, input.price.provider, input.state.providerSubscriptionId, input.state.providerChargeId, checkoutSession?.checkoutSessionId));
|
|
1339
|
+
const subscriptionId = baseSubscription?.id ?? deps.generateId('sub');
|
|
1340
|
+
const record = {
|
|
1341
|
+
id: subscriptionId,
|
|
1342
|
+
billingAccountId: input.billingAccount.id,
|
|
1343
|
+
planKey: input.plan.planKey,
|
|
1344
|
+
priceId: input.price.priceId,
|
|
1345
|
+
provider: input.price.provider,
|
|
1346
|
+
providerSubscriptionId: input.state.providerSubscriptionId ?? baseSubscription?.providerSubscriptionId,
|
|
1347
|
+
providerCheckoutId: checkoutSession?.providerCheckoutId ?? baseSubscription?.providerCheckoutId,
|
|
1348
|
+
providerChargeId: input.state.providerChargeId ?? baseSubscription?.providerChargeId,
|
|
1349
|
+
status: input.state.subscriptionStatus,
|
|
1350
|
+
currentPeriodStart: input.state.currentPeriodStart ?? baseSubscription?.currentPeriodStart,
|
|
1351
|
+
currentPeriodEnd: input.state.currentPeriodEnd ?? baseSubscription?.currentPeriodEnd,
|
|
1352
|
+
autoRenew: input.state.autoRenew ?? baseSubscription?.autoRenew ?? false,
|
|
1353
|
+
metadata: mergeJson(baseSubscription?.metadata, input.state.raw),
|
|
1354
|
+
createdAt: baseSubscription?.createdAt ?? timestamp,
|
|
1355
|
+
updatedAt: timestamp,
|
|
1356
|
+
cancelAt: baseSubscription?.cancelAt,
|
|
1357
|
+
canceledAt: input.state.subscriptionStatus === 'canceled' ? timestamp : baseSubscription?.canceledAt,
|
|
1358
|
+
trialEnd: baseSubscription?.trialEnd
|
|
1359
|
+
};
|
|
1360
|
+
const subscription = baseSubscription
|
|
1361
|
+
? await deps.db.update({
|
|
1362
|
+
model: TABLES.subscriptions,
|
|
1363
|
+
where: [{ field: 'id', operator: 'eq', value: baseSubscription.id }],
|
|
1364
|
+
data: record,
|
|
1365
|
+
namespace: deps.namespace
|
|
1366
|
+
})
|
|
1367
|
+
: await deps.db.create({
|
|
1368
|
+
model: TABLES.subscriptions,
|
|
1369
|
+
data: record,
|
|
1370
|
+
namespace: deps.namespace
|
|
1371
|
+
});
|
|
1372
|
+
const entitlements = await upsertEntitlements(deps, input.billingAccount.id, input.plan, subscription, timestamp);
|
|
1373
|
+
await recordBillingEvent(deps, {
|
|
1374
|
+
id: deps.generateId('evt'),
|
|
1375
|
+
billingAccountId: input.billingAccount.id,
|
|
1376
|
+
type: `billfn.subscription.${subscription.status}`,
|
|
1377
|
+
payload: {
|
|
1378
|
+
subscriptionId: subscription.id,
|
|
1379
|
+
provider: subscription.provider,
|
|
1380
|
+
priceId: subscription.priceId
|
|
1381
|
+
},
|
|
1382
|
+
createdAt: timestamp
|
|
1383
|
+
});
|
|
1384
|
+
deps.metrics.track('subscription.updated', {
|
|
1385
|
+
provider: subscription.provider,
|
|
1386
|
+
status: subscription.status
|
|
1387
|
+
});
|
|
1388
|
+
return {
|
|
1389
|
+
checkoutSession: checkoutSession ?? input.checkoutSession,
|
|
1390
|
+
subscription,
|
|
1391
|
+
entitlements
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
async function upsertEntitlements(deps, billingAccountId, plan, subscription, timestamp) {
|
|
1395
|
+
const existing = await findEntitlementSnapshot(deps, billingAccountId);
|
|
1396
|
+
const snapshot = {
|
|
1397
|
+
id: existing?.id ?? `ent_${billingAccountId}`,
|
|
1398
|
+
billingAccountId,
|
|
1399
|
+
planKey: plan.planKey,
|
|
1400
|
+
status: mapSubscriptionToEntitlementStatus(subscription.status),
|
|
1401
|
+
features: { ...plan.features },
|
|
1402
|
+
limits: { ...plan.limits },
|
|
1403
|
+
effectiveAt: timestamp,
|
|
1404
|
+
expiresAt: subscription.currentPeriodEnd,
|
|
1405
|
+
sourceEventId: subscription.id,
|
|
1406
|
+
createdAt: existing?.createdAt ?? timestamp,
|
|
1407
|
+
updatedAt: timestamp
|
|
1408
|
+
};
|
|
1409
|
+
if (existing) {
|
|
1410
|
+
return deps.db.update({
|
|
1411
|
+
model: TABLES.entitlementSnapshots,
|
|
1412
|
+
where: [{ field: 'billingAccountId', operator: 'eq', value: billingAccountId }],
|
|
1413
|
+
data: snapshot,
|
|
1414
|
+
namespace: deps.namespace
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
return deps.db.create({
|
|
1418
|
+
model: TABLES.entitlementSnapshots,
|
|
1419
|
+
data: snapshot,
|
|
1420
|
+
namespace: deps.namespace
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
async function recordBillingEvent(deps, event) {
|
|
1424
|
+
await deps.db.create({
|
|
1425
|
+
model: TABLES.billingEvents,
|
|
1426
|
+
data: event,
|
|
1427
|
+
namespace: deps.namespace
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
async function createRefundRecord(deps, input) {
|
|
1431
|
+
const refund = {
|
|
1432
|
+
id: deps.generateId('rfd'),
|
|
1433
|
+
...input
|
|
1434
|
+
};
|
|
1435
|
+
await deps.db.create({
|
|
1436
|
+
model: TABLES.refunds,
|
|
1437
|
+
data: refund,
|
|
1438
|
+
namespace: deps.namespace
|
|
1439
|
+
});
|
|
1440
|
+
return refund;
|
|
1441
|
+
}
|
|
1442
|
+
async function createSubscriptionChangeRequestRecord(deps, input) {
|
|
1443
|
+
const changeRequest = {
|
|
1444
|
+
id: deps.generateId('scr'),
|
|
1445
|
+
...input
|
|
1446
|
+
};
|
|
1447
|
+
await deps.db.create({
|
|
1448
|
+
model: TABLES.subscriptionChangeRequests,
|
|
1449
|
+
data: changeRequest,
|
|
1450
|
+
namespace: deps.namespace
|
|
1451
|
+
});
|
|
1452
|
+
return changeRequest;
|
|
1453
|
+
}
|
|
1454
|
+
async function incrementUsage(deps, billingAccountId, resource, amount) {
|
|
1455
|
+
assertNonNegativeFiniteAmount(amount, 'bytes');
|
|
1456
|
+
if (amount === 0) {
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
const timestamp = toIsoString(deps.now());
|
|
1460
|
+
const meterId = `${billingAccountId}:${resource}`;
|
|
1461
|
+
let updated = false;
|
|
1462
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
1463
|
+
const existing = await findUsageMeter(deps, billingAccountId, resource);
|
|
1464
|
+
if (!existing) {
|
|
1465
|
+
try {
|
|
1466
|
+
await deps.db.create({
|
|
1467
|
+
model: TABLES.usageMeters,
|
|
1468
|
+
data: {
|
|
1469
|
+
id: meterId,
|
|
1470
|
+
billingAccountId,
|
|
1471
|
+
resource,
|
|
1472
|
+
current: amount,
|
|
1473
|
+
updatedAt: timestamp
|
|
1474
|
+
},
|
|
1475
|
+
namespace: deps.namespace
|
|
1476
|
+
});
|
|
1477
|
+
updated = true;
|
|
1478
|
+
break;
|
|
1479
|
+
}
|
|
1480
|
+
catch (error) {
|
|
1481
|
+
if (isDuplicateRecordError(error)) {
|
|
1482
|
+
await Promise.resolve();
|
|
1483
|
+
continue;
|
|
1484
|
+
}
|
|
1485
|
+
throw error;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
try {
|
|
1489
|
+
await deps.db.update({
|
|
1490
|
+
model: TABLES.usageMeters,
|
|
1491
|
+
where: [
|
|
1492
|
+
{ field: 'id', operator: 'eq', value: existing.id },
|
|
1493
|
+
{ field: 'current', operator: 'eq', value: existing.current }
|
|
1494
|
+
],
|
|
1495
|
+
data: {
|
|
1496
|
+
...existing,
|
|
1497
|
+
current: existing.current + amount,
|
|
1498
|
+
updatedAt: timestamp
|
|
1499
|
+
},
|
|
1500
|
+
namespace: deps.namespace
|
|
1501
|
+
});
|
|
1502
|
+
updated = true;
|
|
1503
|
+
break;
|
|
1504
|
+
}
|
|
1505
|
+
catch (error) {
|
|
1506
|
+
if (isOptimisticUsageConflict(error)) {
|
|
1507
|
+
await Promise.resolve();
|
|
1508
|
+
continue;
|
|
1509
|
+
}
|
|
1510
|
+
throw error;
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
if (!updated) {
|
|
1514
|
+
throw createBillFnError({
|
|
1515
|
+
code: 'BILLFN_CONFLICT',
|
|
1516
|
+
message: `Unable to update usage for ${resource} after multiple retries`
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
const ledger = {
|
|
1520
|
+
id: deps.generateId('ulg'),
|
|
1521
|
+
billingAccountId,
|
|
1522
|
+
resource,
|
|
1523
|
+
amount,
|
|
1524
|
+
createdAt: timestamp
|
|
1525
|
+
};
|
|
1526
|
+
await deps.db.create({
|
|
1527
|
+
model: TABLES.usageLedger,
|
|
1528
|
+
data: ledger,
|
|
1529
|
+
namespace: deps.namespace
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
async function resolveProjectionContextForProviderState(deps, input) {
|
|
1533
|
+
const subscription = await findSubscriptionByProviderRef(deps, input.provider, input.state.providerSubscriptionId, input.state.providerChargeId, input.checkoutReferenceId);
|
|
1534
|
+
if (subscription) {
|
|
1535
|
+
const billingAccount = await getBillingAccountById(deps, subscription.billingAccountId);
|
|
1536
|
+
if (!billingAccount) {
|
|
1537
|
+
return null;
|
|
1538
|
+
}
|
|
1539
|
+
const plan = requirePlan(deps.catalog, subscription.planKey);
|
|
1540
|
+
const price = requirePriceById(plan, subscription.priceId);
|
|
1541
|
+
const checkoutSession = await findCheckoutSessionByProviderRef(deps, input.provider, input.state.providerSubscriptionId, input.state.providerChargeId, input.checkoutReferenceId);
|
|
1542
|
+
return {
|
|
1543
|
+
billingAccount,
|
|
1544
|
+
subscription,
|
|
1545
|
+
checkoutSession,
|
|
1546
|
+
plan,
|
|
1547
|
+
price
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
const checkoutSession = await findCheckoutSessionByProviderRef(deps, input.provider, input.state.providerSubscriptionId, input.state.providerChargeId, input.checkoutReferenceId);
|
|
1551
|
+
if (!checkoutSession) {
|
|
1552
|
+
return null;
|
|
1553
|
+
}
|
|
1554
|
+
const billingAccount = await getBillingAccountById(deps, checkoutSession.billingAccountId);
|
|
1555
|
+
if (!billingAccount) {
|
|
1556
|
+
return null;
|
|
1557
|
+
}
|
|
1558
|
+
const plan = requirePlan(deps.catalog, checkoutSession.planKey);
|
|
1559
|
+
const price = requirePriceById(plan, checkoutSession.priceId);
|
|
1560
|
+
return {
|
|
1561
|
+
billingAccount,
|
|
1562
|
+
subscription: null,
|
|
1563
|
+
checkoutSession,
|
|
1564
|
+
plan,
|
|
1565
|
+
price
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
async function processParsedWebhookEvent(deps, providerName, event) {
|
|
1569
|
+
if (!event.billingState) {
|
|
1570
|
+
return null;
|
|
1571
|
+
}
|
|
1572
|
+
const projection = await resolveProjectionContextForProviderState(deps, {
|
|
1573
|
+
provider: providerName,
|
|
1574
|
+
state: event.billingState,
|
|
1575
|
+
checkoutReferenceId: event.checkoutReferenceId
|
|
1576
|
+
});
|
|
1577
|
+
if (!projection) {
|
|
1578
|
+
throw createBillFnError({
|
|
1579
|
+
code: 'BILLFN_NOT_FOUND',
|
|
1580
|
+
message: `Webhook event could not be linked to a billing account: ${event.providerEventId}`
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
return applyVerificationState(deps, {
|
|
1584
|
+
billingAccount: projection.billingAccount,
|
|
1585
|
+
plan: projection.plan,
|
|
1586
|
+
price: projection.price,
|
|
1587
|
+
checkoutSession: projection.checkoutSession ?? undefined,
|
|
1588
|
+
subscription: projection.subscription ?? undefined,
|
|
1589
|
+
state: event.billingState
|
|
1590
|
+
});
|
|
1591
|
+
}
|
|
1592
|
+
function jobToQueuePayload(job) {
|
|
1593
|
+
switch (job.kind) {
|
|
1594
|
+
case 'webhook-event':
|
|
1595
|
+
return {
|
|
1596
|
+
type: 'webhook-event',
|
|
1597
|
+
jobId: job.id,
|
|
1598
|
+
provider: job.provider,
|
|
1599
|
+
providerEventId: job.providerEventId
|
|
1600
|
+
};
|
|
1601
|
+
case 'subscription-sync':
|
|
1602
|
+
return {
|
|
1603
|
+
type: 'subscription-sync',
|
|
1604
|
+
jobId: job.id,
|
|
1605
|
+
provider: job.provider,
|
|
1606
|
+
subscriptionId: job.subscriptionId
|
|
1607
|
+
};
|
|
1608
|
+
case 'account-scan':
|
|
1609
|
+
return {
|
|
1610
|
+
type: 'account-scan',
|
|
1611
|
+
jobId: job.id,
|
|
1612
|
+
provider: job.provider,
|
|
1613
|
+
billingAccountId: job.billingAccountId
|
|
1614
|
+
};
|
|
1615
|
+
case 'notification-history-backfill':
|
|
1616
|
+
return {
|
|
1617
|
+
type: 'notification-history-backfill',
|
|
1618
|
+
jobId: job.id,
|
|
1619
|
+
provider: job.provider,
|
|
1620
|
+
cursor: job.cursor
|
|
1621
|
+
};
|
|
1622
|
+
case 'webhook-replay':
|
|
1623
|
+
return {
|
|
1624
|
+
type: 'webhook-replay',
|
|
1625
|
+
jobId: job.id,
|
|
1626
|
+
provider: job.provider,
|
|
1627
|
+
providerEventId: job.providerEventId
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
function buildWebhookReceiptId(provider, providerEventId) {
|
|
1632
|
+
return `whr_${provider}_${Buffer.from(providerEventId).toString('base64url')}`;
|
|
1633
|
+
}
|
|
1634
|
+
function serializeParsedWebhookEvent(event) {
|
|
1635
|
+
return {
|
|
1636
|
+
providerEventId: event.providerEventId,
|
|
1637
|
+
type: event.type,
|
|
1638
|
+
signatureVerified: event.signatureVerified,
|
|
1639
|
+
occurredAt: event.occurredAt,
|
|
1640
|
+
planKey: event.planKey,
|
|
1641
|
+
priceId: event.priceId,
|
|
1642
|
+
providerSubscriptionId: event.providerSubscriptionId,
|
|
1643
|
+
providerChargeId: event.providerChargeId,
|
|
1644
|
+
checkoutReferenceId: event.checkoutReferenceId,
|
|
1645
|
+
billingState: event.billingState,
|
|
1646
|
+
raw: event.raw
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
function deserializeParsedWebhookEvent(value) {
|
|
1650
|
+
const record = asRecord(value);
|
|
1651
|
+
if (!record) {
|
|
1652
|
+
return null;
|
|
1653
|
+
}
|
|
1654
|
+
return {
|
|
1655
|
+
providerEventId: readString(record, 'providerEventId') ?? 'unknown',
|
|
1656
|
+
type: readString(record, 'type') ?? 'unknown',
|
|
1657
|
+
signatureVerified: record.signatureVerified === true,
|
|
1658
|
+
occurredAt: readString(record, 'occurredAt') ?? undefined,
|
|
1659
|
+
planKey: readString(record, 'planKey') ?? undefined,
|
|
1660
|
+
priceId: readString(record, 'priceId') ?? undefined,
|
|
1661
|
+
providerSubscriptionId: readString(record, 'providerSubscriptionId') ?? undefined,
|
|
1662
|
+
providerChargeId: readString(record, 'providerChargeId') ?? undefined,
|
|
1663
|
+
checkoutReferenceId: readString(record, 'checkoutReferenceId') ?? undefined,
|
|
1664
|
+
billingState: asRecord(record.billingState),
|
|
1665
|
+
raw: asRecord(record.raw) ?? {}
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
function readString(record, key) {
|
|
1669
|
+
const value = record[key];
|
|
1670
|
+
return typeof value === 'string' && value.length > 0 ? value : null;
|
|
1671
|
+
}
|
|
1672
|
+
function asRecord(value) {
|
|
1673
|
+
return typeof value === 'object' && value !== null ? value : null;
|
|
1674
|
+
}
|
|
1675
|
+
function assertNonNegativeFiniteAmount(value, fieldName) {
|
|
1676
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
1677
|
+
throw createBillFnError({
|
|
1678
|
+
code: 'BILLFN_VALIDATION_ERROR',
|
|
1679
|
+
message: `${fieldName} must be a non-negative finite number`
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
function isDuplicateRecordError(error) {
|
|
1684
|
+
return error instanceof DuplicateKeyError || (error instanceof Error && error.message.includes('UNIQUE constraint failed'));
|
|
1685
|
+
}
|
|
1686
|
+
function isOptimisticUsageConflict(error) {
|
|
1687
|
+
return (error instanceof NotFoundError ||
|
|
1688
|
+
(error instanceof Error && 'code' in error && error.code === AdapterErrorCode.NOT_FOUND));
|
|
1689
|
+
}
|
|
1690
|
+
function mergeJson(existing, incoming) {
|
|
1691
|
+
if (!existing && !incoming) {
|
|
1692
|
+
return undefined;
|
|
1693
|
+
}
|
|
1694
|
+
return {
|
|
1695
|
+
...(existing ?? {}),
|
|
1696
|
+
...(incoming ?? {})
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
//# sourceMappingURL=service.js.map
|