better-auth-paystack 3.1.2 → 3.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.
- package/README.md +113 -36
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{index-BfHLsAWb.d.mts → index-CXuHlFoy.d.mts} +93 -16
- package/dist/index-CXuHlFoy.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +667 -139
- package/dist/index.mjs.map +1 -1
- package/dist/{version-Db-470Pe.mjs → version-BYbIySEf.mjs} +2 -2
- package/dist/{version-Db-470Pe.mjs.map → version-BYbIySEf.mjs.map} +1 -1
- package/package.json +1 -1
- package/skills/better-auth-paystack-setup/SKILL.md +1 -1
- package/skills/paystack-billing-flows/SKILL.md +1 -1
- package/skills/paystack-catalog-limits/SKILL.md +1 -1
- package/skills/paystack-client-api/SKILL.md +1 -1
- package/skills/paystack-local-subscriptions/SKILL.md +1 -1
- package/skills/paystack-organization-billing/SKILL.md +1 -1
- package/skills/paystack-schema-migrations/SKILL.md +1 -1
- package/skills/paystack-tanstack-start/SKILL.md +1 -1
- package/skills/paystack-testing-fixtures/SKILL.md +1 -1
- package/skills/paystack-webhooks-events/SKILL.md +1 -1
- package/dist/index-BfHLsAWb.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,26 @@
|
|
|
1
|
-
import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-
|
|
1
|
+
import { a as getMetadataBoolean, c as hasPaystackMetadata, i as createRenewalMetadata, l as parsePaystackMetadata, n as createCheckoutMetadata, o as getMetadataNumber, r as createProrationMetadata, s as getMetadataString, t as PACKAGE_VERSION, u as stringifyPaystackMetadata } from "./version-BYbIySEf.mjs";
|
|
2
2
|
import { HIDE_METADATA, defineErrorCodes } from "better-auth";
|
|
3
3
|
import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, originCheck, sessionMiddleware } from "better-auth/api";
|
|
4
4
|
import { defu } from "defu";
|
|
5
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
5
6
|
import { z } from "zod";
|
|
6
7
|
import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
|
|
8
|
+
import { Buffer } from "node:buffer";
|
|
7
9
|
import { mergeSchema } from "better-auth/db";
|
|
10
|
+
//#region src/models.ts
|
|
11
|
+
/** Provider-owned Better Auth model names. Keep these centralized so a provider
|
|
12
|
+
* model cannot accidentally fall back to Better Auth's generic billing tables. */
|
|
13
|
+
const PAYSTACK_MODELS = {
|
|
14
|
+
customer: "paystackCustomer",
|
|
15
|
+
paymentCredential: "paystackPaymentCredential",
|
|
16
|
+
subscription: "paystackSubscription",
|
|
17
|
+
transaction: "paystackTransaction",
|
|
18
|
+
product: "paystackProduct",
|
|
19
|
+
plan: "paystackPlan",
|
|
20
|
+
webhookEvent: "paystackWebhookEvent"
|
|
21
|
+
};
|
|
22
|
+
const LEGACY_PAYSTACK_MODELS = { subscription: "subscription" };
|
|
23
|
+
//#endregion
|
|
8
24
|
//#region src/billing-store.ts
|
|
9
25
|
function sortSubscriptionsForCurrent(subscriptions) {
|
|
10
26
|
const statusRank = /* @__PURE__ */ new Map([
|
|
@@ -25,24 +41,36 @@ function createBillingStore(ctx) {
|
|
|
25
41
|
return createBillingStoreFromAdapter(ctx.context.adapter);
|
|
26
42
|
}
|
|
27
43
|
function createBillingStoreFromAdapter(adapter) {
|
|
28
|
-
const findOne = async (model, where) =>
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
44
|
+
const findOne = async (model, where) => {
|
|
45
|
+
try {
|
|
46
|
+
return await adapter.findOne({
|
|
47
|
+
model,
|
|
48
|
+
where
|
|
49
|
+
}) ?? null;
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
const findMany = async (model, where) => {
|
|
55
|
+
try {
|
|
56
|
+
return await adapter.findMany({
|
|
57
|
+
model,
|
|
58
|
+
...where ? { where } : {}
|
|
59
|
+
}) ?? [];
|
|
60
|
+
} catch {
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
};
|
|
36
64
|
return {
|
|
37
|
-
findSubscriptionById: (id) => findOne(
|
|
65
|
+
findSubscriptionById: (id) => findOne(PAYSTACK_MODELS.subscription, [{
|
|
38
66
|
field: "id",
|
|
39
67
|
value: id
|
|
40
68
|
}]),
|
|
41
|
-
findSubscriptionByCode: (subscriptionCode) => findOne(
|
|
42
|
-
field: "
|
|
69
|
+
findSubscriptionByCode: (subscriptionCode) => findOne(PAYSTACK_MODELS.subscription, [{
|
|
70
|
+
field: "subscriptionCode",
|
|
43
71
|
value: subscriptionCode
|
|
44
72
|
}]),
|
|
45
|
-
findSubscriptionsByReference: (referenceId) => findMany(
|
|
73
|
+
findSubscriptionsByReference: (referenceId) => findMany(PAYSTACK_MODELS.subscription, [{
|
|
46
74
|
field: "referenceId",
|
|
47
75
|
value: referenceId
|
|
48
76
|
}]),
|
|
@@ -61,16 +89,16 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
61
89
|
updatedAt: now
|
|
62
90
|
});
|
|
63
91
|
},
|
|
64
|
-
findSubscriptionsByTransactionReference: (reference) => findMany(
|
|
65
|
-
field: "
|
|
92
|
+
findSubscriptionsByTransactionReference: (reference) => findMany(PAYSTACK_MODELS.subscription, [{
|
|
93
|
+
field: "transactionReference",
|
|
66
94
|
value: reference
|
|
67
95
|
}]),
|
|
68
96
|
createSubscription: async (data) => await adapter.create({
|
|
69
|
-
model:
|
|
97
|
+
model: PAYSTACK_MODELS.subscription,
|
|
70
98
|
data
|
|
71
99
|
}),
|
|
72
100
|
updateSubscription: (id, update) => adapter.update({
|
|
73
|
-
model:
|
|
101
|
+
model: PAYSTACK_MODELS.subscription,
|
|
74
102
|
update,
|
|
75
103
|
where: [{
|
|
76
104
|
field: "id",
|
|
@@ -78,49 +106,65 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
78
106
|
}]
|
|
79
107
|
}),
|
|
80
108
|
updateSubscriptionByCode: (subscriptionCode, update) => adapter.update({
|
|
81
|
-
model:
|
|
109
|
+
model: PAYSTACK_MODELS.subscription,
|
|
82
110
|
update,
|
|
83
111
|
where: [{
|
|
84
|
-
field: "
|
|
112
|
+
field: "subscriptionCode",
|
|
85
113
|
value: subscriptionCode
|
|
86
114
|
}]
|
|
87
115
|
}),
|
|
88
116
|
createTransaction: async (data) => await adapter.create({
|
|
89
|
-
model:
|
|
117
|
+
model: PAYSTACK_MODELS.transaction,
|
|
90
118
|
data
|
|
91
119
|
}),
|
|
92
|
-
findTransactionByReference: (reference) => findOne(
|
|
120
|
+
findTransactionByReference: (reference) => findOne(PAYSTACK_MODELS.transaction, [{
|
|
93
121
|
field: "reference",
|
|
94
122
|
value: reference
|
|
95
123
|
}]),
|
|
96
124
|
updateTransactionByReference: (reference, update) => adapter.update({
|
|
97
|
-
model:
|
|
125
|
+
model: PAYSTACK_MODELS.transaction,
|
|
98
126
|
update,
|
|
99
127
|
where: [{
|
|
100
128
|
field: "reference",
|
|
101
129
|
value: reference
|
|
102
130
|
}]
|
|
103
131
|
}),
|
|
132
|
+
createWebhookEvent: (data) => adapter.create({
|
|
133
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
134
|
+
data
|
|
135
|
+
}),
|
|
136
|
+
findWebhookEvent: (eventId) => findOne(PAYSTACK_MODELS.webhookEvent, [{
|
|
137
|
+
field: "eventId",
|
|
138
|
+
value: eventId
|
|
139
|
+
}]),
|
|
140
|
+
updateWebhookEvent: (eventId, update) => adapter.update({
|
|
141
|
+
model: PAYSTACK_MODELS.webhookEvent,
|
|
142
|
+
update,
|
|
143
|
+
where: [{
|
|
144
|
+
field: "eventId",
|
|
145
|
+
value: eventId
|
|
146
|
+
}]
|
|
147
|
+
}),
|
|
104
148
|
async listTransactions(referenceId) {
|
|
105
|
-
return (await findMany(
|
|
149
|
+
return (await findMany(PAYSTACK_MODELS.transaction, [{
|
|
106
150
|
field: "referenceId",
|
|
107
151
|
value: referenceId
|
|
108
152
|
}])).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
|
109
153
|
},
|
|
110
154
|
async listProducts() {
|
|
111
|
-
return (await findMany(
|
|
155
|
+
return (await findMany(PAYSTACK_MODELS.product)).sort((a, b) => a.name.localeCompare(b.name));
|
|
112
156
|
},
|
|
113
|
-
findProductByName: (name) => findOne(
|
|
157
|
+
findProductByName: (name) => findOne(PAYSTACK_MODELS.product, [{
|
|
114
158
|
field: "name",
|
|
115
159
|
value: name
|
|
116
160
|
}]),
|
|
117
|
-
findProductBySlug: (slug) => findOne(
|
|
161
|
+
findProductBySlug: (slug) => findOne(PAYSTACK_MODELS.product, [{
|
|
118
162
|
field: "slug",
|
|
119
163
|
value: slug
|
|
120
164
|
}]),
|
|
121
165
|
async updateProduct(id, update) {
|
|
122
166
|
await adapter.update({
|
|
123
|
-
model:
|
|
167
|
+
model: PAYSTACK_MODELS.product,
|
|
124
168
|
update,
|
|
125
169
|
where: [{
|
|
126
170
|
field: "id",
|
|
@@ -129,14 +173,14 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
129
173
|
});
|
|
130
174
|
},
|
|
131
175
|
async upsertProductByPaystackId(paystackId, data) {
|
|
132
|
-
const existing = await findOne(
|
|
176
|
+
const existing = await findOne(PAYSTACK_MODELS.product, [{
|
|
133
177
|
field: "paystackId",
|
|
134
178
|
value: paystackId
|
|
135
179
|
}]);
|
|
136
180
|
if (existing?.id !== void 0) {
|
|
137
181
|
const { createdAt: _createdAt, ...update } = data;
|
|
138
182
|
await adapter.update({
|
|
139
|
-
model:
|
|
183
|
+
model: PAYSTACK_MODELS.product,
|
|
140
184
|
update,
|
|
141
185
|
where: [{
|
|
142
186
|
field: "id",
|
|
@@ -146,28 +190,28 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
146
190
|
return;
|
|
147
191
|
}
|
|
148
192
|
await adapter.create({
|
|
149
|
-
model:
|
|
193
|
+
model: PAYSTACK_MODELS.product,
|
|
150
194
|
data
|
|
151
195
|
});
|
|
152
196
|
},
|
|
153
|
-
listPlans: () => findMany(
|
|
154
|
-
findPlanByName: (name) => findOne(
|
|
197
|
+
listPlans: () => findMany(PAYSTACK_MODELS.plan),
|
|
198
|
+
findPlanByName: (name) => findOne(PAYSTACK_MODELS.plan, [{
|
|
155
199
|
field: "name",
|
|
156
200
|
value: name
|
|
157
201
|
}]),
|
|
158
|
-
findPlanByCode: (planCode) => findOne(
|
|
202
|
+
findPlanByCode: (planCode) => findOne(PAYSTACK_MODELS.plan, [{
|
|
159
203
|
field: "planCode",
|
|
160
204
|
value: planCode
|
|
161
205
|
}]),
|
|
162
206
|
async upsertPlanByPaystackId(paystackId, data) {
|
|
163
|
-
const existing = await findOne(
|
|
207
|
+
const existing = await findOne(PAYSTACK_MODELS.plan, [{
|
|
164
208
|
field: "paystackId",
|
|
165
209
|
value: paystackId
|
|
166
210
|
}]);
|
|
167
211
|
if (existing?.id !== void 0) {
|
|
168
212
|
const { createdAt: _createdAt, ...update } = data;
|
|
169
213
|
await adapter.update({
|
|
170
|
-
model:
|
|
214
|
+
model: PAYSTACK_MODELS.plan,
|
|
171
215
|
update,
|
|
172
216
|
where: [{
|
|
173
217
|
field: "id",
|
|
@@ -177,7 +221,7 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
177
221
|
return;
|
|
178
222
|
}
|
|
179
223
|
await adapter.create({
|
|
180
|
-
model:
|
|
224
|
+
model: PAYSTACK_MODELS.plan,
|
|
181
225
|
data
|
|
182
226
|
});
|
|
183
227
|
},
|
|
@@ -204,15 +248,53 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
204
248
|
field: "organizationId",
|
|
205
249
|
value: organizationId
|
|
206
250
|
}]),
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
251
|
+
findCustomerByReference: (referenceType, referenceId) => findOne(PAYSTACK_MODELS.customer, [{
|
|
252
|
+
field: "referenceKey",
|
|
253
|
+
value: `${referenceType}:${referenceId}`
|
|
254
|
+
}]),
|
|
255
|
+
findCustomerByCode: (customerCode) => findOne(PAYSTACK_MODELS.customer, [{
|
|
256
|
+
field: "customerCode",
|
|
257
|
+
value: customerCode
|
|
258
|
+
}]),
|
|
259
|
+
async saveCustomer(referenceType, referenceId, customerCode, email) {
|
|
260
|
+
const referenceKey = `${referenceType}:${referenceId}`;
|
|
261
|
+
const existing = await findOne(PAYSTACK_MODELS.customer, [{
|
|
262
|
+
field: "referenceKey",
|
|
263
|
+
value: referenceKey
|
|
264
|
+
}]);
|
|
265
|
+
const now = /* @__PURE__ */ new Date();
|
|
266
|
+
if (existing) return await adapter.update({
|
|
267
|
+
model: PAYSTACK_MODELS.customer,
|
|
268
|
+
update: {
|
|
269
|
+
customerCode,
|
|
270
|
+
...email ? { email } : {},
|
|
271
|
+
updatedAt: now
|
|
272
|
+
},
|
|
211
273
|
where: [{
|
|
212
274
|
field: "id",
|
|
213
|
-
value:
|
|
275
|
+
value: existing.id
|
|
214
276
|
}]
|
|
277
|
+
}) ?? {
|
|
278
|
+
...existing,
|
|
279
|
+
customerCode,
|
|
280
|
+
email: email ?? existing.email,
|
|
281
|
+
updatedAt: now
|
|
282
|
+
};
|
|
283
|
+
return adapter.create({
|
|
284
|
+
model: PAYSTACK_MODELS.customer,
|
|
285
|
+
data: {
|
|
286
|
+
referenceType,
|
|
287
|
+
referenceId,
|
|
288
|
+
referenceKey,
|
|
289
|
+
customerCode,
|
|
290
|
+
...email ? { email } : {},
|
|
291
|
+
createdAt: now,
|
|
292
|
+
updatedAt: now
|
|
293
|
+
}
|
|
215
294
|
});
|
|
295
|
+
},
|
|
296
|
+
async saveCustomerCode(referenceId, customerCode, isOrganization, email) {
|
|
297
|
+
await this.saveCustomer(isOrganization ? "organization" : "user", referenceId, customerCode, email);
|
|
216
298
|
}
|
|
217
299
|
};
|
|
218
300
|
}
|
|
@@ -331,9 +413,9 @@ function isLocalSubscriptionCode(subscriptionCode) {
|
|
|
331
413
|
return typeof subscriptionCode === "string" && (subscriptionCode.startsWith("LOC_") || subscriptionCode.startsWith("sub_local_"));
|
|
332
414
|
}
|
|
333
415
|
function isLocallyManagedSubscription(subscription) {
|
|
334
|
-
if (isLocalSubscriptionCode(subscription.
|
|
335
|
-
if (typeof subscription.
|
|
336
|
-
return subscription.
|
|
416
|
+
if (isLocalSubscriptionCode(subscription.subscriptionCode)) return true;
|
|
417
|
+
if (typeof subscription.subscriptionCode === "string" && subscription.subscriptionCode !== "") return false;
|
|
418
|
+
return subscription.planCode === void 0 || subscription.planCode === null || subscription.planCode === "";
|
|
337
419
|
}
|
|
338
420
|
function assertLocallyManagedSubscription(subscription, action) {
|
|
339
421
|
if (!isLocallyManagedSubscription(subscription)) throw new Error(`Paystack-managed subscriptions do not support ${action}. Use local billing for seat-based or prorated subscription changes.`);
|
|
@@ -435,7 +517,7 @@ async function syncSubscriptionSeats(ctx, organizationId, options) {
|
|
|
435
517
|
}
|
|
436
518
|
const quantity = (await store.listMembers(organizationId)).length;
|
|
437
519
|
for (const subscription of seatSubscriptions) {
|
|
438
|
-
if (subscription.
|
|
520
|
+
if (subscription.subscriptionCode === void 0 || subscription.subscriptionCode === null || subscription.subscriptionCode === "") continue;
|
|
439
521
|
try {
|
|
440
522
|
assertLocallyManagedSubscription(subscription, "automatic seat sync");
|
|
441
523
|
await store.updateSubscription(subscription.id, {
|
|
@@ -548,6 +630,108 @@ const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
|
|
|
548
630
|
return true;
|
|
549
631
|
};
|
|
550
632
|
//#endregion
|
|
633
|
+
//#region src/credential-crypto.ts
|
|
634
|
+
const ALGORITHM = "aes-256-gcm";
|
|
635
|
+
const VERSION = "v1";
|
|
636
|
+
const IV_LENGTH = 12;
|
|
637
|
+
function deriveKey(secret) {
|
|
638
|
+
if (typeof secret !== "string" || secret.trim() === "") throw new Error("A non-empty credential encryption key is required");
|
|
639
|
+
return createHash("sha256").update(secret, "utf8").digest();
|
|
640
|
+
}
|
|
641
|
+
function encryptPaystackCredential(value, secret) {
|
|
642
|
+
if (value === "") throw new Error("Cannot encrypt an empty Paystack credential");
|
|
643
|
+
const iv = randomBytes(IV_LENGTH);
|
|
644
|
+
const cipher = createCipheriv(ALGORITHM, deriveKey(secret), iv);
|
|
645
|
+
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
646
|
+
const authTag = cipher.getAuthTag();
|
|
647
|
+
return [
|
|
648
|
+
VERSION,
|
|
649
|
+
iv.toString("hex"),
|
|
650
|
+
authTag.toString("hex"),
|
|
651
|
+
ciphertext.toString("hex")
|
|
652
|
+
].join(":");
|
|
653
|
+
}
|
|
654
|
+
function decryptPaystackCredential(encrypted, secret) {
|
|
655
|
+
const parts = encrypted.split(":");
|
|
656
|
+
if (parts.length !== 4 || parts[0] !== VERSION) throw new Error("Invalid Paystack credential ciphertext");
|
|
657
|
+
const [, ivHex, authTagHex, ciphertextHex] = parts;
|
|
658
|
+
const iv = Buffer.from(ivHex, "hex");
|
|
659
|
+
const authTag = Buffer.from(authTagHex, "hex");
|
|
660
|
+
const ciphertext = Buffer.from(ciphertextHex, "hex");
|
|
661
|
+
if (iv.length !== IV_LENGTH || authTag.length !== 16 || ciphertext.length === 0) throw new Error("Invalid Paystack credential ciphertext");
|
|
662
|
+
const decipher = createDecipheriv(ALGORITHM, deriveKey(secret), iv);
|
|
663
|
+
decipher.setAuthTag(authTag);
|
|
664
|
+
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
|
|
665
|
+
}
|
|
666
|
+
function resolveCredentialEncryptionKey(options) {
|
|
667
|
+
const key = options.credentialEncryptionKey ?? options.secretKey;
|
|
668
|
+
if (typeof key !== "string" || key.trim() === "") throw new Error("credentialEncryptionKey or secretKey must be a non-empty string");
|
|
669
|
+
return key;
|
|
670
|
+
}
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/payment-credentials.ts
|
|
673
|
+
async function readPaystackPaymentCredentials(adapter, options, subscriptionId) {
|
|
674
|
+
let row;
|
|
675
|
+
try {
|
|
676
|
+
row = await adapter.findOne({
|
|
677
|
+
model: PAYSTACK_MODELS.paymentCredential,
|
|
678
|
+
where: [{
|
|
679
|
+
field: "subscriptionId",
|
|
680
|
+
value: subscriptionId
|
|
681
|
+
}]
|
|
682
|
+
});
|
|
683
|
+
} catch {
|
|
684
|
+
return null;
|
|
685
|
+
}
|
|
686
|
+
if (!row) return null;
|
|
687
|
+
const key = resolveCredentialEncryptionKey(options);
|
|
688
|
+
return {
|
|
689
|
+
authorizationCode: row.authorizationCodeEncrypted ? decryptPaystackCredential(row.authorizationCodeEncrypted, key) : void 0,
|
|
690
|
+
emailToken: row.emailTokenEncrypted ? decryptPaystackCredential(row.emailTokenEncrypted, key) : void 0
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
async function savePaystackPaymentCredentials(adapter, options, subscriptionId, values) {
|
|
694
|
+
const authorizationCode = values.authorizationCode ?? void 0;
|
|
695
|
+
const emailToken = values.emailToken ?? void 0;
|
|
696
|
+
if (authorizationCode === void 0 && emailToken === void 0) return;
|
|
697
|
+
const key = resolveCredentialEncryptionKey(options);
|
|
698
|
+
const now = /* @__PURE__ */ new Date();
|
|
699
|
+
let existing = null;
|
|
700
|
+
try {
|
|
701
|
+
existing = await adapter.findOne({
|
|
702
|
+
model: PAYSTACK_MODELS.paymentCredential,
|
|
703
|
+
where: [{
|
|
704
|
+
field: "subscriptionId",
|
|
705
|
+
value: subscriptionId
|
|
706
|
+
}]
|
|
707
|
+
});
|
|
708
|
+
} catch {}
|
|
709
|
+
const update = {
|
|
710
|
+
...authorizationCode !== void 0 ? { authorizationCodeEncrypted: encryptPaystackCredential(authorizationCode, key) } : {},
|
|
711
|
+
...emailToken !== void 0 ? { emailTokenEncrypted: encryptPaystackCredential(emailToken, key) } : {},
|
|
712
|
+
updatedAt: now
|
|
713
|
+
};
|
|
714
|
+
if (existing !== null) {
|
|
715
|
+
await adapter.update({
|
|
716
|
+
model: PAYSTACK_MODELS.paymentCredential,
|
|
717
|
+
update,
|
|
718
|
+
where: [{
|
|
719
|
+
field: "id",
|
|
720
|
+
value: existing.id
|
|
721
|
+
}]
|
|
722
|
+
});
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
await adapter.create({
|
|
726
|
+
model: PAYSTACK_MODELS.paymentCredential,
|
|
727
|
+
data: {
|
|
728
|
+
subscriptionId,
|
|
729
|
+
...update,
|
|
730
|
+
createdAt: now
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
//#endregion
|
|
551
735
|
//#region src/subscription-lifecycle.ts
|
|
552
736
|
async function scheduleSubscriptionLifecycleChange(ctx, input) {
|
|
553
737
|
const groupId = normalizeSubscriptionGroup(input.plan?.group);
|
|
@@ -555,7 +739,7 @@ async function scheduleSubscriptionLifecycleChange(ctx, input) {
|
|
|
555
739
|
const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
|
|
556
740
|
if (existingSub?.status === "active") {
|
|
557
741
|
await ctx.context.adapter.update({
|
|
558
|
-
model:
|
|
742
|
+
model: PAYSTACK_MODELS.subscription,
|
|
559
743
|
where: [{
|
|
560
744
|
field: "id",
|
|
561
745
|
value: existingSub.id
|
|
@@ -577,7 +761,7 @@ async function scheduleSubscriptionLifecycleChange(ctx, input) {
|
|
|
577
761
|
const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, input.plan === void 0 ? void 0 : groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
|
|
578
762
|
if (existingSub?.status === "active") {
|
|
579
763
|
await ctx.context.adapter.update({
|
|
580
|
-
model:
|
|
764
|
+
model: PAYSTACK_MODELS.subscription,
|
|
581
765
|
where: [{
|
|
582
766
|
field: "id",
|
|
583
767
|
value: existingSub.id
|
|
@@ -608,7 +792,7 @@ async function resolveTrialLifecycle(ctx, input) {
|
|
|
608
792
|
granted: false
|
|
609
793
|
};
|
|
610
794
|
if ((await ctx.context.adapter.findMany({
|
|
611
|
-
model:
|
|
795
|
+
model: PAYSTACK_MODELS.subscription,
|
|
612
796
|
where: [{
|
|
613
797
|
field: "referenceId",
|
|
614
798
|
value: input.referenceId
|
|
@@ -666,7 +850,7 @@ async function resolveCheckoutTargetEmail(ctx, options, input) {
|
|
|
666
850
|
async function handleProratedUpgrade(ctx, options, input) {
|
|
667
851
|
const store = createBillingStore(ctx);
|
|
668
852
|
const existingSub = input.subscriptionId === void 0 ? await store.findCurrentSubscription(input.referenceId, normalizeSubscriptionGroup(input.plan.group)) : await store.findSubscriptionById(input.subscriptionId);
|
|
669
|
-
if (existingSub?.status !== "active" || existingSub.
|
|
853
|
+
if (existingSub?.status !== "active" || existingSub.subscriptionCode === void 0 || existingSub.subscriptionCode === null || existingSub.subscriptionCode === "" || existingSub.periodEnd === void 0 || existingSub.periodEnd === null || existingSub.periodStart === void 0 || existingSub.periodStart === null) return null;
|
|
670
854
|
const now = /* @__PURE__ */ new Date();
|
|
671
855
|
const periodEnd = new Date(existingSub.periodEnd);
|
|
672
856
|
const periodStart = new Date(existingSub.periodStart);
|
|
@@ -675,7 +859,7 @@ async function handleProratedUpgrade(ctx, options, input) {
|
|
|
675
859
|
let oldAmount = 0;
|
|
676
860
|
if (existingSub.plan !== "") {
|
|
677
861
|
const oldPlan = await getPlanByName(options, existingSub.plan) ?? await store.findPlanByName(existingSub.plan);
|
|
678
|
-
if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats);
|
|
862
|
+
if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats ?? 1);
|
|
679
863
|
}
|
|
680
864
|
let membersCount = 1;
|
|
681
865
|
let newSeatCount;
|
|
@@ -708,11 +892,12 @@ async function handleProratedUpgrade(ctx, options, input) {
|
|
|
708
892
|
status: 400
|
|
709
893
|
});
|
|
710
894
|
const paystack = createPaystackAdapter(options.paystackClient);
|
|
711
|
-
|
|
895
|
+
const credentials = await readPaystackPaymentCredentials(ctx.context.adapter, options, existingSub.id);
|
|
896
|
+
if (credentials?.authorizationCode) {
|
|
712
897
|
const sdkRes = await paystack.chargeAuthorization({
|
|
713
898
|
email: input.targetEmail,
|
|
714
899
|
amount: proratedAmount,
|
|
715
|
-
authorization_code:
|
|
900
|
+
authorization_code: credentials.authorizationCode,
|
|
716
901
|
reference: `upg_${existingSub.id}_${Date.now()}_${Math.random().toString(36).substring(7)}`,
|
|
717
902
|
metadata: serializedProrationMetadata
|
|
718
903
|
});
|
|
@@ -764,7 +949,7 @@ async function handleProratedUpgrade(ctx, options, input) {
|
|
|
764
949
|
await store.updateSubscription(existingSub.id, {
|
|
765
950
|
plan: input.plan.name,
|
|
766
951
|
seats: newSeatCount,
|
|
767
|
-
...completedProrationReference !== void 0 ? {
|
|
952
|
+
...completedProrationReference !== void 0 ? { transactionReference: completedProrationReference } : {},
|
|
768
953
|
updatedAt: /* @__PURE__ */ new Date()
|
|
769
954
|
});
|
|
770
955
|
return {
|
|
@@ -962,7 +1147,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
962
1147
|
if (paystackCustomerCodeFromPaystack !== void 0 && paystackCustomerCodeFromPaystack !== null && paystackCustomerCodeFromPaystack !== "" && referenceId !== void 0 && referenceId !== "") {
|
|
963
1148
|
let isOrganization = options.organization?.enabled === true && typeof referenceId === "string" && referenceId.startsWith("org_");
|
|
964
1149
|
if (isOrganization === false && options.organization?.enabled === true) isOrganization = await store.findOrganization(referenceId) !== null;
|
|
965
|
-
await store.saveCustomerCode(referenceId, paystackCustomerCodeFromPaystack, isOrganization);
|
|
1150
|
+
await store.saveCustomerCode(referenceId, paystackCustomerCodeFromPaystack, isOrganization, data.customer?.email);
|
|
966
1151
|
summary.customer.saved = true;
|
|
967
1152
|
summary.customer.referenceId = referenceId;
|
|
968
1153
|
summary.customer.customerCode = paystackCustomerCodeFromPaystack;
|
|
@@ -994,8 +1179,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
994
1179
|
const updatedSubscription = await store.updateSubscription(subscriptionId, {
|
|
995
1180
|
plan: newPlan,
|
|
996
1181
|
...typeof newSeatCount === "number" ? { seats: newSeatCount } : {},
|
|
997
|
-
|
|
998
|
-
...authorizationCode !== void 0 && authorizationCode !== null ? { paystackAuthorizationCode: authorizationCode } : {},
|
|
1182
|
+
transactionReference: reference,
|
|
999
1183
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1000
1184
|
});
|
|
1001
1185
|
summary.subscription.found = updatedSubscription !== null;
|
|
@@ -1003,6 +1187,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1003
1187
|
summary.subscription.id = updatedSubscription?.id ?? subscriptionId;
|
|
1004
1188
|
summary.subscription.status = updatedSubscription?.status;
|
|
1005
1189
|
summary.subscription.prorationApplied = updatedSubscription !== null;
|
|
1190
|
+
if (updatedSubscription && authorizationCode) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1006
1191
|
}
|
|
1007
1192
|
return {
|
|
1008
1193
|
ok: true,
|
|
@@ -1013,7 +1198,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1013
1198
|
...summary
|
|
1014
1199
|
};
|
|
1015
1200
|
}
|
|
1016
|
-
let
|
|
1201
|
+
let subscriptionCode;
|
|
1017
1202
|
const targetSub = (await store.findSubscriptionsByTransactionReference(reference)).find((subscription) => referenceId === void 0 || referenceId === "" || subscription.referenceId === referenceId);
|
|
1018
1203
|
summary.subscription.found = targetSub !== void 0;
|
|
1019
1204
|
summary.subscription.id = targetSub?.id;
|
|
@@ -1021,9 +1206,9 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1021
1206
|
if (isTrial && targetPlan !== void 0 && trialEnd !== void 0) {
|
|
1022
1207
|
const email = data.customer?.email;
|
|
1023
1208
|
const planConfig = (await getPlans(options.subscription)).find((plan) => plan.name.toLowerCase() === targetPlan.toLowerCase());
|
|
1024
|
-
if (planConfig !== void 0 && planConfig !== null && (planConfig.planCode === void 0 || planConfig.planCode === null || planConfig.planCode === ""))
|
|
1025
|
-
else if (targetSub?.
|
|
1026
|
-
else if (authorizationCode !== void 0 && authorizationCode !== null && email !== void 0 && email !== null && email !== "" && planConfig?.planCode !== void 0 && planConfig.planCode !== null && planConfig.planCode !== "")
|
|
1209
|
+
if (planConfig !== void 0 && planConfig !== null && (planConfig.planCode === void 0 || planConfig.planCode === null || planConfig.planCode === "")) subscriptionCode = `LOC_${reference}`;
|
|
1210
|
+
else if (targetSub?.subscriptionCode !== void 0 && targetSub.subscriptionCode !== null && targetSub.subscriptionCode !== "") subscriptionCode = targetSub.subscriptionCode;
|
|
1211
|
+
else if (authorizationCode !== void 0 && authorizationCode !== null && email !== void 0 && email !== null && email !== "" && planConfig?.planCode !== void 0 && planConfig.planCode !== null && planConfig.planCode !== "") subscriptionCode = unwrapSdkResult(await paystack?.subscription?.create({ body: {
|
|
1027
1212
|
customer: email,
|
|
1028
1213
|
plan: planConfig.planCode,
|
|
1029
1214
|
authorization: authorizationCode,
|
|
@@ -1031,8 +1216,8 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1031
1216
|
} }))?.subscription_code;
|
|
1032
1217
|
} else if (isTrial === false) {
|
|
1033
1218
|
const planCodeFromPaystack = data.plan?.plan_code;
|
|
1034
|
-
if (planCodeFromPaystack === void 0 || planCodeFromPaystack === null || planCodeFromPaystack === "")
|
|
1035
|
-
else
|
|
1219
|
+
if (planCodeFromPaystack === void 0 || planCodeFromPaystack === null || planCodeFromPaystack === "") subscriptionCode = `LOC_${reference}`;
|
|
1220
|
+
else subscriptionCode = data.subscription?.subscription_code ?? void 0;
|
|
1036
1221
|
}
|
|
1037
1222
|
let updatedSubscription = null;
|
|
1038
1223
|
if (targetSub !== void 0 && targetSub !== null) {
|
|
@@ -1047,12 +1232,12 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1047
1232
|
trialEnd: new Date(trialEnd),
|
|
1048
1233
|
periodEnd: new Date(trialEnd)
|
|
1049
1234
|
} : {},
|
|
1050
|
-
...
|
|
1051
|
-
...authorizationCode !== void 0 && authorizationCode !== null ? { paystackAuthorizationCode: authorizationCode } : {}
|
|
1235
|
+
...subscriptionCode !== void 0 ? { subscriptionCode } : {}
|
|
1052
1236
|
});
|
|
1053
1237
|
summary.subscription.updated = updatedSubscription !== null;
|
|
1054
1238
|
summary.subscription.id = updatedSubscription?.id ?? targetSub.id;
|
|
1055
1239
|
summary.subscription.status = updatedSubscription?.status ?? targetSub.status;
|
|
1240
|
+
if (authorizationCode && updatedSubscription !== null) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1056
1241
|
if (updatedSubscription !== null && (updatedSubscription.status === "active" || updatedSubscription.status === "trialing")) await store.retireCompetingSubscriptions(updatedSubscription.referenceId, updatedSubscription.groupId ?? null, updatedSubscription.id);
|
|
1057
1242
|
}
|
|
1058
1243
|
if (updatedSubscription !== void 0 && updatedSubscription !== null) {
|
|
@@ -1229,6 +1414,34 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1229
1414
|
const event = JSON.parse(payload);
|
|
1230
1415
|
const eventName = event.event;
|
|
1231
1416
|
const data = event.data;
|
|
1417
|
+
const reference = data?.reference;
|
|
1418
|
+
const eventId = createHash("sha256").update(payload).digest("hex");
|
|
1419
|
+
const store = createBillingStore(ctx);
|
|
1420
|
+
let webhookEventsAvailable = true;
|
|
1421
|
+
let existingEvent = null;
|
|
1422
|
+
try {
|
|
1423
|
+
existingEvent = await store.findWebhookEvent(eventId);
|
|
1424
|
+
} catch {
|
|
1425
|
+
webhookEventsAvailable = false;
|
|
1426
|
+
}
|
|
1427
|
+
if (webhookEventsAvailable && existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
1428
|
+
if (webhookEventsAvailable && existingEvent === null) try {
|
|
1429
|
+
await store.createWebhookEvent({
|
|
1430
|
+
eventId,
|
|
1431
|
+
eventType: eventName,
|
|
1432
|
+
reference: reference ?? null,
|
|
1433
|
+
payload,
|
|
1434
|
+
status: "pending",
|
|
1435
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1436
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1437
|
+
});
|
|
1438
|
+
} catch {
|
|
1439
|
+
try {
|
|
1440
|
+
existingEvent = await store.findWebhookEvent(eventId);
|
|
1441
|
+
if (existingEvent?.status === "processed") return ctx.json({ received: true });
|
|
1442
|
+
} catch {}
|
|
1443
|
+
webhookEventsAvailable = false;
|
|
1444
|
+
}
|
|
1232
1445
|
if (eventName === "charge.success") {
|
|
1233
1446
|
const reference = data?.reference;
|
|
1234
1447
|
const paystackIdRaw = data?.id;
|
|
@@ -1306,7 +1519,7 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1306
1519
|
value: referenceIdFromMetadata
|
|
1307
1520
|
});
|
|
1308
1521
|
else if (customerCode !== void 0 && customerCode !== null && customerCode !== "") where.push({
|
|
1309
|
-
field: "
|
|
1522
|
+
field: "customerCode",
|
|
1310
1523
|
value: customerCode
|
|
1311
1524
|
});
|
|
1312
1525
|
if (planName !== void 0 && planName !== null && planName !== "") where.push({
|
|
@@ -1315,7 +1528,7 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1315
1528
|
});
|
|
1316
1529
|
if (where.length > 0) {
|
|
1317
1530
|
const subscription = (await ctx.context.adapter.findMany({
|
|
1318
|
-
model:
|
|
1531
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1319
1532
|
where
|
|
1320
1533
|
}))?.find((candidate) => groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
|
|
1321
1534
|
if (subscription !== void 0 && subscription !== null) {
|
|
@@ -1323,16 +1536,16 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1323
1536
|
const now = /* @__PURE__ */ new Date();
|
|
1324
1537
|
const persistedSubscription = {
|
|
1325
1538
|
...subscription,
|
|
1326
|
-
|
|
1539
|
+
subscriptionCode,
|
|
1327
1540
|
status: "active",
|
|
1328
1541
|
billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
|
|
1329
1542
|
periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
|
|
1330
1543
|
updatedAt: now
|
|
1331
1544
|
};
|
|
1332
1545
|
await ctx.context.adapter.update({
|
|
1333
|
-
model:
|
|
1546
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1334
1547
|
update: {
|
|
1335
|
-
|
|
1548
|
+
subscriptionCode: persistedSubscription.subscriptionCode,
|
|
1336
1549
|
status: persistedSubscription.status,
|
|
1337
1550
|
billingInterval: persistedSubscription.billingInterval,
|
|
1338
1551
|
periodEnd: persistedSubscription.periodEnd,
|
|
@@ -1374,9 +1587,9 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1374
1587
|
const subscriptionCode = subscriptionData.subscription_code ?? "";
|
|
1375
1588
|
if (subscriptionCode !== "") {
|
|
1376
1589
|
const existing = await ctx.context.adapter.findOne({
|
|
1377
|
-
model:
|
|
1590
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1378
1591
|
where: [{
|
|
1379
|
-
field: "
|
|
1592
|
+
field: "subscriptionCode",
|
|
1380
1593
|
value: subscriptionCode
|
|
1381
1594
|
}]
|
|
1382
1595
|
});
|
|
@@ -1396,7 +1609,7 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1396
1609
|
updatedAt: now
|
|
1397
1610
|
};
|
|
1398
1611
|
await ctx.context.adapter.update({
|
|
1399
|
-
model:
|
|
1612
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1400
1613
|
update: {
|
|
1401
1614
|
status: newStatus,
|
|
1402
1615
|
cancelAtPeriodEnd: newStatus === "active",
|
|
@@ -1407,7 +1620,7 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1407
1620
|
updatedAt: now
|
|
1408
1621
|
},
|
|
1409
1622
|
where: [{
|
|
1410
|
-
field: "
|
|
1623
|
+
field: "subscriptionCode",
|
|
1411
1624
|
value: subscriptionCode
|
|
1412
1625
|
}]
|
|
1413
1626
|
});
|
|
@@ -1445,14 +1658,14 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1445
1658
|
const subscriptionCode = subscriptionCodeRaw !== void 0 && subscriptionCodeRaw !== null && subscriptionCodeRaw !== "" ? subscriptionCodeRaw : void 0;
|
|
1446
1659
|
if (subscriptionCode !== void 0) {
|
|
1447
1660
|
const existingSub = await ctx.context.adapter.findOne({
|
|
1448
|
-
model:
|
|
1661
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1449
1662
|
where: [{
|
|
1450
|
-
field: "
|
|
1663
|
+
field: "subscriptionCode",
|
|
1451
1664
|
value: subscriptionCode
|
|
1452
1665
|
}]
|
|
1453
1666
|
});
|
|
1454
1667
|
if (existingSub !== void 0 && existingSub !== null && existingSub.pendingPlan !== void 0 && existingSub.pendingPlan !== null && existingSub.pendingPlan !== "") await ctx.context.adapter.update({
|
|
1455
|
-
model:
|
|
1668
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1456
1669
|
update: {
|
|
1457
1670
|
plan: existingSub.pendingPlan,
|
|
1458
1671
|
pendingPlan: null,
|
|
@@ -1469,6 +1682,11 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1469
1682
|
ctx.context.logger.error("Failed to sync Paystack webhook event", _e);
|
|
1470
1683
|
}
|
|
1471
1684
|
await options.onEvent?.(event);
|
|
1685
|
+
if (webhookEventsAvailable) await store.updateWebhookEvent(eventId, {
|
|
1686
|
+
status: "processed",
|
|
1687
|
+
processedAt: /* @__PURE__ */ new Date(),
|
|
1688
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1689
|
+
});
|
|
1472
1690
|
return ctx.json({ received: true });
|
|
1473
1691
|
});
|
|
1474
1692
|
};
|
|
@@ -1680,7 +1898,7 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1680
1898
|
});
|
|
1681
1899
|
}
|
|
1682
1900
|
await ctx.context.adapter.create({
|
|
1683
|
-
model:
|
|
1901
|
+
model: PAYSTACK_MODELS.transaction,
|
|
1684
1902
|
data: {
|
|
1685
1903
|
reference: reference ?? "",
|
|
1686
1904
|
referenceId,
|
|
@@ -1696,32 +1914,30 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1696
1914
|
}
|
|
1697
1915
|
});
|
|
1698
1916
|
if (plan !== void 0) {
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1917
|
+
const store = createBillingStore(ctx);
|
|
1918
|
+
let customerCode = (await store.findCustomerByReference(referenceId === user.id ? "user" : "organization", referenceId))?.customerCode;
|
|
1919
|
+
if (customerCode === void 0) try {
|
|
1920
|
+
customerCode = (await ctx.context.adapter.findOne({
|
|
1921
|
+
model: referenceId === user.id ? "user" : "organization",
|
|
1703
1922
|
where: [{
|
|
1704
1923
|
field: "id",
|
|
1705
1924
|
value: referenceId
|
|
1706
|
-
}]
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
}
|
|
1712
|
-
}
|
|
1925
|
+
}],
|
|
1926
|
+
select: ["paystackCustomerCode"]
|
|
1927
|
+
}))?.paystackCustomerCode ?? void 0;
|
|
1928
|
+
if (customerCode) await store.saveCustomer(referenceId === user.id ? "user" : "organization", referenceId, customerCode);
|
|
1929
|
+
} catch {}
|
|
1713
1930
|
const newSubscription = await ctx.context.adapter.create({
|
|
1714
|
-
model:
|
|
1931
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1715
1932
|
data: {
|
|
1716
1933
|
plan: plan.name.toLowerCase(),
|
|
1717
1934
|
groupId,
|
|
1718
1935
|
referenceId,
|
|
1719
1936
|
userId: user.id,
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
paystackTransactionReference: reference ?? "",
|
|
1937
|
+
customerCode,
|
|
1938
|
+
subscriptionCode: void 0,
|
|
1939
|
+
planCode: plan.planCode,
|
|
1940
|
+
transactionReference: reference ?? "",
|
|
1725
1941
|
status: trialStart !== void 0 ? "trialing" : "incomplete",
|
|
1726
1942
|
billingInterval: plan.interval ?? null,
|
|
1727
1943
|
seats: quantity ?? 1,
|
|
@@ -1853,9 +2069,9 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
1853
2069
|
try {
|
|
1854
2070
|
if (isLocalSubscriptionCode(subscriptionCode)) {
|
|
1855
2071
|
const sub = await ctx.context.adapter.findOne({
|
|
1856
|
-
model:
|
|
2072
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1857
2073
|
where: [{
|
|
1858
|
-
field: "
|
|
2074
|
+
field: "subscriptionCode",
|
|
1859
2075
|
value: subscriptionCode
|
|
1860
2076
|
}]
|
|
1861
2077
|
});
|
|
@@ -1863,7 +2079,7 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
1863
2079
|
const now = /* @__PURE__ */ new Date();
|
|
1864
2080
|
const immediate = atPeriodEnd === false;
|
|
1865
2081
|
await ctx.context.adapter.update({
|
|
1866
|
-
model:
|
|
2082
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1867
2083
|
update: {
|
|
1868
2084
|
status: immediate ? "canceled" : "active",
|
|
1869
2085
|
cancelAtPeriodEnd: !immediate,
|
|
@@ -1881,7 +2097,9 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
1881
2097
|
}
|
|
1882
2098
|
throw new APIError("BAD_REQUEST", { message: "Subscription not found" });
|
|
1883
2099
|
}
|
|
1884
|
-
|
|
2100
|
+
const storedSubscription = await createBillingStore(ctx).findSubscriptionByCode(subscriptionCode);
|
|
2101
|
+
const storedCredentials = storedSubscription ? await readPaystackPaymentCredentials(ctx.context.adapter, options, storedSubscription.id) : null;
|
|
2102
|
+
let emailToken = ctx.body.emailToken ?? storedCredentials?.emailToken;
|
|
1885
2103
|
let nextPaymentDate;
|
|
1886
2104
|
try {
|
|
1887
2105
|
const fetchRes = unwrapSdkResult(await paystack?.subscription?.fetch(subscriptionCode));
|
|
@@ -1895,15 +2113,16 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
1895
2113
|
if (link !== void 0 && link !== null && link !== "") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
|
|
1896
2114
|
} catch {}
|
|
1897
2115
|
if (emailToken === void 0 || emailToken === null || emailToken === "") throw new Error("Could not retrieve email_token for subscription disable.");
|
|
2116
|
+
if (storedSubscription) await savePaystackPaymentCredentials(ctx.context.adapter, options, storedSubscription.id, { emailToken });
|
|
1898
2117
|
await paystack?.subscription?.disable({ body: {
|
|
1899
2118
|
code: subscriptionCode,
|
|
1900
2119
|
token: emailToken
|
|
1901
2120
|
} });
|
|
1902
2121
|
const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : void 0;
|
|
1903
2122
|
const sub = await ctx.context.adapter.findOne({
|
|
1904
|
-
model:
|
|
2123
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1905
2124
|
where: [{
|
|
1906
|
-
field: "
|
|
2125
|
+
field: "subscriptionCode",
|
|
1907
2126
|
value: subscriptionCode
|
|
1908
2127
|
}]
|
|
1909
2128
|
});
|
|
@@ -1911,7 +2130,7 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
1911
2130
|
const now = /* @__PURE__ */ new Date();
|
|
1912
2131
|
const immediate = atPeriodEnd === false;
|
|
1913
2132
|
await ctx.context.adapter.update({
|
|
1914
|
-
model:
|
|
2133
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1915
2134
|
update: {
|
|
1916
2135
|
status: immediate ? "canceled" : "active",
|
|
1917
2136
|
cancelAtPeriodEnd: !immediate,
|
|
@@ -1950,7 +2169,9 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
|
1950
2169
|
const { subscriptionCode } = ctx.body;
|
|
1951
2170
|
const paystack = getPaystackOps(options.paystackClient);
|
|
1952
2171
|
try {
|
|
1953
|
-
|
|
2172
|
+
const storedSubscription = await createBillingStore(ctx).findSubscriptionByCode(subscriptionCode);
|
|
2173
|
+
const storedCredentials = storedSubscription ? await readPaystackPaymentCredentials(ctx.context.adapter, options, storedSubscription.id) : null;
|
|
2174
|
+
let emailToken = ctx.body.emailToken ?? storedCredentials?.emailToken;
|
|
1954
2175
|
if (emailToken === void 0 || emailToken === null || emailToken === "") try {
|
|
1955
2176
|
const fetchRes = unwrapSdkResult(await paystack?.subscription?.fetch(subscriptionCode));
|
|
1956
2177
|
if (fetchRes !== void 0 && fetchRes !== null) emailToken = fetchRes.email_token ?? void 0;
|
|
@@ -1960,12 +2181,13 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
|
1960
2181
|
if (link !== void 0 && link !== null && link !== "") emailToken = tryGetEmailTokenFromSubscriptionManageLink(link);
|
|
1961
2182
|
} catch {}
|
|
1962
2183
|
if (emailToken === void 0 || emailToken === null || emailToken === "") throw new APIError("BAD_REQUEST", { message: "Could not retrieve email_token for subscription enable." });
|
|
2184
|
+
if (storedSubscription) await savePaystackPaymentCredentials(ctx.context.adapter, options, storedSubscription.id, { emailToken });
|
|
1963
2185
|
await paystack?.subscription?.enable({ body: {
|
|
1964
2186
|
code: subscriptionCode,
|
|
1965
2187
|
token: emailToken
|
|
1966
2188
|
} });
|
|
1967
2189
|
await ctx.context.adapter.update({
|
|
1968
|
-
model:
|
|
2190
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1969
2191
|
update: {
|
|
1970
2192
|
status: "active",
|
|
1971
2193
|
cancelAtPeriodEnd: false,
|
|
@@ -1975,7 +2197,7 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
|
1975
2197
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1976
2198
|
},
|
|
1977
2199
|
where: [{
|
|
1978
|
-
field: "
|
|
2200
|
+
field: "subscriptionCode",
|
|
1979
2201
|
value: subscriptionCode
|
|
1980
2202
|
}]
|
|
1981
2203
|
});
|
|
@@ -2102,7 +2324,7 @@ const transactions = { paystackTransaction: { fields: {
|
|
|
2102
2324
|
required: true
|
|
2103
2325
|
}
|
|
2104
2326
|
} } };
|
|
2105
|
-
const subscriptions = {
|
|
2327
|
+
const subscriptions = { paystackSubscription: { fields: {
|
|
2106
2328
|
plan: {
|
|
2107
2329
|
type: "string",
|
|
2108
2330
|
required: true,
|
|
@@ -2113,26 +2335,27 @@ const subscriptions = { subscription: { fields: {
|
|
|
2113
2335
|
required: true,
|
|
2114
2336
|
index: true
|
|
2115
2337
|
},
|
|
2116
|
-
|
|
2338
|
+
userId: {
|
|
2339
|
+
type: "string",
|
|
2340
|
+
required: true,
|
|
2341
|
+
index: true
|
|
2342
|
+
},
|
|
2343
|
+
customerCode: {
|
|
2117
2344
|
type: "string",
|
|
2118
2345
|
required: false,
|
|
2119
2346
|
index: true
|
|
2120
2347
|
},
|
|
2121
|
-
|
|
2348
|
+
subscriptionCode: {
|
|
2122
2349
|
type: "string",
|
|
2123
2350
|
required: false,
|
|
2124
2351
|
unique: true
|
|
2125
2352
|
},
|
|
2126
|
-
|
|
2353
|
+
transactionReference: {
|
|
2127
2354
|
type: "string",
|
|
2128
2355
|
required: false,
|
|
2129
2356
|
index: true
|
|
2130
2357
|
},
|
|
2131
|
-
|
|
2132
|
-
type: "string",
|
|
2133
|
-
required: false
|
|
2134
|
-
},
|
|
2135
|
-
paystackEmailToken: {
|
|
2358
|
+
planCode: {
|
|
2136
2359
|
type: "string",
|
|
2137
2360
|
required: false
|
|
2138
2361
|
},
|
|
@@ -2188,24 +2411,78 @@ const subscriptions = { subscription: { fields: {
|
|
|
2188
2411
|
pendingPlan: {
|
|
2189
2412
|
type: "string",
|
|
2190
2413
|
required: false
|
|
2414
|
+
},
|
|
2415
|
+
createdAt: {
|
|
2416
|
+
type: "date",
|
|
2417
|
+
required: true
|
|
2418
|
+
},
|
|
2419
|
+
updatedAt: {
|
|
2420
|
+
type: "date",
|
|
2421
|
+
required: true
|
|
2191
2422
|
}
|
|
2192
2423
|
} } };
|
|
2193
|
-
const
|
|
2194
|
-
|
|
2195
|
-
required: false,
|
|
2196
|
-
index: true
|
|
2197
|
-
} } } };
|
|
2198
|
-
const organization = { organization: { fields: {
|
|
2199
|
-
paystackCustomerCode: {
|
|
2424
|
+
const customers = { paystackCustomer: { fields: {
|
|
2425
|
+
referenceType: {
|
|
2200
2426
|
type: "string",
|
|
2201
|
-
required:
|
|
2427
|
+
required: true
|
|
2428
|
+
},
|
|
2429
|
+
referenceId: {
|
|
2430
|
+
type: "string",
|
|
2431
|
+
required: true,
|
|
2202
2432
|
index: true
|
|
2203
2433
|
},
|
|
2434
|
+
referenceKey: {
|
|
2435
|
+
type: "string",
|
|
2436
|
+
required: true,
|
|
2437
|
+
unique: true
|
|
2438
|
+
},
|
|
2439
|
+
customerCode: {
|
|
2440
|
+
type: "string",
|
|
2441
|
+
required: true,
|
|
2442
|
+
unique: true
|
|
2443
|
+
},
|
|
2204
2444
|
email: {
|
|
2205
2445
|
type: "string",
|
|
2206
2446
|
required: false
|
|
2447
|
+
},
|
|
2448
|
+
createdAt: {
|
|
2449
|
+
type: "date",
|
|
2450
|
+
required: true
|
|
2451
|
+
},
|
|
2452
|
+
updatedAt: {
|
|
2453
|
+
type: "date",
|
|
2454
|
+
required: true
|
|
2455
|
+
}
|
|
2456
|
+
} } };
|
|
2457
|
+
const paymentCredentials = { paystackPaymentCredential: { fields: {
|
|
2458
|
+
subscriptionId: {
|
|
2459
|
+
type: "string",
|
|
2460
|
+
required: true,
|
|
2461
|
+
unique: true,
|
|
2462
|
+
index: true
|
|
2463
|
+
},
|
|
2464
|
+
authorizationCodeEncrypted: {
|
|
2465
|
+
type: "string",
|
|
2466
|
+
required: false
|
|
2467
|
+
},
|
|
2468
|
+
emailTokenEncrypted: {
|
|
2469
|
+
type: "string",
|
|
2470
|
+
required: false
|
|
2471
|
+
},
|
|
2472
|
+
createdAt: {
|
|
2473
|
+
type: "date",
|
|
2474
|
+
required: true
|
|
2475
|
+
},
|
|
2476
|
+
updatedAt: {
|
|
2477
|
+
type: "date",
|
|
2478
|
+
required: true
|
|
2207
2479
|
}
|
|
2208
2480
|
} } };
|
|
2481
|
+
const user = { user: { fields: {} } };
|
|
2482
|
+
const organization = { organization: { fields: { email: {
|
|
2483
|
+
type: "string",
|
|
2484
|
+
required: false
|
|
2485
|
+
} } } };
|
|
2209
2486
|
const products = { paystackProduct: { fields: {
|
|
2210
2487
|
name: {
|
|
2211
2488
|
type: "string",
|
|
@@ -2304,13 +2581,55 @@ const plans = { paystackPlan: { fields: {
|
|
|
2304
2581
|
required: true
|
|
2305
2582
|
}
|
|
2306
2583
|
} } };
|
|
2584
|
+
const webhookEvents = { paystackWebhookEvent: { fields: {
|
|
2585
|
+
eventId: {
|
|
2586
|
+
type: "string",
|
|
2587
|
+
required: true,
|
|
2588
|
+
unique: true
|
|
2589
|
+
},
|
|
2590
|
+
eventType: {
|
|
2591
|
+
type: "string",
|
|
2592
|
+
required: true,
|
|
2593
|
+
index: true
|
|
2594
|
+
},
|
|
2595
|
+
reference: {
|
|
2596
|
+
type: "string",
|
|
2597
|
+
required: false,
|
|
2598
|
+
index: true
|
|
2599
|
+
},
|
|
2600
|
+
payload: {
|
|
2601
|
+
type: "string",
|
|
2602
|
+
required: true
|
|
2603
|
+
},
|
|
2604
|
+
status: {
|
|
2605
|
+
type: "string",
|
|
2606
|
+
required: true,
|
|
2607
|
+
defaultValue: "pending",
|
|
2608
|
+
index: true
|
|
2609
|
+
},
|
|
2610
|
+
processedAt: {
|
|
2611
|
+
type: "date",
|
|
2612
|
+
required: false
|
|
2613
|
+
},
|
|
2614
|
+
createdAt: {
|
|
2615
|
+
type: "date",
|
|
2616
|
+
required: true
|
|
2617
|
+
},
|
|
2618
|
+
updatedAt: {
|
|
2619
|
+
type: "date",
|
|
2620
|
+
required: true
|
|
2621
|
+
}
|
|
2622
|
+
} } };
|
|
2307
2623
|
({
|
|
2308
2624
|
...subscriptions,
|
|
2309
2625
|
...transactions,
|
|
2626
|
+
...customers,
|
|
2627
|
+
...paymentCredentials,
|
|
2310
2628
|
...user,
|
|
2311
2629
|
...organization,
|
|
2312
2630
|
...products,
|
|
2313
|
-
...plans
|
|
2631
|
+
...plans,
|
|
2632
|
+
...webhookEvents
|
|
2314
2633
|
});
|
|
2315
2634
|
const getSchema = (options) => {
|
|
2316
2635
|
let baseSchema;
|
|
@@ -2318,21 +2637,27 @@ const getSchema = (options) => {
|
|
|
2318
2637
|
if (options.subscription?.enabled === true) baseSchema = {
|
|
2319
2638
|
...subscriptions,
|
|
2320
2639
|
...transactions,
|
|
2640
|
+
...customers,
|
|
2641
|
+
...paymentCredentials,
|
|
2321
2642
|
...user,
|
|
2322
2643
|
...products,
|
|
2323
|
-
...plans
|
|
2644
|
+
...plans,
|
|
2645
|
+
...webhookEvents
|
|
2324
2646
|
};
|
|
2325
2647
|
else baseSchema = {
|
|
2326
2648
|
...user,
|
|
2327
2649
|
...transactions,
|
|
2650
|
+
...customers,
|
|
2651
|
+
...paymentCredentials,
|
|
2328
2652
|
...products,
|
|
2329
|
-
...plans
|
|
2653
|
+
...plans,
|
|
2654
|
+
...webhookEvents
|
|
2330
2655
|
};
|
|
2331
2656
|
if (options.organization?.enabled === true) baseSchema = {
|
|
2332
2657
|
...baseSchema,
|
|
2333
2658
|
...organization
|
|
2334
2659
|
};
|
|
2335
|
-
if (options.schema !== void 0 &&
|
|
2660
|
+
if (options.schema !== void 0 && "subscription" in options.schema) {
|
|
2336
2661
|
const { subscription: _subscription, ...restSchema } = optionSchema ?? {};
|
|
2337
2662
|
return mergeSchema(baseSchema, restSchema);
|
|
2338
2663
|
}
|
|
@@ -2372,9 +2697,23 @@ function ownershipMetadata(reference, existing) {
|
|
|
2372
2697
|
async function resolvePaystackCustomer(input) {
|
|
2373
2698
|
const { adapter, client, logger, reference } = input;
|
|
2374
2699
|
const store = createBillingStoreFromAdapter(adapter);
|
|
2375
|
-
const persisted =
|
|
2376
|
-
|
|
2377
|
-
|
|
2700
|
+
const persisted = await store.findCustomerByReference(reference.type, reference.id);
|
|
2701
|
+
let legacyCode;
|
|
2702
|
+
try {
|
|
2703
|
+
legacyCode = (await adapter.findOne({
|
|
2704
|
+
model: reference.type,
|
|
2705
|
+
where: [{
|
|
2706
|
+
field: "id",
|
|
2707
|
+
value: reference.id
|
|
2708
|
+
}],
|
|
2709
|
+
select: ["paystackCustomerCode"]
|
|
2710
|
+
}))?.paystackCustomerCode ?? void 0;
|
|
2711
|
+
} catch {}
|
|
2712
|
+
const existingCode = reference.paystackCustomerCode ?? persisted?.customerCode ?? legacyCode;
|
|
2713
|
+
if (typeof existingCode === "string" && existingCode !== "") {
|
|
2714
|
+
if (persisted === null) await store.saveCustomer(reference.type, reference.id, existingCode, reference.email);
|
|
2715
|
+
return null;
|
|
2716
|
+
}
|
|
2378
2717
|
const sdk = createPaystackAdapter(client);
|
|
2379
2718
|
let existing = null;
|
|
2380
2719
|
if (typeof client.customer?.fetch === "function") try {
|
|
@@ -2399,7 +2738,7 @@ async function resolvePaystackCustomer(input) {
|
|
|
2399
2738
|
}
|
|
2400
2739
|
const existingMetadata = existing.metadata;
|
|
2401
2740
|
if (canClaimLegacy || parsePaystackMetadata(existingMetadata).customerType !== reference.type) await sdk.updateCustomer(code, { metadata: ownershipMetadata(reference, existingMetadata) });
|
|
2402
|
-
await store.
|
|
2741
|
+
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
2403
2742
|
return {
|
|
2404
2743
|
customer: existing,
|
|
2405
2744
|
created: false
|
|
@@ -2413,7 +2752,7 @@ async function resolvePaystackCustomer(input) {
|
|
|
2413
2752
|
});
|
|
2414
2753
|
const code = customerCode(customer);
|
|
2415
2754
|
if (code === void 0) return null;
|
|
2416
|
-
await store.
|
|
2755
|
+
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
2417
2756
|
return {
|
|
2418
2757
|
customer,
|
|
2419
2758
|
created: true
|
|
@@ -2499,7 +2838,8 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2499
2838
|
const store = createBillingStore(ctx);
|
|
2500
2839
|
const subscription = await store.findSubscriptionById(subscriptionId);
|
|
2501
2840
|
if (subscription === void 0 || subscription === null) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
2502
|
-
|
|
2841
|
+
const credentials = await readPaystackPaymentCredentials(ctx.context.adapter, options, subscription.id);
|
|
2842
|
+
if (!credentials?.authorizationCode) throw new APIError("BAD_REQUEST", { message: "No authorization code found for this subscription" });
|
|
2503
2843
|
const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
|
|
2504
2844
|
if (plan === void 0 || plan === null) throw new APIError("NOT_FOUND", { message: "Plan not found" });
|
|
2505
2845
|
const amount = bodyAmount ?? plan.amount;
|
|
@@ -2535,7 +2875,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2535
2875
|
const typedChargeData = await paystack.chargeAuthorization({
|
|
2536
2876
|
email,
|
|
2537
2877
|
amount,
|
|
2538
|
-
authorization_code:
|
|
2878
|
+
authorization_code: credentials.authorizationCode,
|
|
2539
2879
|
reference: `rec_${subscription.id}_${Date.now()}`,
|
|
2540
2880
|
metadata: serializedRenewalMetadata
|
|
2541
2881
|
});
|
|
@@ -2559,7 +2899,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2559
2899
|
periodStart: now,
|
|
2560
2900
|
periodEnd: nextPeriodEnd,
|
|
2561
2901
|
updatedAt: now,
|
|
2562
|
-
|
|
2902
|
+
transactionReference: typedChargeData.reference
|
|
2563
2903
|
});
|
|
2564
2904
|
return {
|
|
2565
2905
|
status: "success",
|
|
@@ -2572,6 +2912,196 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2572
2912
|
};
|
|
2573
2913
|
}
|
|
2574
2914
|
//#endregion
|
|
2915
|
+
//#region src/migrations.ts
|
|
2916
|
+
function asString(value) {
|
|
2917
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
2918
|
+
}
|
|
2919
|
+
function asIdentifier(value) {
|
|
2920
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
2921
|
+
return asString(value);
|
|
2922
|
+
}
|
|
2923
|
+
function asDate(value, fallback) {
|
|
2924
|
+
if (value instanceof Date) return value;
|
|
2925
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
2926
|
+
const date = new Date(value);
|
|
2927
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
2928
|
+
}
|
|
2929
|
+
return fallback;
|
|
2930
|
+
}
|
|
2931
|
+
function asOptionalDate(value) {
|
|
2932
|
+
if (value === null) return null;
|
|
2933
|
+
if (value === void 0) return void 0;
|
|
2934
|
+
if (value instanceof Date) return value;
|
|
2935
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
2936
|
+
const date = new Date(value);
|
|
2937
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
2938
|
+
}
|
|
2939
|
+
}
|
|
2940
|
+
async function findManySafely(adapter, model) {
|
|
2941
|
+
try {
|
|
2942
|
+
return await adapter.findMany({ model }) ?? [];
|
|
2943
|
+
} catch {
|
|
2944
|
+
return [];
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
function migrationData(legacy) {
|
|
2948
|
+
const now = /* @__PURE__ */ new Date();
|
|
2949
|
+
const referenceId = asIdentifier(legacy.referenceId) ?? asIdentifier(legacy.userId) ?? "";
|
|
2950
|
+
return {
|
|
2951
|
+
...asIdentifier(legacy.id) ? { id: asIdentifier(legacy.id) } : {},
|
|
2952
|
+
plan: asString(legacy.plan) ?? "",
|
|
2953
|
+
referenceId,
|
|
2954
|
+
userId: asIdentifier(legacy.userId) ?? referenceId,
|
|
2955
|
+
customerCode: asString(legacy.customerCode) ?? asString(legacy.paystackCustomerCode) ?? void 0,
|
|
2956
|
+
subscriptionCode: asString(legacy.subscriptionCode) ?? asString(legacy.paystackSubscriptionCode) ?? void 0,
|
|
2957
|
+
transactionReference: asString(legacy.transactionReference) ?? asString(legacy.paystackTransactionReference) ?? void 0,
|
|
2958
|
+
planCode: asString(legacy.planCode) ?? asString(legacy.paystackPlanCode) ?? void 0,
|
|
2959
|
+
status: asString(legacy.status) ?? "incomplete",
|
|
2960
|
+
periodStart: asDate(legacy.periodStart, now),
|
|
2961
|
+
periodEnd: asOptionalDate(legacy.periodEnd),
|
|
2962
|
+
trialStart: asOptionalDate(legacy.trialStart),
|
|
2963
|
+
trialEnd: asOptionalDate(legacy.trialEnd),
|
|
2964
|
+
cancelAtPeriodEnd: legacy.cancelAtPeriodEnd === true,
|
|
2965
|
+
cancelAt: asOptionalDate(legacy.cancelAt),
|
|
2966
|
+
canceledAt: asOptionalDate(legacy.canceledAt),
|
|
2967
|
+
endedAt: asOptionalDate(legacy.endedAt),
|
|
2968
|
+
billingInterval: asString(legacy.billingInterval) ?? void 0,
|
|
2969
|
+
groupId: asString(legacy.groupId) ?? void 0,
|
|
2970
|
+
seats: typeof legacy.seats === "number" ? legacy.seats : void 0,
|
|
2971
|
+
pendingPlan: asString(legacy.pendingPlan) ?? void 0,
|
|
2972
|
+
createdAt: asDate(legacy.createdAt, now),
|
|
2973
|
+
updatedAt: asDate(legacy.updatedAt, now)
|
|
2974
|
+
};
|
|
2975
|
+
}
|
|
2976
|
+
async function migrateCustomer(adapter, referenceType, legacy, report) {
|
|
2977
|
+
const customerCode = asString(legacy.paystackCustomerCode) ?? asString(legacy.customerCode);
|
|
2978
|
+
const referenceId = asIdentifier(legacy.id);
|
|
2979
|
+
if (!customerCode || !referenceId) return;
|
|
2980
|
+
const referenceKey = `${referenceType}:${referenceId}`;
|
|
2981
|
+
try {
|
|
2982
|
+
if (await adapter.findOne({
|
|
2983
|
+
model: PAYSTACK_MODELS.customer,
|
|
2984
|
+
where: [{
|
|
2985
|
+
field: "referenceKey",
|
|
2986
|
+
value: referenceKey
|
|
2987
|
+
}]
|
|
2988
|
+
})) {
|
|
2989
|
+
report.customers.skipped += 1;
|
|
2990
|
+
report.skipped += 1;
|
|
2991
|
+
return;
|
|
2992
|
+
}
|
|
2993
|
+
const now = /* @__PURE__ */ new Date();
|
|
2994
|
+
const email = asString(legacy.email);
|
|
2995
|
+
await adapter.create({
|
|
2996
|
+
model: PAYSTACK_MODELS.customer,
|
|
2997
|
+
data: {
|
|
2998
|
+
referenceType,
|
|
2999
|
+
referenceId,
|
|
3000
|
+
referenceKey,
|
|
3001
|
+
customerCode,
|
|
3002
|
+
...email !== void 0 ? { email } : {},
|
|
3003
|
+
createdAt: asDate(legacy.createdAt, now),
|
|
3004
|
+
updatedAt: asDate(legacy.updatedAt, now)
|
|
3005
|
+
}
|
|
3006
|
+
});
|
|
3007
|
+
report.customers.migrated += 1;
|
|
3008
|
+
} catch (error) {
|
|
3009
|
+
report.customers.failed += 1;
|
|
3010
|
+
report.failures.push({
|
|
3011
|
+
kind: "customer",
|
|
3012
|
+
id: referenceKey,
|
|
3013
|
+
message: error instanceof Error ? error.message : "Failed to migrate customer"
|
|
3014
|
+
});
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
async function migratePaystackSubscriptionSchema(ctx, options) {
|
|
3018
|
+
const adapter = ctx.context.adapter;
|
|
3019
|
+
const report = {
|
|
3020
|
+
status: "complete",
|
|
3021
|
+
subscriptions: {
|
|
3022
|
+
migrated: 0,
|
|
3023
|
+
skipped: 0,
|
|
3024
|
+
failed: 0
|
|
3025
|
+
},
|
|
3026
|
+
customers: {
|
|
3027
|
+
migrated: 0,
|
|
3028
|
+
skipped: 0,
|
|
3029
|
+
failed: 0
|
|
3030
|
+
},
|
|
3031
|
+
credentials: {
|
|
3032
|
+
migrated: 0,
|
|
3033
|
+
skipped: 0,
|
|
3034
|
+
failed: 0
|
|
3035
|
+
},
|
|
3036
|
+
skipped: 0,
|
|
3037
|
+
failures: []
|
|
3038
|
+
};
|
|
3039
|
+
for (const referenceType of ["user", "organization"]) {
|
|
3040
|
+
const records = await findManySafely(adapter, referenceType);
|
|
3041
|
+
for (const record of records) await migrateCustomer(adapter, referenceType, record, report);
|
|
3042
|
+
}
|
|
3043
|
+
const legacySubscriptions = await findManySafely(adapter, LEGACY_PAYSTACK_MODELS.subscription);
|
|
3044
|
+
for (const legacy of legacySubscriptions) {
|
|
3045
|
+
const id = asIdentifier(legacy.id);
|
|
3046
|
+
if (!id) continue;
|
|
3047
|
+
try {
|
|
3048
|
+
if (await adapter.findOne({
|
|
3049
|
+
model: PAYSTACK_MODELS.subscription,
|
|
3050
|
+
where: [{
|
|
3051
|
+
field: "id",
|
|
3052
|
+
value: id
|
|
3053
|
+
}]
|
|
3054
|
+
})) {
|
|
3055
|
+
report.subscriptions.skipped += 1;
|
|
3056
|
+
report.skipped += 1;
|
|
3057
|
+
} else {
|
|
3058
|
+
await adapter.create({
|
|
3059
|
+
model: PAYSTACK_MODELS.subscription,
|
|
3060
|
+
data: migrationData(legacy),
|
|
3061
|
+
forceAllowId: true
|
|
3062
|
+
});
|
|
3063
|
+
report.subscriptions.migrated += 1;
|
|
3064
|
+
}
|
|
3065
|
+
} catch (error) {
|
|
3066
|
+
report.subscriptions.failed += 1;
|
|
3067
|
+
report.failures.push({
|
|
3068
|
+
kind: "subscription",
|
|
3069
|
+
id,
|
|
3070
|
+
message: error instanceof Error ? error.message : "Failed to migrate subscription"
|
|
3071
|
+
});
|
|
3072
|
+
}
|
|
3073
|
+
const authorizationCode = asString(legacy.authorizationCode) ?? asString(legacy.paystackAuthorizationCode);
|
|
3074
|
+
const emailToken = asString(legacy.emailToken) ?? asString(legacy.paystackEmailToken);
|
|
3075
|
+
if (authorizationCode || emailToken) try {
|
|
3076
|
+
if (await adapter.findOne({
|
|
3077
|
+
model: PAYSTACK_MODELS.paymentCredential,
|
|
3078
|
+
where: [{
|
|
3079
|
+
field: "subscriptionId",
|
|
3080
|
+
value: id
|
|
3081
|
+
}]
|
|
3082
|
+
})) {
|
|
3083
|
+
report.credentials.skipped += 1;
|
|
3084
|
+
report.skipped += 1;
|
|
3085
|
+
} else {
|
|
3086
|
+
await savePaystackPaymentCredentials(adapter, options, id, {
|
|
3087
|
+
authorizationCode,
|
|
3088
|
+
emailToken
|
|
3089
|
+
});
|
|
3090
|
+
report.credentials.migrated += 1;
|
|
3091
|
+
}
|
|
3092
|
+
} catch (error) {
|
|
3093
|
+
report.credentials.failed += 1;
|
|
3094
|
+
report.failures.push({
|
|
3095
|
+
kind: "credential",
|
|
3096
|
+
id,
|
|
3097
|
+
message: error instanceof Error ? error.message : "Failed to migrate credential"
|
|
3098
|
+
});
|
|
3099
|
+
}
|
|
3100
|
+
}
|
|
3101
|
+
report.status = report.failures.length > 0 ? "partial" : "complete";
|
|
3102
|
+
return report;
|
|
3103
|
+
}
|
|
3104
|
+
//#endregion
|
|
2575
3105
|
//#region src/index.ts
|
|
2576
3106
|
const INTERNAL_ERROR_CODES = defineErrorCodes(Object.fromEntries(Object.entries(PAYSTACK_ERROR_CODES).map(([key, value]) => [key, typeof value === "string" ? value : value.message])));
|
|
2577
3107
|
const createPaystackPlugin = (options) => {
|
|
@@ -2635,8 +3165,7 @@ const createPaystackPlugin = (options) => {
|
|
|
2635
3165
|
}
|
|
2636
3166
|
} },
|
|
2637
3167
|
update: { async after(user) {
|
|
2638
|
-
const
|
|
2639
|
-
const customerCode = user.paystackCustomerCode ?? persisted?.paystackCustomerCode;
|
|
3168
|
+
const customerCode = (await createBillingStoreFromAdapter(ctx.adapter).findCustomerByReference("user", user.id))?.customerCode;
|
|
2640
3169
|
if (typeof customerCode !== "string" || customerCode === "" || typeof user.email !== "string" || user.email === "") return;
|
|
2641
3170
|
try {
|
|
2642
3171
|
await createPaystackAdapter(options.paystackClient).updateCustomer(customerCode, { email: user.email });
|
|
@@ -2683,7 +3212,7 @@ const createPaystackPlugin = (options) => {
|
|
|
2683
3212
|
} },
|
|
2684
3213
|
update: { async after(org, hookCtx) {
|
|
2685
3214
|
const persisted = await createBillingStoreFromAdapter(ctx.adapter).findOrganization(org.id);
|
|
2686
|
-
const customerCode = org.
|
|
3215
|
+
const customerCode = (await createBillingStoreFromAdapter(ctx.adapter).findCustomerByReference("organization", org.id))?.customerCode;
|
|
2687
3216
|
if (typeof customerCode !== "string" || customerCode === "") return;
|
|
2688
3217
|
try {
|
|
2689
3218
|
const configured = typeof options.organization?.getCustomerCreateParams === "function" && hookCtx ? await options.organization.getCustomerCreateParams({
|
|
@@ -2703,8 +3232,7 @@ const createPaystackPlugin = (options) => {
|
|
|
2703
3232
|
delete: { async before(org) {
|
|
2704
3233
|
const store = createBillingStoreFromAdapter(ctx.adapter);
|
|
2705
3234
|
if ((await store.findSubscriptionsByReference(org.id)).some((subscription) => subscription.status === "active" || subscription.status === "trialing")) throw new APIError("BAD_REQUEST", { message: "Organization cannot be deleted while it has an active subscription" });
|
|
2706
|
-
const
|
|
2707
|
-
const customerCode = org.paystackCustomerCode ?? persisted?.paystackCustomerCode;
|
|
3235
|
+
const customerCode = (await store.findCustomerByReference("organization", org.id))?.customerCode;
|
|
2708
3236
|
if (typeof customerCode !== "string" || customerCode === "") return;
|
|
2709
3237
|
try {
|
|
2710
3238
|
if ((await createPaystackAdapter(options.paystackClient).fetchCustomer(customerCode)).subscriptions?.some((subscription) => subscription.status === "active" || subscription.status === "trialing") === true) throw new APIError("BAD_REQUEST", { message: "Organization cannot be deleted while it has an active subscription" });
|
|
@@ -2755,6 +3283,6 @@ const createPaystackPlugin = (options) => {
|
|
|
2755
3283
|
};
|
|
2756
3284
|
const paystack = createPaystackPlugin;
|
|
2757
3285
|
//#endregion
|
|
2758
|
-
export { chargeSubscriptionRenewal, createCheckoutMetadata, createProrationMetadata, createRenewalMetadata, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasPaystackMetadata, parsePaystackMetadata, paystack, reconcilePaystackTransaction, stringifyPaystackMetadata, syncPaystackPlans, syncPaystackProducts };
|
|
3286
|
+
export { chargeSubscriptionRenewal, createCheckoutMetadata, createProrationMetadata, createRenewalMetadata, getMetadataBoolean, getMetadataNumber, getMetadataString, getOrganizationEntitlements, hasPaystackMetadata, migratePaystackSubscriptionSchema, parsePaystackMetadata, paystack, reconcilePaystackTransaction, stringifyPaystackMetadata, syncPaystackPlans, syncPaystackProducts };
|
|
2759
3287
|
|
|
2760
3288
|
//# sourceMappingURL=index.mjs.map
|