better-auth-paystack 3.2.0 → 3.4.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 +37 -3
- package/dist/client.d.mts +1 -1
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/{index-CXuHlFoy.d.mts → index-ciWwfZ27.d.mts} +55 -4
- package/dist/index-ciWwfZ27.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +699 -552
- package/dist/index.mjs.map +1 -1
- package/dist/{version-BYbIySEf.mjs → version-DbATmzCS.mjs} +2 -2
- package/dist/{version-BYbIySEf.mjs.map → version-DbATmzCS.mjs.map} +1 -1
- package/package.json +18 -25
- 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-CXuHlFoy.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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-DbATmzCS.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 { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
|
|
5
6
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
6
7
|
import { z } from "zod";
|
|
7
|
-
import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
|
|
8
8
|
import { Buffer } from "node:buffer";
|
|
9
9
|
import { mergeSchema } from "better-auth/db";
|
|
10
10
|
//#region src/models.ts
|
|
@@ -263,11 +263,12 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
263
263
|
value: referenceKey
|
|
264
264
|
}]);
|
|
265
265
|
const now = /* @__PURE__ */ new Date();
|
|
266
|
+
const hasEmail = email !== void 0 && email !== null && email !== "";
|
|
266
267
|
if (existing) return await adapter.update({
|
|
267
268
|
model: PAYSTACK_MODELS.customer,
|
|
268
269
|
update: {
|
|
269
270
|
customerCode,
|
|
270
|
-
...
|
|
271
|
+
...hasEmail ? { email } : {},
|
|
271
272
|
updatedAt: now
|
|
272
273
|
},
|
|
273
274
|
where: [{
|
|
@@ -287,7 +288,7 @@ function createBillingStoreFromAdapter(adapter) {
|
|
|
287
288
|
referenceId,
|
|
288
289
|
referenceKey,
|
|
289
290
|
customerCode,
|
|
290
|
-
...
|
|
291
|
+
...hasEmail ? { email } : {},
|
|
291
292
|
createdAt: now,
|
|
292
293
|
updatedAt: now
|
|
293
294
|
}
|
|
@@ -391,6 +392,101 @@ function createPaystackAdapter(client) {
|
|
|
391
392
|
};
|
|
392
393
|
}
|
|
393
394
|
//#endregion
|
|
395
|
+
//#region src/customer.ts
|
|
396
|
+
function isNotFound(error) {
|
|
397
|
+
if (error === null || typeof error !== "object") return false;
|
|
398
|
+
const candidate = error;
|
|
399
|
+
return candidate.status === 404 || candidate.statusCode === 404;
|
|
400
|
+
}
|
|
401
|
+
function customerCode(customer) {
|
|
402
|
+
if (customer === null || typeof customer !== "object") return void 0;
|
|
403
|
+
const code = customer.customer_code;
|
|
404
|
+
return typeof code === "string" && code !== "" ? code : void 0;
|
|
405
|
+
}
|
|
406
|
+
function ownsCustomer(customer, reference) {
|
|
407
|
+
if (customer === null || typeof customer !== "object") return false;
|
|
408
|
+
const metadata = parsePaystackMetadata(customer.metadata);
|
|
409
|
+
const expectedIdKey = reference.type === "user" ? "userId" : "organizationId";
|
|
410
|
+
const otherIdKey = reference.type === "user" ? "organizationId" : "userId";
|
|
411
|
+
return metadata[expectedIdKey] === reference.id && metadata[otherIdKey] === void 0 && (metadata.customerType === void 0 || metadata.customerType === reference.type);
|
|
412
|
+
}
|
|
413
|
+
function hasOwner(customer) {
|
|
414
|
+
if (customer === null || typeof customer !== "object") return false;
|
|
415
|
+
const metadata = parsePaystackMetadata(customer.metadata);
|
|
416
|
+
return typeof metadata.userId === "string" || typeof metadata.organizationId === "string" || typeof metadata.customerType === "string";
|
|
417
|
+
}
|
|
418
|
+
function ownershipMetadata(reference, existing) {
|
|
419
|
+
return stringifyPaystackMetadata({
|
|
420
|
+
...parsePaystackMetadata(existing),
|
|
421
|
+
customerType: reference.type,
|
|
422
|
+
...reference.type === "user" ? { userId: reference.id } : { organizationId: reference.id }
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
async function resolvePaystackCustomer(input) {
|
|
426
|
+
const { adapter, client, logger, reference } = input;
|
|
427
|
+
const store = createBillingStoreFromAdapter(adapter);
|
|
428
|
+
const persisted = await store.findCustomerByReference(reference.type, reference.id);
|
|
429
|
+
let legacyCode;
|
|
430
|
+
try {
|
|
431
|
+
legacyCode = (await adapter.findOne({
|
|
432
|
+
model: reference.type,
|
|
433
|
+
where: [{
|
|
434
|
+
field: "id",
|
|
435
|
+
value: reference.id
|
|
436
|
+
}],
|
|
437
|
+
select: ["paystackCustomerCode"]
|
|
438
|
+
}))?.paystackCustomerCode ?? void 0;
|
|
439
|
+
} catch {}
|
|
440
|
+
const existingCode = reference.paystackCustomerCode ?? persisted?.customerCode ?? legacyCode;
|
|
441
|
+
if (typeof existingCode === "string" && existingCode !== "") {
|
|
442
|
+
if (persisted === null) await store.saveCustomer(reference.type, reference.id, existingCode, reference.email);
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
const sdk = createPaystackAdapter(client);
|
|
446
|
+
let existing = null;
|
|
447
|
+
if (typeof client.customer?.fetch === "function") try {
|
|
448
|
+
existing = await sdk.fetchCustomer(reference.email) ?? null;
|
|
449
|
+
} catch (error) {
|
|
450
|
+
if (!isNotFound(error)) {
|
|
451
|
+
logger.error("Failed to look up Paystack customer; customer creation was skipped", error);
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (existing !== null) {
|
|
456
|
+
const code = customerCode(existing);
|
|
457
|
+
if (code === void 0) {
|
|
458
|
+
logger.error("Paystack customer lookup returned no customer code");
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
const owned = ownsCustomer(existing, reference);
|
|
462
|
+
const canClaimLegacy = reference.type === "user" && reference.emailVerified === true && !hasOwner(existing);
|
|
463
|
+
if (!owned && !canClaimLegacy) {
|
|
464
|
+
logger.error("Paystack customer belongs to another billing reference");
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
const existingMetadata = existing.metadata;
|
|
468
|
+
if (canClaimLegacy || parsePaystackMetadata(existingMetadata).customerType !== reference.type) await sdk.updateCustomer(code, { metadata: ownershipMetadata(reference, existingMetadata) });
|
|
469
|
+
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
470
|
+
return {
|
|
471
|
+
customer: existing,
|
|
472
|
+
created: false
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
const customer = await sdk.createCustomer({
|
|
476
|
+
...input.createParams,
|
|
477
|
+
email: reference.email,
|
|
478
|
+
first_name: reference.name ?? void 0,
|
|
479
|
+
metadata: ownershipMetadata(reference)
|
|
480
|
+
});
|
|
481
|
+
const code = customerCode(customer);
|
|
482
|
+
if (code === void 0) return null;
|
|
483
|
+
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
484
|
+
return {
|
|
485
|
+
customer,
|
|
486
|
+
created: true
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
//#endregion
|
|
394
490
|
//#region src/utils.ts
|
|
395
491
|
function getPlanSeatAmount(plan) {
|
|
396
492
|
if (plan.seatAmount !== void 0) {
|
|
@@ -530,6 +626,37 @@ async function syncSubscriptionSeats(ctx, organizationId, options) {
|
|
|
530
626
|
}
|
|
531
627
|
}
|
|
532
628
|
//#endregion
|
|
629
|
+
//#region src/limits.ts
|
|
630
|
+
const getOrganizationSubscription = async (ctx, organizationId, groupId) => {
|
|
631
|
+
return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);
|
|
632
|
+
};
|
|
633
|
+
const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
|
|
634
|
+
const store = createBillingStore(ctx);
|
|
635
|
+
const seatLimit = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing").reduce((maximum, subscription) => typeof subscription.seats === "number" ? Math.max(maximum ?? subscription.seats, subscription.seats) : maximum, void 0);
|
|
636
|
+
const members = await store.listMembers(organizationId);
|
|
637
|
+
if (seatLimit === void 0) return true;
|
|
638
|
+
if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
|
|
639
|
+
return true;
|
|
640
|
+
};
|
|
641
|
+
async function getOrganizationEntitlements(ctx, organizationId, options) {
|
|
642
|
+
const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
|
|
643
|
+
const limits = {};
|
|
644
|
+
const features = /* @__PURE__ */ new Set();
|
|
645
|
+
for (const subscription of subscriptions) {
|
|
646
|
+
const plan = await getPlanByName(options, subscription.plan);
|
|
647
|
+
for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
|
|
648
|
+
for (const feature of plan?.features ?? []) features.add(feature);
|
|
649
|
+
}
|
|
650
|
+
return {
|
|
651
|
+
limits,
|
|
652
|
+
features: [...features]
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
|
|
656
|
+
if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
|
|
657
|
+
return true;
|
|
658
|
+
};
|
|
659
|
+
//#endregion
|
|
533
660
|
//#region src/reference-access.ts
|
|
534
661
|
const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
|
|
535
662
|
function normalizeBillingRoles(roles) {
|
|
@@ -599,37 +726,6 @@ const referenceMiddleware = (options, action) => createAuthMiddleware(async (ctx
|
|
|
599
726
|
} };
|
|
600
727
|
});
|
|
601
728
|
//#endregion
|
|
602
|
-
//#region src/limits.ts
|
|
603
|
-
const getOrganizationSubscription = async (ctx, organizationId, groupId) => {
|
|
604
|
-
return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);
|
|
605
|
-
};
|
|
606
|
-
const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
|
|
607
|
-
const store = createBillingStore(ctx);
|
|
608
|
-
const seatLimit = (await store.findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing").reduce((maximum, subscription) => typeof subscription.seats === "number" ? Math.max(maximum ?? subscription.seats, subscription.seats) : maximum, void 0);
|
|
609
|
-
const members = await store.listMembers(organizationId);
|
|
610
|
-
if (seatLimit === void 0) return true;
|
|
611
|
-
if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
|
|
612
|
-
return true;
|
|
613
|
-
};
|
|
614
|
-
async function getOrganizationEntitlements(ctx, organizationId, options) {
|
|
615
|
-
const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
|
|
616
|
-
const limits = {};
|
|
617
|
-
const features = /* @__PURE__ */ new Set();
|
|
618
|
-
for (const subscription of subscriptions) {
|
|
619
|
-
const plan = await getPlanByName(options, subscription.plan);
|
|
620
|
-
for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
|
|
621
|
-
for (const feature of plan?.features ?? []) features.add(feature);
|
|
622
|
-
}
|
|
623
|
-
return {
|
|
624
|
-
limits,
|
|
625
|
-
features: [...features]
|
|
626
|
-
};
|
|
627
|
-
}
|
|
628
|
-
const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
|
|
629
|
-
if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
|
|
630
|
-
return true;
|
|
631
|
-
};
|
|
632
|
-
//#endregion
|
|
633
729
|
//#region src/credential-crypto.ts
|
|
634
730
|
const ALGORITHM = "aes-256-gcm";
|
|
635
731
|
const VERSION = "v1";
|
|
@@ -685,9 +781,11 @@ async function readPaystackPaymentCredentials(adapter, options, subscriptionId)
|
|
|
685
781
|
}
|
|
686
782
|
if (!row) return null;
|
|
687
783
|
const key = resolveCredentialEncryptionKey(options);
|
|
784
|
+
const authorizationCodeEncrypted = row.authorizationCodeEncrypted;
|
|
785
|
+
const emailTokenEncrypted = row.emailTokenEncrypted;
|
|
688
786
|
return {
|
|
689
|
-
authorizationCode:
|
|
690
|
-
emailToken:
|
|
787
|
+
authorizationCode: typeof authorizationCodeEncrypted === "string" && authorizationCodeEncrypted !== "" ? decryptPaystackCredential(authorizationCodeEncrypted, key) : void 0,
|
|
788
|
+
emailToken: typeof emailTokenEncrypted === "string" && emailTokenEncrypted !== "" ? decryptPaystackCredential(emailTokenEncrypted, key) : void 0
|
|
691
789
|
};
|
|
692
790
|
}
|
|
693
791
|
async function savePaystackPaymentCredentials(adapter, options, subscriptionId, values) {
|
|
@@ -732,256 +830,28 @@ async function savePaystackPaymentCredentials(adapter, options, subscriptionId,
|
|
|
732
830
|
});
|
|
733
831
|
}
|
|
734
832
|
//#endregion
|
|
735
|
-
//#region src/
|
|
736
|
-
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
|
|
740
|
-
if (existingSub?.status === "active") {
|
|
741
|
-
await ctx.context.adapter.update({
|
|
742
|
-
model: PAYSTACK_MODELS.subscription,
|
|
743
|
-
where: [{
|
|
744
|
-
field: "id",
|
|
745
|
-
value: existingSub.id
|
|
746
|
-
}],
|
|
747
|
-
update: {
|
|
748
|
-
pendingPlan: input.plan.name,
|
|
749
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
750
|
-
}
|
|
751
|
-
});
|
|
752
|
-
return {
|
|
753
|
-
kind: "scheduled",
|
|
754
|
-
status: "success",
|
|
755
|
-
message: "Plan change scheduled at period end.",
|
|
756
|
-
scheduled: true
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
if (input.cancelAtPeriodEnd === true) {
|
|
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);
|
|
762
|
-
if (existingSub?.status === "active") {
|
|
763
|
-
await ctx.context.adapter.update({
|
|
764
|
-
model: PAYSTACK_MODELS.subscription,
|
|
765
|
-
where: [{
|
|
766
|
-
field: "id",
|
|
767
|
-
value: existingSub.id
|
|
768
|
-
}],
|
|
769
|
-
update: {
|
|
770
|
-
cancelAtPeriodEnd: true,
|
|
771
|
-
cancelAt: existingSub.periodEnd ?? null,
|
|
772
|
-
canceledAt: /* @__PURE__ */ new Date(),
|
|
773
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
774
|
-
}
|
|
775
|
-
});
|
|
776
|
-
return {
|
|
777
|
-
kind: "scheduled",
|
|
778
|
-
status: "success",
|
|
779
|
-
message: "Subscription cancellation scheduled at period end.",
|
|
780
|
-
scheduled: true
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
return null;
|
|
833
|
+
//#region src/reconciliation.ts
|
|
834
|
+
function getAllowedSubscriptionChannels$1(options) {
|
|
835
|
+
const channels = options.subscription?.allowedPaymentChannels;
|
|
836
|
+
return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
|
|
785
837
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
requested: false,
|
|
792
|
-
granted: false
|
|
793
|
-
};
|
|
794
|
-
if ((await ctx.context.adapter.findMany({
|
|
795
|
-
model: PAYSTACK_MODELS.subscription,
|
|
796
|
-
where: [{
|
|
797
|
-
field: "referenceId",
|
|
798
|
-
value: input.referenceId
|
|
799
|
-
}]
|
|
800
|
-
}))?.some((subscription) => subscription.trialStart !== void 0 && subscription.trialStart !== null || subscription.trialEnd !== void 0 && subscription.trialEnd !== null || subscription.status === "trialing") === true) return {
|
|
801
|
-
requestedDays,
|
|
802
|
-
requested,
|
|
803
|
-
granted: false,
|
|
804
|
-
deniedReason: "already_used"
|
|
805
|
-
};
|
|
806
|
-
const trialStart = /* @__PURE__ */ new Date();
|
|
807
|
-
const trialEnd = /* @__PURE__ */ new Date();
|
|
808
|
-
trialEnd.setDate(trialEnd.getDate() + requestedDays);
|
|
838
|
+
function isAllowedSubscriptionChannel(channel, allowedChannels) {
|
|
839
|
+
if (allowedChannels === void 0) return true;
|
|
840
|
+
return channel !== void 0 && channel !== null && allowedChannels.includes(channel);
|
|
841
|
+
}
|
|
842
|
+
function createSummary() {
|
|
809
843
|
return {
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
model: "organization",
|
|
822
|
-
where: [{
|
|
823
|
-
field: "id",
|
|
824
|
-
value: input.referenceId
|
|
825
|
-
}]
|
|
826
|
-
});
|
|
827
|
-
if (org === void 0 || org === null) return targetEmail;
|
|
828
|
-
const orgWithEmail = org;
|
|
829
|
-
if (orgWithEmail.email !== void 0 && orgWithEmail.email !== null && orgWithEmail.email !== "") return orgWithEmail.email;
|
|
830
|
-
const ownerMember = await ctx.context.adapter.findOne({
|
|
831
|
-
model: "member",
|
|
832
|
-
where: [{
|
|
833
|
-
field: "organizationId",
|
|
834
|
-
value: input.referenceId
|
|
835
|
-
}, {
|
|
836
|
-
field: "role",
|
|
837
|
-
value: "owner"
|
|
838
|
-
}]
|
|
839
|
-
});
|
|
840
|
-
if (ownerMember === void 0 || ownerMember === null) return targetEmail;
|
|
841
|
-
const ownerUser = await ctx.context.adapter.findOne({
|
|
842
|
-
model: "user",
|
|
843
|
-
where: [{
|
|
844
|
-
field: "id",
|
|
845
|
-
value: ownerMember.userId
|
|
846
|
-
}]
|
|
847
|
-
});
|
|
848
|
-
return ownerUser?.email !== void 0 && ownerUser.email !== "" ? ownerUser.email : targetEmail;
|
|
849
|
-
}
|
|
850
|
-
async function handleProratedUpgrade(ctx, options, input) {
|
|
851
|
-
const store = createBillingStore(ctx);
|
|
852
|
-
const existingSub = input.subscriptionId === void 0 ? await store.findCurrentSubscription(input.referenceId, normalizeSubscriptionGroup(input.plan.group)) : await store.findSubscriptionById(input.subscriptionId);
|
|
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;
|
|
854
|
-
const now = /* @__PURE__ */ new Date();
|
|
855
|
-
const periodEnd = new Date(existingSub.periodEnd);
|
|
856
|
-
const periodStart = new Date(existingSub.periodStart);
|
|
857
|
-
const totalDays = Math.max(1, Math.ceil((periodEnd.getTime() - periodStart.getTime()) / (1e3 * 60 * 60 * 24)));
|
|
858
|
-
const remainingDays = Math.max(0, Math.ceil((periodEnd.getTime() - now.getTime()) / (1e3 * 60 * 60 * 24)));
|
|
859
|
-
let oldAmount = 0;
|
|
860
|
-
if (existingSub.plan !== "") {
|
|
861
|
-
const oldPlan = await getPlanByName(options, existingSub.plan) ?? await store.findPlanByName(existingSub.plan);
|
|
862
|
-
if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats ?? 1);
|
|
863
|
-
}
|
|
864
|
-
let membersCount = 1;
|
|
865
|
-
let newSeatCount;
|
|
866
|
-
let newAmount;
|
|
867
|
-
try {
|
|
868
|
-
assertLocallyManagedSubscription(existingSub, "plan or seat changes");
|
|
869
|
-
if (getPlanSeatAmount(input.plan) !== void 0) {
|
|
870
|
-
const members = await store.listMembers(input.referenceId);
|
|
871
|
-
membersCount = members.length > 0 ? members.length : 1;
|
|
872
|
-
}
|
|
873
|
-
newSeatCount = input.quantity ?? existingSub.seats ?? membersCount;
|
|
874
|
-
newAmount = calculatePlanAmount(input.plan, newSeatCount);
|
|
875
|
-
} catch (error) {
|
|
876
|
-
throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
|
|
877
|
-
}
|
|
878
|
-
const costDifference = newAmount - oldAmount;
|
|
879
|
-
const serializedProrationMetadata = stringifyPaystackMetadata(createProrationMetadata({
|
|
880
|
-
subscriptionId: existingSub.id,
|
|
881
|
-
referenceId: input.referenceId,
|
|
882
|
-
newPlan: input.plan.name.toLowerCase(),
|
|
883
|
-
oldPlan: existingSub.plan,
|
|
884
|
-
newSeatCount,
|
|
885
|
-
remainingDays
|
|
886
|
-
}));
|
|
887
|
-
let completedProrationReference;
|
|
888
|
-
if (costDifference > 0 && remainingDays > 0) {
|
|
889
|
-
const proratedAmount = Math.round(costDifference / totalDays * remainingDays);
|
|
890
|
-
if (proratedAmount < 5e3) throw new APIError("BAD_REQUEST", {
|
|
891
|
-
message: "Prorated upgrade amount is below Paystack's minimum charge. Schedule the change for period end instead.",
|
|
892
|
-
status: 400
|
|
893
|
-
});
|
|
894
|
-
const paystack = createPaystackAdapter(options.paystackClient);
|
|
895
|
-
const credentials = await readPaystackPaymentCredentials(ctx.context.adapter, options, existingSub.id);
|
|
896
|
-
if (credentials?.authorizationCode) {
|
|
897
|
-
const sdkRes = await paystack.chargeAuthorization({
|
|
898
|
-
email: input.targetEmail,
|
|
899
|
-
amount: proratedAmount,
|
|
900
|
-
authorization_code: credentials.authorizationCode,
|
|
901
|
-
reference: `upg_${existingSub.id}_${Date.now()}_${Math.random().toString(36).substring(7)}`,
|
|
902
|
-
metadata: serializedProrationMetadata
|
|
903
|
-
});
|
|
904
|
-
if (sdkRes?.status !== "success") throw new APIError("BAD_REQUEST", { message: "Failed to process prorated charge via saved authorization." });
|
|
905
|
-
await store.createTransaction({
|
|
906
|
-
reference: sdkRes.reference ?? "",
|
|
907
|
-
paystackId: sdkRes.id !== void 0 && sdkRes.id !== null ? String(sdkRes.id) : void 0,
|
|
908
|
-
referenceId: input.referenceId,
|
|
909
|
-
userId: input.userId,
|
|
910
|
-
amount: sdkRes.amount ?? proratedAmount,
|
|
911
|
-
currency: sdkRes.currency ?? input.finalCurrency,
|
|
912
|
-
status: "success",
|
|
913
|
-
plan: input.plan.name.toLowerCase(),
|
|
914
|
-
metadata: serializedProrationMetadata,
|
|
915
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
916
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
917
|
-
});
|
|
918
|
-
completedProrationReference = sdkRes.reference ?? void 0;
|
|
919
|
-
} else {
|
|
920
|
-
const initRes = await paystack.initializeTransaction({
|
|
921
|
-
email: input.targetEmail,
|
|
922
|
-
amount: proratedAmount,
|
|
923
|
-
currency: input.finalCurrency,
|
|
924
|
-
callback_url: input.callbackURL ?? void 0,
|
|
925
|
-
metadata: serializedProrationMetadata,
|
|
926
|
-
...input.allowedSubscriptionChannels !== void 0 ? { channels: input.allowedSubscriptionChannels } : {}
|
|
927
|
-
});
|
|
928
|
-
await store.createTransaction({
|
|
929
|
-
reference: initRes?.reference ?? "",
|
|
930
|
-
referenceId: input.referenceId,
|
|
931
|
-
userId: input.userId,
|
|
932
|
-
amount: proratedAmount,
|
|
933
|
-
currency: input.finalCurrency,
|
|
934
|
-
status: "pending",
|
|
935
|
-
plan: input.plan.name.toLowerCase(),
|
|
936
|
-
metadata: serializedProrationMetadata,
|
|
937
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
938
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
939
|
-
});
|
|
940
|
-
return {
|
|
941
|
-
kind: "checkout",
|
|
942
|
-
url: initRes?.authorization_url,
|
|
943
|
-
reference: initRes?.reference,
|
|
944
|
-
accessCode: initRes?.access_code,
|
|
945
|
-
redirect: true
|
|
946
|
-
};
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
await store.updateSubscription(existingSub.id, {
|
|
950
|
-
plan: input.plan.name,
|
|
951
|
-
seats: newSeatCount,
|
|
952
|
-
...completedProrationReference !== void 0 ? { transactionReference: completedProrationReference } : {},
|
|
953
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
954
|
-
});
|
|
955
|
-
return {
|
|
956
|
-
kind: "prorated",
|
|
957
|
-
status: "success",
|
|
958
|
-
message: "Subscription successfully upgraded with prorated charge.",
|
|
959
|
-
prorated: true
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
//#endregion
|
|
963
|
-
//#region src/reconciliation.ts
|
|
964
|
-
function getAllowedSubscriptionChannels$1(options) {
|
|
965
|
-
const channels = options.subscription?.allowedPaymentChannels;
|
|
966
|
-
return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
|
|
967
|
-
}
|
|
968
|
-
function isAllowedSubscriptionChannel(channel, allowedChannels) {
|
|
969
|
-
if (allowedChannels === void 0) return true;
|
|
970
|
-
return channel !== void 0 && channel !== null && allowedChannels.includes(channel);
|
|
971
|
-
}
|
|
972
|
-
function createSummary() {
|
|
973
|
-
return {
|
|
974
|
-
transaction: {
|
|
975
|
-
found: false,
|
|
976
|
-
updated: false
|
|
977
|
-
},
|
|
978
|
-
subscription: {
|
|
979
|
-
found: false,
|
|
980
|
-
updated: false,
|
|
981
|
-
prorationApplied: false
|
|
982
|
-
},
|
|
983
|
-
customer: { saved: false },
|
|
984
|
-
product: { synced: false }
|
|
844
|
+
transaction: {
|
|
845
|
+
found: false,
|
|
846
|
+
updated: false
|
|
847
|
+
},
|
|
848
|
+
subscription: {
|
|
849
|
+
found: false,
|
|
850
|
+
updated: false,
|
|
851
|
+
prorationApplied: false
|
|
852
|
+
},
|
|
853
|
+
customer: { saved: false },
|
|
854
|
+
product: { synced: false }
|
|
985
855
|
};
|
|
986
856
|
}
|
|
987
857
|
function getErrorMessage(error, fallback) {
|
|
@@ -1187,7 +1057,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1187
1057
|
summary.subscription.id = updatedSubscription?.id ?? subscriptionId;
|
|
1188
1058
|
summary.subscription.status = updatedSubscription?.status;
|
|
1189
1059
|
summary.subscription.prorationApplied = updatedSubscription !== null;
|
|
1190
|
-
if (updatedSubscription && authorizationCode) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1060
|
+
if (updatedSubscription !== null && authorizationCode !== void 0 && authorizationCode !== null && authorizationCode !== "") await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1191
1061
|
}
|
|
1192
1062
|
return {
|
|
1193
1063
|
ok: true,
|
|
@@ -1237,7 +1107,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1237
1107
|
summary.subscription.updated = updatedSubscription !== null;
|
|
1238
1108
|
summary.subscription.id = updatedSubscription?.id ?? targetSub.id;
|
|
1239
1109
|
summary.subscription.status = updatedSubscription?.status ?? targetSub.status;
|
|
1240
|
-
if (authorizationCode && updatedSubscription !== null) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1110
|
+
if (authorizationCode !== void 0 && authorizationCode !== null && authorizationCode !== "" && updatedSubscription !== null) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
|
|
1241
1111
|
if (updatedSubscription !== null && (updatedSubscription.status === "active" || updatedSubscription.status === "trialing")) await store.retireCompetingSubscriptions(updatedSubscription.referenceId, updatedSubscription.groupId ?? null, updatedSubscription.id);
|
|
1242
1112
|
}
|
|
1243
1113
|
if (updatedSubscription !== void 0 && updatedSubscription !== null) {
|
|
@@ -1270,6 +1140,20 @@ async function reconcilePaystackTransaction(ctx, options, input) {
|
|
|
1270
1140
|
};
|
|
1271
1141
|
}
|
|
1272
1142
|
//#endregion
|
|
1143
|
+
//#region src/route-modules/catalog.ts
|
|
1144
|
+
async function listStoredProducts(ctx) {
|
|
1145
|
+
return createBillingStore(ctx).listProducts();
|
|
1146
|
+
}
|
|
1147
|
+
async function listStoredPlans(ctx) {
|
|
1148
|
+
return createBillingStore(ctx).listPlans();
|
|
1149
|
+
}
|
|
1150
|
+
async function getConfiguredCatalog(options) {
|
|
1151
|
+
return {
|
|
1152
|
+
plans: options.subscription?.enabled === true ? await getPlans(options.subscription) : [],
|
|
1153
|
+
products: await getProducts(options.products)
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
//#endregion
|
|
1273
1157
|
//#region src/route-modules/checkout.ts
|
|
1274
1158
|
const initializeTransactionBodySchema = z.object({
|
|
1275
1159
|
plan: z.string().optional(),
|
|
@@ -1287,18 +1171,38 @@ const initializeTransactionBodySchema = z.object({
|
|
|
1287
1171
|
prorateAndCharge: z.boolean().optional()
|
|
1288
1172
|
});
|
|
1289
1173
|
//#endregion
|
|
1290
|
-
//#region src/route-modules/
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1174
|
+
//#region src/route-modules/shared.ts
|
|
1175
|
+
const PAYSTACK_ERROR_CODES = defineErrorCodes({
|
|
1176
|
+
SUBSCRIPTION_NOT_FOUND: "Subscription not found",
|
|
1177
|
+
SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
|
|
1178
|
+
UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
|
|
1179
|
+
FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
|
|
1180
|
+
FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
|
|
1181
|
+
FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
|
|
1182
|
+
FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
|
|
1183
|
+
EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
|
|
1184
|
+
SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
|
|
1185
|
+
});
|
|
1186
|
+
function getAllowedSubscriptionChannels(options) {
|
|
1187
|
+
const channels = options.subscription?.allowedPaymentChannels;
|
|
1188
|
+
return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
|
|
1296
1189
|
}
|
|
1297
|
-
async function
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1190
|
+
async function hmacSha512Hex(secret, message) {
|
|
1191
|
+
const encoder = new TextEncoder();
|
|
1192
|
+
const keyData = encoder.encode(secret);
|
|
1193
|
+
const msgData = encoder.encode(message);
|
|
1194
|
+
const crypto = globalThis.crypto;
|
|
1195
|
+
if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
|
|
1196
|
+
const subtle = crypto.subtle;
|
|
1197
|
+
const key = await subtle.importKey("raw", keyData, {
|
|
1198
|
+
name: "HMAC",
|
|
1199
|
+
hash: "SHA-512"
|
|
1200
|
+
}, false, ["sign"]);
|
|
1201
|
+
const signature = await subtle.sign("HMAC", key, msgData);
|
|
1202
|
+
return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1203
|
+
}
|
|
1204
|
+
const { createHmac } = await import("node:crypto");
|
|
1205
|
+
return createHmac("sha512", secret).update(message).digest("hex");
|
|
1302
1206
|
}
|
|
1303
1207
|
//#endregion
|
|
1304
1208
|
//#region src/route-modules/subscriptions.ts
|
|
@@ -1341,38 +1245,321 @@ function getWebhookClientIP(ctx, headers) {
|
|
|
1341
1245
|
return headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers?.get("x-real-ip") ?? ctx.request.ip;
|
|
1342
1246
|
}
|
|
1343
1247
|
//#endregion
|
|
1344
|
-
//#region src/
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
});
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1248
|
+
//#region src/subscription-lifecycle.ts
|
|
1249
|
+
/** Keep reservation context invocation-local, including concurrent requests through one plugin. */
|
|
1250
|
+
async function runSubscriptionOperation(ctx, options, operation, run) {
|
|
1251
|
+
const hooks = options?.subscription?.operationHooks;
|
|
1252
|
+
if (hooks === void 0) return run(void 0, () => void 0);
|
|
1253
|
+
const decision = await hooks.before(operation, ctx);
|
|
1254
|
+
if (decision.kind === "replay") {
|
|
1255
|
+
if (!(operation.kind === "schedule" ? decision.result.kind === "scheduled" : operation.kind === "initialize" ? decision.result.kind === "checkout" : operation.kind === "local-change" ? decision.result.kind === "prorated" : decision.result.kind === "checkout" || decision.result.kind === "prorated")) throw new APIError("BAD_REQUEST", { message: "Operation replay does not match the validated operation kind." });
|
|
1256
|
+
return decision.result;
|
|
1257
|
+
}
|
|
1258
|
+
if (decision.kind === "block") throw new APIError("CONFLICT", { message: decision.message ?? "Subscription operation is blocked." });
|
|
1259
|
+
if (decision.kind !== "proceed" || typeof decision.providerReference !== "string" || decision.providerReference.trim() === "") throw new APIError("BAD_REQUEST", { message: "Operation hook must reserve a provider reference." });
|
|
1260
|
+
const invocation = {
|
|
1261
|
+
...operation,
|
|
1262
|
+
providerReference: decision.providerReference,
|
|
1263
|
+
context: decision.context
|
|
1264
|
+
};
|
|
1265
|
+
let phase = operation.kind === "schedule" || operation.kind === "local-change" ? "persistence" : "provider";
|
|
1266
|
+
try {
|
|
1267
|
+
const result = await run(decision.providerReference, (next) => {
|
|
1268
|
+
phase = next;
|
|
1269
|
+
});
|
|
1270
|
+
phase = "completion";
|
|
1271
|
+
await hooks.after?.({
|
|
1272
|
+
...invocation,
|
|
1273
|
+
result
|
|
1274
|
+
}, ctx);
|
|
1275
|
+
return result;
|
|
1276
|
+
} catch (error) {
|
|
1277
|
+
try {
|
|
1278
|
+
await hooks.onError?.({
|
|
1279
|
+
...invocation,
|
|
1280
|
+
phase,
|
|
1281
|
+
error
|
|
1282
|
+
}, ctx);
|
|
1283
|
+
} catch {
|
|
1284
|
+
ctx.context.logger.error("Paystack operation error hook failed", { phase });
|
|
1285
|
+
}
|
|
1286
|
+
throw error;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
async function scheduleSubscriptionLifecycleChange(ctx, input, options) {
|
|
1290
|
+
const groupId = normalizeSubscriptionGroup(input.plan?.group);
|
|
1291
|
+
if (input.plan !== void 0 && input.scheduleAtPeriodEnd === true) {
|
|
1292
|
+
const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
|
|
1293
|
+
if (existingSub?.status === "active") return runSubscriptionOperation(ctx, options, {
|
|
1294
|
+
actor: { id: input.userId ?? existingSub.userId },
|
|
1295
|
+
referenceId: input.referenceId,
|
|
1296
|
+
kind: "schedule",
|
|
1297
|
+
subscription: existingSub,
|
|
1298
|
+
intent: {
|
|
1299
|
+
plan: input.plan?.name ?? existingSub.plan,
|
|
1300
|
+
interval: input.plan?.interval ?? existingSub.billingInterval ?? void 0,
|
|
1301
|
+
groupId,
|
|
1302
|
+
scheduleAtPeriodEnd: input.scheduleAtPeriodEnd,
|
|
1303
|
+
cancelAtPeriodEnd: input.cancelAtPeriodEnd
|
|
1304
|
+
}
|
|
1305
|
+
}, async () => {
|
|
1306
|
+
await ctx.context.adapter.update({
|
|
1307
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1308
|
+
where: [{
|
|
1309
|
+
field: "id",
|
|
1310
|
+
value: existingSub.id
|
|
1311
|
+
}],
|
|
1312
|
+
update: {
|
|
1313
|
+
pendingPlan: input.plan?.name,
|
|
1314
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1315
|
+
}
|
|
1316
|
+
});
|
|
1317
|
+
return {
|
|
1318
|
+
kind: "scheduled",
|
|
1319
|
+
status: "success",
|
|
1320
|
+
message: "Plan change scheduled at period end.",
|
|
1321
|
+
scheduled: true
|
|
1322
|
+
};
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
if (input.cancelAtPeriodEnd === true) {
|
|
1326
|
+
const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, input.plan === void 0 ? void 0 : groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
|
|
1327
|
+
if (existingSub?.status === "active") return runSubscriptionOperation(ctx, options, {
|
|
1328
|
+
actor: { id: input.userId ?? existingSub.userId },
|
|
1329
|
+
referenceId: input.referenceId,
|
|
1330
|
+
kind: "schedule",
|
|
1331
|
+
subscription: existingSub,
|
|
1332
|
+
intent: {
|
|
1333
|
+
plan: input.plan?.name ?? existingSub.plan,
|
|
1334
|
+
interval: input.plan?.interval ?? existingSub.billingInterval ?? void 0,
|
|
1335
|
+
groupId,
|
|
1336
|
+
scheduleAtPeriodEnd: input.scheduleAtPeriodEnd,
|
|
1337
|
+
cancelAtPeriodEnd: input.cancelAtPeriodEnd
|
|
1338
|
+
}
|
|
1339
|
+
}, async () => {
|
|
1340
|
+
await ctx.context.adapter.update({
|
|
1341
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1342
|
+
where: [{
|
|
1343
|
+
field: "id",
|
|
1344
|
+
value: existingSub.id
|
|
1345
|
+
}],
|
|
1346
|
+
update: {
|
|
1347
|
+
cancelAtPeriodEnd: true,
|
|
1348
|
+
cancelAt: existingSub.periodEnd ?? null,
|
|
1349
|
+
canceledAt: /* @__PURE__ */ new Date(),
|
|
1350
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1351
|
+
}
|
|
1352
|
+
});
|
|
1353
|
+
return {
|
|
1354
|
+
kind: "scheduled",
|
|
1355
|
+
status: "success",
|
|
1356
|
+
message: "Subscription cancellation scheduled at period end.",
|
|
1357
|
+
scheduled: true
|
|
1358
|
+
};
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
return null;
|
|
1362
|
+
}
|
|
1363
|
+
async function resolveTrialLifecycle(ctx, input) {
|
|
1364
|
+
const requestedDays = input.plan?.freeTrial?.days !== void 0 && input.plan.freeTrial.days > 0 ? input.plan.freeTrial.days : 0;
|
|
1365
|
+
const requested = requestedDays > 0;
|
|
1366
|
+
if (!requested) return {
|
|
1367
|
+
requestedDays,
|
|
1368
|
+
requested: false,
|
|
1369
|
+
granted: false
|
|
1370
|
+
};
|
|
1371
|
+
if ((await ctx.context.adapter.findMany({
|
|
1372
|
+
model: PAYSTACK_MODELS.subscription,
|
|
1373
|
+
where: [{
|
|
1374
|
+
field: "referenceId",
|
|
1375
|
+
value: input.referenceId
|
|
1376
|
+
}]
|
|
1377
|
+
}))?.some((subscription) => subscription.trialStart !== void 0 && subscription.trialStart !== null || subscription.trialEnd !== void 0 && subscription.trialEnd !== null || subscription.status === "trialing") === true) return {
|
|
1378
|
+
requestedDays,
|
|
1379
|
+
requested,
|
|
1380
|
+
granted: false,
|
|
1381
|
+
deniedReason: "already_used"
|
|
1382
|
+
};
|
|
1383
|
+
const trialStart = /* @__PURE__ */ new Date();
|
|
1384
|
+
const trialEnd = /* @__PURE__ */ new Date();
|
|
1385
|
+
trialEnd.setDate(trialEnd.getDate() + requestedDays);
|
|
1386
|
+
return {
|
|
1387
|
+
trialStart,
|
|
1388
|
+
trialEnd,
|
|
1389
|
+
requestedDays,
|
|
1390
|
+
requested,
|
|
1391
|
+
granted: true
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
async function resolveCheckoutTargetEmail(ctx, options, input) {
|
|
1395
|
+
const targetEmail = input.email ?? input.user.email;
|
|
1396
|
+
if (options.organization?.enabled !== true || input.referenceId === input.user.id || input.referenceId === "") return targetEmail;
|
|
1397
|
+
const org = await ctx.context.adapter.findOne({
|
|
1398
|
+
model: "organization",
|
|
1399
|
+
where: [{
|
|
1400
|
+
field: "id",
|
|
1401
|
+
value: input.referenceId
|
|
1402
|
+
}]
|
|
1403
|
+
});
|
|
1404
|
+
if (org === void 0 || org === null) return targetEmail;
|
|
1405
|
+
const orgWithEmail = org;
|
|
1406
|
+
if (orgWithEmail.email !== void 0 && orgWithEmail.email !== null && orgWithEmail.email !== "") return orgWithEmail.email;
|
|
1407
|
+
const ownerMember = await ctx.context.adapter.findOne({
|
|
1408
|
+
model: "member",
|
|
1409
|
+
where: [{
|
|
1410
|
+
field: "organizationId",
|
|
1411
|
+
value: input.referenceId
|
|
1412
|
+
}, {
|
|
1413
|
+
field: "role",
|
|
1414
|
+
value: "owner"
|
|
1415
|
+
}]
|
|
1416
|
+
});
|
|
1417
|
+
if (ownerMember === void 0 || ownerMember === null) return targetEmail;
|
|
1418
|
+
const ownerUser = await ctx.context.adapter.findOne({
|
|
1419
|
+
model: "user",
|
|
1420
|
+
where: [{
|
|
1421
|
+
field: "id",
|
|
1422
|
+
value: ownerMember.userId
|
|
1423
|
+
}]
|
|
1424
|
+
});
|
|
1425
|
+
return ownerUser?.email !== void 0 && ownerUser.email !== "" ? ownerUser.email : targetEmail;
|
|
1359
1426
|
}
|
|
1360
|
-
async function
|
|
1361
|
-
const
|
|
1362
|
-
const
|
|
1363
|
-
|
|
1364
|
-
const
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
const
|
|
1372
|
-
|
|
1427
|
+
async function handleProratedUpgrade(ctx, options, input) {
|
|
1428
|
+
const store = createBillingStore(ctx);
|
|
1429
|
+
const existingSub = input.subscriptionId === void 0 ? await store.findCurrentSubscription(input.referenceId, normalizeSubscriptionGroup(input.plan.group)) : await store.findSubscriptionById(input.subscriptionId);
|
|
1430
|
+
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;
|
|
1431
|
+
const now = /* @__PURE__ */ new Date();
|
|
1432
|
+
const periodEnd = new Date(existingSub.periodEnd);
|
|
1433
|
+
const periodStart = new Date(existingSub.periodStart);
|
|
1434
|
+
const totalDays = Math.max(1, Math.ceil((periodEnd.getTime() - periodStart.getTime()) / 864e5));
|
|
1435
|
+
const remainingDays = Math.max(0, Math.ceil((periodEnd.getTime() - now.getTime()) / 864e5));
|
|
1436
|
+
let oldAmount = 0;
|
|
1437
|
+
if (existingSub.plan !== "") {
|
|
1438
|
+
const oldPlan = await getPlanByName(options, existingSub.plan) ?? await store.findPlanByName(existingSub.plan);
|
|
1439
|
+
if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats ?? 1);
|
|
1373
1440
|
}
|
|
1374
|
-
|
|
1375
|
-
|
|
1441
|
+
let membersCount = 1;
|
|
1442
|
+
let newSeatCount;
|
|
1443
|
+
let newAmount;
|
|
1444
|
+
try {
|
|
1445
|
+
assertLocallyManagedSubscription(existingSub, "plan or seat changes");
|
|
1446
|
+
if (getPlanSeatAmount(input.plan) !== void 0) {
|
|
1447
|
+
const members = await store.listMembers(input.referenceId);
|
|
1448
|
+
membersCount = members.length > 0 ? members.length : 1;
|
|
1449
|
+
}
|
|
1450
|
+
newSeatCount = input.quantity ?? existingSub.seats ?? membersCount;
|
|
1451
|
+
newAmount = calculatePlanAmount(input.plan, newSeatCount);
|
|
1452
|
+
} catch (error) {
|
|
1453
|
+
throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
|
|
1454
|
+
}
|
|
1455
|
+
const costDifference = newAmount - oldAmount;
|
|
1456
|
+
const prorationMetadata = createProrationMetadata({
|
|
1457
|
+
subscriptionId: existingSub.id,
|
|
1458
|
+
referenceId: input.referenceId,
|
|
1459
|
+
newPlan: input.plan.name.toLowerCase(),
|
|
1460
|
+
oldPlan: existingSub.plan,
|
|
1461
|
+
newSeatCount,
|
|
1462
|
+
remainingDays
|
|
1463
|
+
});
|
|
1464
|
+
const serializedProrationMetadata = stringifyPaystackMetadata(prorationMetadata);
|
|
1465
|
+
const proratedAmount = Math.round(costDifference / totalDays * remainingDays);
|
|
1466
|
+
const hasCharge = costDifference > 0 && remainingDays > 0;
|
|
1467
|
+
if (hasCharge && proratedAmount < 5e3) throw new APIError("BAD_REQUEST", {
|
|
1468
|
+
message: "Prorated upgrade amount is below Paystack's minimum charge. Schedule the change for period end instead.",
|
|
1469
|
+
status: 400
|
|
1470
|
+
});
|
|
1471
|
+
const credentials = hasCharge ? await readPaystackPaymentCredentials(ctx.context.adapter, options, existingSub.id) : null;
|
|
1472
|
+
const hasAuthorization = credentials?.authorizationCode !== void 0 && credentials.authorizationCode !== null && credentials.authorizationCode !== "";
|
|
1473
|
+
return runSubscriptionOperation(ctx, options, {
|
|
1474
|
+
actor: { id: input.userId ?? existingSub.userId },
|
|
1475
|
+
referenceId: input.referenceId,
|
|
1476
|
+
kind: hasCharge ? hasAuthorization ? "proration-charge" : "proration-initialize" : "local-change",
|
|
1477
|
+
subscription: existingSub,
|
|
1478
|
+
intent: {
|
|
1479
|
+
plan: input.plan.name.toLowerCase(),
|
|
1480
|
+
amount: hasCharge ? proratedAmount : 0,
|
|
1481
|
+
currency: input.finalCurrency,
|
|
1482
|
+
interval: input.plan.interval,
|
|
1483
|
+
quantity: newSeatCount,
|
|
1484
|
+
groupId: normalizeSubscriptionGroup(input.plan.group),
|
|
1485
|
+
callbackURL: input.callbackURL
|
|
1486
|
+
}
|
|
1487
|
+
}, async (providerReference, setPhase) => {
|
|
1488
|
+
let completedProrationReference;
|
|
1489
|
+
if (costDifference > 0 && remainingDays > 0) {
|
|
1490
|
+
const paystack = createPaystackAdapter(options.paystackClient);
|
|
1491
|
+
if (credentials?.authorizationCode !== void 0 && credentials.authorizationCode !== null && credentials.authorizationCode !== "") {
|
|
1492
|
+
const sdkRes = await paystack.chargeAuthorization({
|
|
1493
|
+
email: input.targetEmail,
|
|
1494
|
+
amount: proratedAmount,
|
|
1495
|
+
authorization_code: credentials.authorizationCode,
|
|
1496
|
+
reference: providerReference ?? `upg_${existingSub.id}_${Date.now()}_${Math.random().toString(36).substring(7)}`,
|
|
1497
|
+
metadata: serializedProrationMetadata
|
|
1498
|
+
});
|
|
1499
|
+
if (providerReference !== void 0 && sdkRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
|
|
1500
|
+
if (sdkRes?.status !== "success") throw new APIError("BAD_REQUEST", { message: "Failed to process prorated charge via saved authorization." });
|
|
1501
|
+
setPhase("persistence");
|
|
1502
|
+
await store.createTransaction({
|
|
1503
|
+
reference: sdkRes.reference ?? "",
|
|
1504
|
+
paystackId: sdkRes.id !== void 0 && sdkRes.id !== null ? String(sdkRes.id) : void 0,
|
|
1505
|
+
referenceId: input.referenceId,
|
|
1506
|
+
userId: input.userId,
|
|
1507
|
+
amount: sdkRes.amount ?? proratedAmount,
|
|
1508
|
+
currency: sdkRes.currency ?? input.finalCurrency,
|
|
1509
|
+
status: "success",
|
|
1510
|
+
plan: input.plan.name.toLowerCase(),
|
|
1511
|
+
metadata: serializedProrationMetadata,
|
|
1512
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1513
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1514
|
+
});
|
|
1515
|
+
completedProrationReference = sdkRes.reference ?? void 0;
|
|
1516
|
+
} else {
|
|
1517
|
+
const initRes = await paystack.initializeTransaction({
|
|
1518
|
+
...providerReference !== void 0 ? { reference: providerReference } : {},
|
|
1519
|
+
email: input.targetEmail,
|
|
1520
|
+
amount: proratedAmount,
|
|
1521
|
+
currency: input.finalCurrency,
|
|
1522
|
+
callback_url: input.callbackURL ?? void 0,
|
|
1523
|
+
metadata: serializedProrationMetadata,
|
|
1524
|
+
...input.allowedSubscriptionChannels !== void 0 ? { channels: input.allowedSubscriptionChannels } : {}
|
|
1525
|
+
});
|
|
1526
|
+
if (providerReference !== void 0 && initRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
|
|
1527
|
+
setPhase("persistence");
|
|
1528
|
+
await store.createTransaction({
|
|
1529
|
+
reference: initRes?.reference ?? "",
|
|
1530
|
+
referenceId: input.referenceId,
|
|
1531
|
+
userId: input.userId,
|
|
1532
|
+
amount: proratedAmount,
|
|
1533
|
+
currency: input.finalCurrency,
|
|
1534
|
+
status: "pending",
|
|
1535
|
+
plan: input.plan.name.toLowerCase(),
|
|
1536
|
+
metadata: serializedProrationMetadata,
|
|
1537
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1538
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1539
|
+
});
|
|
1540
|
+
return {
|
|
1541
|
+
kind: "checkout",
|
|
1542
|
+
url: initRes?.authorization_url,
|
|
1543
|
+
reference: initRes?.reference,
|
|
1544
|
+
accessCode: initRes?.access_code,
|
|
1545
|
+
redirect: true
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
setPhase("persistence");
|
|
1550
|
+
await store.updateSubscription(existingSub.id, {
|
|
1551
|
+
plan: input.plan.name,
|
|
1552
|
+
seats: newSeatCount,
|
|
1553
|
+
...completedProrationReference !== void 0 ? { transactionReference: completedProrationReference } : {},
|
|
1554
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1555
|
+
});
|
|
1556
|
+
return {
|
|
1557
|
+
kind: "prorated",
|
|
1558
|
+
status: "success",
|
|
1559
|
+
message: "Subscription successfully upgraded with prorated charge.",
|
|
1560
|
+
prorated: true
|
|
1561
|
+
};
|
|
1562
|
+
});
|
|
1376
1563
|
}
|
|
1377
1564
|
//#endregion
|
|
1378
1565
|
//#region src/routes.ts
|
|
@@ -1692,14 +1879,15 @@ const paystackWebhook = (options, path = "/webhook") => {
|
|
|
1692
1879
|
};
|
|
1693
1880
|
const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
1694
1881
|
const subscriptionOptions = options.subscription;
|
|
1882
|
+
const useMiddlewares = subscriptionOptions?.enabled === true ? [
|
|
1883
|
+
sessionMiddleware,
|
|
1884
|
+
originCheck,
|
|
1885
|
+
referenceMiddleware(options, "initialize-transaction")
|
|
1886
|
+
] : [sessionMiddleware, originCheck];
|
|
1695
1887
|
return createAuthEndpoint(path, {
|
|
1696
1888
|
method: "POST",
|
|
1697
1889
|
body: initializeTransactionBodySchema,
|
|
1698
|
-
use:
|
|
1699
|
-
sessionMiddleware,
|
|
1700
|
-
originCheck,
|
|
1701
|
-
referenceMiddleware(options, "initialize-transaction")
|
|
1702
|
-
] : [sessionMiddleware, originCheck]
|
|
1890
|
+
use: useMiddlewares
|
|
1703
1891
|
}, async (ctx) => {
|
|
1704
1892
|
const paystack = getPaystackOps(options.paystackClient);
|
|
1705
1893
|
const { plan: planName, product: productName, amount: bodyAmount, currency, email, metadata: extraMetadata, callbackURL, quantity, scheduleAtPeriodEnd, cancelAtPeriodEnd, prorateAndCharge, subscriptionId } = ctx.body;
|
|
@@ -1785,13 +1973,15 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1785
1973
|
if (selectedSubscription === null || selectedSubscription.referenceId !== referenceId || normalizeSubscriptionGroup(selectedSubscription.groupId) !== groupId) throw new APIError("BAD_REQUEST", { message: "Subscription does not belong to the authorized reference and plan group." });
|
|
1786
1974
|
}
|
|
1787
1975
|
const scheduledChange = await scheduleSubscriptionLifecycleChange(ctx, {
|
|
1976
|
+
userId: user.id,
|
|
1788
1977
|
referenceId,
|
|
1789
1978
|
subscriptionId,
|
|
1790
1979
|
plan,
|
|
1791
1980
|
scheduleAtPeriodEnd,
|
|
1792
1981
|
cancelAtPeriodEnd
|
|
1793
|
-
});
|
|
1982
|
+
}, options);
|
|
1794
1983
|
if (scheduledChange !== null) return ctx.json(scheduledChange);
|
|
1984
|
+
let validatedQuantity = quantity ?? 1;
|
|
1795
1985
|
if (plan !== void 0) try {
|
|
1796
1986
|
if (getPlanSeatAmount(plan) !== void 0) {
|
|
1797
1987
|
const members = await ctx.context.adapter.findMany({
|
|
@@ -1802,7 +1992,9 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1802
1992
|
}]
|
|
1803
1993
|
});
|
|
1804
1994
|
const seatCount = members.length > 0 ? members.length : 1;
|
|
1805
|
-
|
|
1995
|
+
const quantityToUse = quantity ?? seatCount;
|
|
1996
|
+
validatedQuantity = quantityToUse;
|
|
1997
|
+
amount = calculatePlanAmount(plan, quantityToUse);
|
|
1806
1998
|
}
|
|
1807
1999
|
} catch (error) {
|
|
1808
2000
|
throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
|
|
@@ -1815,7 +2007,14 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1815
2007
|
plan
|
|
1816
2008
|
});
|
|
1817
2009
|
const { trialStart, trialEnd } = trial;
|
|
1818
|
-
|
|
2010
|
+
const normalizeInitializationError = (error) => {
|
|
2011
|
+
ctx.context.logger.error("Failed to initialize Paystack transaction", error);
|
|
2012
|
+
return new APIError("BAD_REQUEST", {
|
|
2013
|
+
code: "FAILED_TO_INITIALIZE_TRANSACTION",
|
|
2014
|
+
message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION.message
|
|
2015
|
+
});
|
|
2016
|
+
};
|
|
2017
|
+
const prepared = await (async () => {
|
|
1819
2018
|
const targetEmail = await resolveCheckoutTargetEmail(ctx, options, {
|
|
1820
2019
|
email,
|
|
1821
2020
|
referenceId,
|
|
@@ -1857,108 +2056,136 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
|
|
|
1857
2056
|
callbackURL,
|
|
1858
2057
|
allowedSubscriptionChannels
|
|
1859
2058
|
});
|
|
1860
|
-
if (proration?.kind === "checkout") return
|
|
2059
|
+
if (proration?.kind === "checkout") return { earlyResult: {
|
|
1861
2060
|
kind: "checkout",
|
|
1862
2061
|
url: proration.url ?? "",
|
|
1863
2062
|
reference: proration.reference ?? "",
|
|
1864
2063
|
accessCode: proration.accessCode ?? "",
|
|
1865
2064
|
redirect: proration.redirect
|
|
1866
|
-
}
|
|
1867
|
-
if (proration?.kind === "prorated") return
|
|
2065
|
+
} };
|
|
2066
|
+
if (proration?.kind === "prorated") return { earlyResult: {
|
|
1868
2067
|
kind: "prorated",
|
|
1869
2068
|
status: proration.status,
|
|
1870
2069
|
message: proration.message,
|
|
1871
2070
|
prorated: proration.prorated
|
|
1872
|
-
}
|
|
1873
|
-
}
|
|
1874
|
-
if (plan !== void 0) if (trialStart !== void 0) initBody.amount = 5e3;
|
|
1875
|
-
else {
|
|
1876
|
-
initBody.plan = plan.planCode;
|
|
1877
|
-
initBody.invoice_limit = plan.invoiceLimit;
|
|
1878
|
-
let finalAmount;
|
|
1879
|
-
if (amount !== void 0 && amount !== null) {
|
|
1880
|
-
finalAmount = amount;
|
|
1881
|
-
initBody.quantity = 1;
|
|
1882
|
-
} else finalAmount = (plan.amount ?? 0) * (quantity ?? 1);
|
|
1883
|
-
initBody.amount = Math.max(Math.round(finalAmount), 5e3);
|
|
2071
|
+
} };
|
|
1884
2072
|
}
|
|
1885
|
-
|
|
2073
|
+
if (plan !== void 0) {
|
|
2074
|
+
if (trialStart !== void 0) initBody.amount = 5e3;
|
|
2075
|
+
else {
|
|
2076
|
+
initBody.plan = plan.planCode;
|
|
2077
|
+
initBody.invoice_limit = plan.invoiceLimit;
|
|
2078
|
+
let finalAmount;
|
|
2079
|
+
if (amount !== void 0 && amount !== null) {
|
|
2080
|
+
finalAmount = amount;
|
|
2081
|
+
initBody.quantity = 1;
|
|
2082
|
+
} else finalAmount = (plan.amount ?? 0) * (quantity ?? 1);
|
|
2083
|
+
initBody.amount = Math.max(Math.round(finalAmount), 5e3);
|
|
2084
|
+
}
|
|
2085
|
+
} else {
|
|
1886
2086
|
if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Amount is required for one-time payments" });
|
|
1887
2087
|
initBody.amount = Math.round(amount);
|
|
1888
2088
|
}
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
} catch (error) {
|
|
1894
|
-
ctx.context.logger.error("Failed to initialize Paystack transaction", error);
|
|
1895
|
-
throw new APIError("BAD_REQUEST", {
|
|
1896
|
-
code: "FAILED_TO_INITIALIZE_TRANSACTION",
|
|
1897
|
-
message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION.message
|
|
1898
|
-
});
|
|
1899
|
-
}
|
|
1900
|
-
await ctx.context.adapter.create({
|
|
1901
|
-
model: PAYSTACK_MODELS.transaction,
|
|
1902
|
-
data: {
|
|
1903
|
-
reference: reference ?? "",
|
|
1904
|
-
referenceId,
|
|
1905
|
-
userId: user.id,
|
|
1906
|
-
amount: amount ?? 0,
|
|
1907
|
-
currency: plan?.currency ?? currency ?? "NGN",
|
|
1908
|
-
status: "pending",
|
|
1909
|
-
plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
|
|
1910
|
-
product: product !== void 0 ? product.name.toLowerCase() : void 0,
|
|
1911
|
-
metadata: hasPaystackMetadata(extraMetadata) ? stringifyPaystackMetadata(extraMetadata) : void 0,
|
|
1912
|
-
createdAt: /* @__PURE__ */ new Date(),
|
|
1913
|
-
updatedAt: /* @__PURE__ */ new Date()
|
|
1914
|
-
}
|
|
2089
|
+
return { initBody };
|
|
2090
|
+
})().catch((error) => {
|
|
2091
|
+
if (options.subscription?.operationHooks === void 0) throw normalizeInitializationError(error);
|
|
2092
|
+
throw error;
|
|
1915
2093
|
});
|
|
1916
|
-
if (
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
2094
|
+
if (prepared.earlyResult !== void 0) return ctx.json(prepared.earlyResult);
|
|
2095
|
+
const initBody = prepared.initBody;
|
|
2096
|
+
const operation = plan !== void 0 && options.subscription?.operationHooks !== void 0 ? {
|
|
2097
|
+
actor: { id: user.id },
|
|
2098
|
+
referenceId,
|
|
2099
|
+
kind: "initialize",
|
|
2100
|
+
subscription: subscriptionId !== void 0 ? await createBillingStore(ctx).findSubscriptionById(subscriptionId) : await createBillingStore(ctx).findCurrentSubscription(referenceId, groupId),
|
|
2101
|
+
intent: {
|
|
2102
|
+
plan: plan.name.toLowerCase(),
|
|
2103
|
+
amount: initBody.amount,
|
|
2104
|
+
currency: finalCurrency,
|
|
2105
|
+
interval: plan.interval,
|
|
2106
|
+
quantity: validatedQuantity,
|
|
2107
|
+
groupId,
|
|
2108
|
+
callbackURL,
|
|
2109
|
+
trialStart,
|
|
2110
|
+
trialEnd
|
|
2111
|
+
}
|
|
2112
|
+
} : void 0;
|
|
2113
|
+
const execute = async (providerReference, setPhase) => {
|
|
2114
|
+
if (providerReference !== void 0) initBody.reference = providerReference;
|
|
2115
|
+
try {
|
|
2116
|
+
const sdkRes = unwrapSdkResult(await paystack?.transaction?.initialize({ body: initBody }));
|
|
2117
|
+
if (providerReference !== void 0 && sdkRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
|
|
2118
|
+
url = sdkRes?.authorization_url;
|
|
2119
|
+
reference = sdkRes?.reference;
|
|
2120
|
+
accessCode = sdkRes?.access_code;
|
|
2121
|
+
} catch (error) {
|
|
2122
|
+
throw normalizeInitializationError(error);
|
|
2123
|
+
}
|
|
2124
|
+
setPhase("persistence");
|
|
2125
|
+
await ctx.context.adapter.create({
|
|
2126
|
+
model: PAYSTACK_MODELS.transaction,
|
|
1932
2127
|
data: {
|
|
1933
|
-
|
|
1934
|
-
groupId,
|
|
2128
|
+
reference: reference ?? "",
|
|
1935
2129
|
referenceId,
|
|
1936
2130
|
userId: user.id,
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
seats: quantity ?? 1,
|
|
1944
|
-
periodStart: /* @__PURE__ */ new Date(),
|
|
1945
|
-
periodEnd: new Date(Date.now() + 720 * 60 * 60 * 1e3),
|
|
1946
|
-
cancelAtPeriodEnd: false,
|
|
1947
|
-
trialStart,
|
|
1948
|
-
trialEnd,
|
|
2131
|
+
amount: amount ?? 0,
|
|
2132
|
+
currency: plan?.currency ?? currency ?? "NGN",
|
|
2133
|
+
status: "pending",
|
|
2134
|
+
plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
|
|
2135
|
+
product: product !== void 0 ? product.name.toLowerCase() : void 0,
|
|
2136
|
+
metadata: hasPaystackMetadata(extraMetadata) ? stringifyPaystackMetadata(extraMetadata) : void 0,
|
|
1949
2137
|
createdAt: /* @__PURE__ */ new Date(),
|
|
1950
2138
|
updatedAt: /* @__PURE__ */ new Date()
|
|
1951
2139
|
}
|
|
1952
2140
|
});
|
|
1953
|
-
if (
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
2141
|
+
if (plan !== void 0) {
|
|
2142
|
+
const store = createBillingStore(ctx);
|
|
2143
|
+
let customerCode = (await store.findCustomerByReference(referenceId === user.id ? "user" : "organization", referenceId))?.customerCode;
|
|
2144
|
+
if (customerCode === void 0) try {
|
|
2145
|
+
customerCode = (await ctx.context.adapter.findOne({
|
|
2146
|
+
model: referenceId === user.id ? "user" : "organization",
|
|
2147
|
+
where: [{
|
|
2148
|
+
field: "id",
|
|
2149
|
+
value: referenceId
|
|
2150
|
+
}],
|
|
2151
|
+
select: ["paystackCustomerCode"]
|
|
2152
|
+
}))?.paystackCustomerCode ?? void 0;
|
|
2153
|
+
if (customerCode !== void 0 && customerCode !== null && customerCode !== "") await store.saveCustomer(referenceId === user.id ? "user" : "organization", referenceId, customerCode);
|
|
2154
|
+
} catch {}
|
|
2155
|
+
const newSubscription = await ctx.context.adapter.create({
|
|
2156
|
+
model: PAYSTACK_MODELS.subscription,
|
|
2157
|
+
data: {
|
|
2158
|
+
plan: plan.name.toLowerCase(),
|
|
2159
|
+
groupId,
|
|
2160
|
+
referenceId,
|
|
2161
|
+
userId: user.id,
|
|
2162
|
+
customerCode,
|
|
2163
|
+
subscriptionCode: void 0,
|
|
2164
|
+
planCode: plan.planCode,
|
|
2165
|
+
transactionReference: reference ?? "",
|
|
2166
|
+
status: trialStart !== void 0 ? "trialing" : "incomplete",
|
|
2167
|
+
billingInterval: plan.interval ?? null,
|
|
2168
|
+
seats: quantity ?? 1,
|
|
2169
|
+
periodStart: /* @__PURE__ */ new Date(),
|
|
2170
|
+
periodEnd: new Date(Date.now() + 2592e6),
|
|
2171
|
+
cancelAtPeriodEnd: false,
|
|
2172
|
+
trialStart,
|
|
2173
|
+
trialEnd,
|
|
2174
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
2175
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
2176
|
+
}
|
|
2177
|
+
});
|
|
2178
|
+
if (trialStart !== void 0 && newSubscription !== void 0 && newSubscription !== null && plan.freeTrial?.onTrialStart !== void 0) await plan.freeTrial.onTrialStart(newSubscription);
|
|
2179
|
+
}
|
|
2180
|
+
return ctx.json({
|
|
2181
|
+
kind: "checkout",
|
|
2182
|
+
url: url ?? "",
|
|
2183
|
+
reference: reference ?? "",
|
|
2184
|
+
accessCode: accessCode ?? "",
|
|
2185
|
+
redirect: true
|
|
2186
|
+
});
|
|
2187
|
+
};
|
|
2188
|
+
return operation !== void 0 ? runSubscriptionOperation(ctx, options, operation, execute) : execute(void 0, () => void 0);
|
|
1962
2189
|
});
|
|
1963
2190
|
};
|
|
1964
2191
|
const createSubscription = (options, path = "/create-subscription") => initializeTransaction(options, path);
|
|
@@ -1966,14 +2193,16 @@ const upgradeSubscription = (options, path = "/upgrade-subscription") => initial
|
|
|
1966
2193
|
const cancelSubscription = (options, path = "/cancel-subscription") => disablePaystackSubscription(options, path);
|
|
1967
2194
|
const restoreSubscription = (options, path = "/restore-subscription") => enablePaystackSubscription(options, path);
|
|
1968
2195
|
const verifyTransaction = (options, path = "/verify-transaction") => {
|
|
2196
|
+
const verifyBodySchema = z.object({ reference: z.string() });
|
|
2197
|
+
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2198
|
+
sessionMiddleware,
|
|
2199
|
+
originCheck,
|
|
2200
|
+
referenceMiddleware(options, "verify-transaction")
|
|
2201
|
+
] : [sessionMiddleware, originCheck];
|
|
1969
2202
|
return createAuthEndpoint(path, {
|
|
1970
2203
|
method: "POST",
|
|
1971
|
-
body:
|
|
1972
|
-
use:
|
|
1973
|
-
sessionMiddleware,
|
|
1974
|
-
originCheck,
|
|
1975
|
-
referenceMiddleware(options, "verify-transaction")
|
|
1976
|
-
] : [sessionMiddleware, originCheck]
|
|
2204
|
+
body: verifyBodySchema,
|
|
2205
|
+
use: useMiddlewares
|
|
1977
2206
|
}, async (ctx) => {
|
|
1978
2207
|
const session = await getSessionFromCtx(ctx);
|
|
1979
2208
|
const result = await reconcilePaystackTransaction(ctx, options, {
|
|
@@ -2000,14 +2229,15 @@ const verifyTransaction = (options, path = "/verify-transaction") => {
|
|
|
2000
2229
|
const listSubscriptions = (options, path = "/list-subscriptions") => {
|
|
2001
2230
|
const listQuerySchema = z.object({ referenceId: z.string().optional() });
|
|
2002
2231
|
const subscriptionOptions = options.subscription;
|
|
2232
|
+
const useMiddlewares = subscriptionOptions?.enabled === true ? [
|
|
2233
|
+
sessionMiddleware,
|
|
2234
|
+
originCheck,
|
|
2235
|
+
referenceMiddleware(options, "list-subscriptions")
|
|
2236
|
+
] : [sessionMiddleware, originCheck];
|
|
2003
2237
|
return createAuthEndpoint(path, {
|
|
2004
2238
|
method: "GET",
|
|
2005
2239
|
query: listQuerySchema,
|
|
2006
|
-
use:
|
|
2007
|
-
sessionMiddleware,
|
|
2008
|
-
originCheck,
|
|
2009
|
-
referenceMiddleware(options, "list-subscriptions")
|
|
2010
|
-
] : [sessionMiddleware, originCheck]
|
|
2240
|
+
use: useMiddlewares
|
|
2011
2241
|
}, async (ctx) => {
|
|
2012
2242
|
if (subscriptionOptions?.enabled !== true) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled in the Paystack options." });
|
|
2013
2243
|
const session = await getSessionFromCtx(ctx);
|
|
@@ -2028,14 +2258,16 @@ const listSubscriptions = (options, path = "/list-subscriptions") => {
|
|
|
2028
2258
|
});
|
|
2029
2259
|
};
|
|
2030
2260
|
const listTransactions = (options, path = "/list-transactions") => {
|
|
2261
|
+
const listQuerySchema = z.object({ referenceId: z.string().optional() });
|
|
2262
|
+
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2263
|
+
sessionMiddleware,
|
|
2264
|
+
originCheck,
|
|
2265
|
+
referenceMiddleware(options, "list-transactions")
|
|
2266
|
+
] : [sessionMiddleware, originCheck];
|
|
2031
2267
|
return createAuthEndpoint(path, {
|
|
2032
2268
|
method: "GET",
|
|
2033
|
-
query:
|
|
2034
|
-
use:
|
|
2035
|
-
sessionMiddleware,
|
|
2036
|
-
originCheck,
|
|
2037
|
-
referenceMiddleware(options, "list-transactions")
|
|
2038
|
-
] : [sessionMiddleware, originCheck]
|
|
2269
|
+
query: listQuerySchema,
|
|
2270
|
+
use: useMiddlewares
|
|
2039
2271
|
}, async (ctx) => {
|
|
2040
2272
|
const session = await getSessionFromCtx(ctx);
|
|
2041
2273
|
if (session === void 0 || session === null) throw new APIError("UNAUTHORIZED");
|
|
@@ -2055,14 +2287,15 @@ const listTransactions = (options, path = "/list-transactions") => {
|
|
|
2055
2287
|
});
|
|
2056
2288
|
};
|
|
2057
2289
|
const disablePaystackSubscription = (options, path = "/disable-subscription") => {
|
|
2290
|
+
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2291
|
+
sessionMiddleware,
|
|
2292
|
+
originCheck,
|
|
2293
|
+
referenceMiddleware(options, "disable-subscription")
|
|
2294
|
+
] : [sessionMiddleware, originCheck];
|
|
2058
2295
|
return createAuthEndpoint(path, {
|
|
2059
2296
|
method: "POST",
|
|
2060
2297
|
body: enableDisableBodySchema,
|
|
2061
|
-
use:
|
|
2062
|
-
sessionMiddleware,
|
|
2063
|
-
originCheck,
|
|
2064
|
-
referenceMiddleware(options, "disable-subscription")
|
|
2065
|
-
] : [sessionMiddleware, originCheck]
|
|
2298
|
+
use: useMiddlewares
|
|
2066
2299
|
}, async (ctx) => {
|
|
2067
2300
|
const { subscriptionCode, atPeriodEnd } = ctx.body;
|
|
2068
2301
|
const paystack = getPaystackOps(options.paystackClient);
|
|
@@ -2149,22 +2382,24 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
|
|
|
2149
2382
|
return ctx.json({ status: "success" });
|
|
2150
2383
|
} catch (error) {
|
|
2151
2384
|
ctx.context.logger.error("Failed to disable subscription", error);
|
|
2385
|
+
const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION.message;
|
|
2152
2386
|
throw new APIError("BAD_REQUEST", {
|
|
2153
2387
|
code: "FAILED_TO_DISABLE_SUBSCRIPTION",
|
|
2154
|
-
message:
|
|
2388
|
+
message: errorMessage
|
|
2155
2389
|
});
|
|
2156
2390
|
}
|
|
2157
2391
|
});
|
|
2158
2392
|
};
|
|
2159
2393
|
const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
2394
|
+
const useMiddlewares = options.subscription?.enabled === true ? [
|
|
2395
|
+
sessionMiddleware,
|
|
2396
|
+
originCheck,
|
|
2397
|
+
referenceMiddleware(options, "enable-subscription")
|
|
2398
|
+
] : [sessionMiddleware, originCheck];
|
|
2160
2399
|
return createAuthEndpoint(path, {
|
|
2161
2400
|
method: "POST",
|
|
2162
2401
|
body: enableDisableBodySchema,
|
|
2163
|
-
use:
|
|
2164
|
-
sessionMiddleware,
|
|
2165
|
-
originCheck,
|
|
2166
|
-
referenceMiddleware(options, "enable-subscription")
|
|
2167
|
-
] : [sessionMiddleware, originCheck]
|
|
2402
|
+
use: useMiddlewares
|
|
2168
2403
|
}, async (ctx) => {
|
|
2169
2404
|
const { subscriptionCode } = ctx.body;
|
|
2170
2405
|
const paystack = getPaystackOps(options.paystackClient);
|
|
@@ -2204,9 +2439,10 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
|
|
|
2204
2439
|
return ctx.json({ status: "success" });
|
|
2205
2440
|
} catch (error) {
|
|
2206
2441
|
ctx.context.logger.error("Failed to enable subscription", error);
|
|
2442
|
+
const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION.message;
|
|
2207
2443
|
throw new APIError("BAD_REQUEST", {
|
|
2208
2444
|
code: "FAILED_TO_ENABLE_SUBSCRIPTION",
|
|
2209
|
-
message:
|
|
2445
|
+
message: errorMessage
|
|
2210
2446
|
});
|
|
2211
2447
|
}
|
|
2212
2448
|
});
|
|
@@ -2230,7 +2466,8 @@ const getSubscriptionManageLink = (options, path = "/subscription-manage-link")
|
|
|
2230
2466
|
return ctx.json({ link: res?.link || null });
|
|
2231
2467
|
} catch (error) {
|
|
2232
2468
|
ctx.context.logger.error("Failed to get subscription manage link", error);
|
|
2233
|
-
|
|
2469
|
+
const errorMessage = error instanceof Error ? error.message : "Failed to get subscription manage link";
|
|
2470
|
+
throw new APIError("BAD_REQUEST", { message: errorMessage });
|
|
2234
2471
|
}
|
|
2235
2472
|
};
|
|
2236
2473
|
return createAuthEndpoint(path, {
|
|
@@ -2259,7 +2496,8 @@ const listPlans = (_options, path = "/list-plans") => {
|
|
|
2259
2496
|
return ctx.json({ plans });
|
|
2260
2497
|
} catch (error) {
|
|
2261
2498
|
ctx.context.logger.error("Failed to list plans", error);
|
|
2262
|
-
|
|
2499
|
+
const errorMessage = error instanceof Error ? error.message : "Failed to list plans";
|
|
2500
|
+
throw new APIError("BAD_REQUEST", { message: errorMessage });
|
|
2263
2501
|
}
|
|
2264
2502
|
});
|
|
2265
2503
|
};
|
|
@@ -2664,101 +2902,6 @@ const getSchema = (options) => {
|
|
|
2664
2902
|
return mergeSchema(baseSchema, optionSchema);
|
|
2665
2903
|
};
|
|
2666
2904
|
//#endregion
|
|
2667
|
-
//#region src/customer.ts
|
|
2668
|
-
function isNotFound(error) {
|
|
2669
|
-
if (error === null || typeof error !== "object") return false;
|
|
2670
|
-
const candidate = error;
|
|
2671
|
-
return candidate.status === 404 || candidate.statusCode === 404;
|
|
2672
|
-
}
|
|
2673
|
-
function customerCode(customer) {
|
|
2674
|
-
if (customer === null || typeof customer !== "object") return void 0;
|
|
2675
|
-
const code = customer.customer_code;
|
|
2676
|
-
return typeof code === "string" && code !== "" ? code : void 0;
|
|
2677
|
-
}
|
|
2678
|
-
function ownsCustomer(customer, reference) {
|
|
2679
|
-
if (customer === null || typeof customer !== "object") return false;
|
|
2680
|
-
const metadata = parsePaystackMetadata(customer.metadata);
|
|
2681
|
-
const expectedIdKey = reference.type === "user" ? "userId" : "organizationId";
|
|
2682
|
-
const otherIdKey = reference.type === "user" ? "organizationId" : "userId";
|
|
2683
|
-
return metadata[expectedIdKey] === reference.id && metadata[otherIdKey] === void 0 && (metadata.customerType === void 0 || metadata.customerType === reference.type);
|
|
2684
|
-
}
|
|
2685
|
-
function hasOwner(customer) {
|
|
2686
|
-
if (customer === null || typeof customer !== "object") return false;
|
|
2687
|
-
const metadata = parsePaystackMetadata(customer.metadata);
|
|
2688
|
-
return typeof metadata.userId === "string" || typeof metadata.organizationId === "string" || typeof metadata.customerType === "string";
|
|
2689
|
-
}
|
|
2690
|
-
function ownershipMetadata(reference, existing) {
|
|
2691
|
-
return stringifyPaystackMetadata({
|
|
2692
|
-
...parsePaystackMetadata(existing),
|
|
2693
|
-
customerType: reference.type,
|
|
2694
|
-
...reference.type === "user" ? { userId: reference.id } : { organizationId: reference.id }
|
|
2695
|
-
});
|
|
2696
|
-
}
|
|
2697
|
-
async function resolvePaystackCustomer(input) {
|
|
2698
|
-
const { adapter, client, logger, reference } = input;
|
|
2699
|
-
const store = createBillingStoreFromAdapter(adapter);
|
|
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
|
-
}
|
|
2717
|
-
const sdk = createPaystackAdapter(client);
|
|
2718
|
-
let existing = null;
|
|
2719
|
-
if (typeof client.customer?.fetch === "function") try {
|
|
2720
|
-
existing = await sdk.fetchCustomer(reference.email) ?? null;
|
|
2721
|
-
} catch (error) {
|
|
2722
|
-
if (!isNotFound(error)) {
|
|
2723
|
-
logger.error("Failed to look up Paystack customer; customer creation was skipped", error);
|
|
2724
|
-
return null;
|
|
2725
|
-
}
|
|
2726
|
-
}
|
|
2727
|
-
if (existing !== null) {
|
|
2728
|
-
const code = customerCode(existing);
|
|
2729
|
-
if (code === void 0) {
|
|
2730
|
-
logger.error("Paystack customer lookup returned no customer code");
|
|
2731
|
-
return null;
|
|
2732
|
-
}
|
|
2733
|
-
const owned = ownsCustomer(existing, reference);
|
|
2734
|
-
const canClaimLegacy = reference.type === "user" && reference.emailVerified === true && !hasOwner(existing);
|
|
2735
|
-
if (!owned && !canClaimLegacy) {
|
|
2736
|
-
logger.error("Paystack customer belongs to another billing reference");
|
|
2737
|
-
return null;
|
|
2738
|
-
}
|
|
2739
|
-
const existingMetadata = existing.metadata;
|
|
2740
|
-
if (canClaimLegacy || parsePaystackMetadata(existingMetadata).customerType !== reference.type) await sdk.updateCustomer(code, { metadata: ownershipMetadata(reference, existingMetadata) });
|
|
2741
|
-
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
2742
|
-
return {
|
|
2743
|
-
customer: existing,
|
|
2744
|
-
created: false
|
|
2745
|
-
};
|
|
2746
|
-
}
|
|
2747
|
-
const customer = await sdk.createCustomer({
|
|
2748
|
-
...input.createParams,
|
|
2749
|
-
email: reference.email,
|
|
2750
|
-
first_name: reference.name ?? void 0,
|
|
2751
|
-
metadata: ownershipMetadata(reference)
|
|
2752
|
-
});
|
|
2753
|
-
const code = customerCode(customer);
|
|
2754
|
-
if (code === void 0) return null;
|
|
2755
|
-
await store.saveCustomer(reference.type, reference.id, code, reference.email);
|
|
2756
|
-
return {
|
|
2757
|
-
customer,
|
|
2758
|
-
created: true
|
|
2759
|
-
};
|
|
2760
|
-
}
|
|
2761
|
-
//#endregion
|
|
2762
2905
|
//#region src/operations.ts
|
|
2763
2906
|
async function syncPaystackProducts(ctx, options) {
|
|
2764
2907
|
const paystack = createPaystackAdapter(options.paystackClient);
|
|
@@ -2794,7 +2937,8 @@ async function syncPaystackProducts(ctx, options) {
|
|
|
2794
2937
|
};
|
|
2795
2938
|
} catch (error) {
|
|
2796
2939
|
ctx.context.logger.error("Failed to sync products", error);
|
|
2797
|
-
|
|
2940
|
+
const errorMessage = error instanceof Error ? error.message : "Failed to sync products";
|
|
2941
|
+
throw new APIError("BAD_REQUEST", { message: errorMessage });
|
|
2798
2942
|
}
|
|
2799
2943
|
}
|
|
2800
2944
|
async function syncPaystackPlans(ctx, options) {
|
|
@@ -2830,7 +2974,8 @@ async function syncPaystackPlans(ctx, options) {
|
|
|
2830
2974
|
};
|
|
2831
2975
|
} catch (error) {
|
|
2832
2976
|
ctx.context.logger.error("Failed to sync plans", error);
|
|
2833
|
-
|
|
2977
|
+
const errorMessage = error instanceof Error ? error.message : "Failed to sync plans";
|
|
2978
|
+
throw new APIError("BAD_REQUEST", { message: errorMessage });
|
|
2834
2979
|
}
|
|
2835
2980
|
}
|
|
2836
2981
|
async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
@@ -2839,7 +2984,7 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2839
2984
|
const subscription = await store.findSubscriptionById(subscriptionId);
|
|
2840
2985
|
if (subscription === void 0 || subscription === null) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
|
|
2841
2986
|
const credentials = await readPaystackPaymentCredentials(ctx.context.adapter, options, subscription.id);
|
|
2842
|
-
if (
|
|
2987
|
+
if (credentials?.authorizationCode === void 0 || credentials.authorizationCode === null || credentials.authorizationCode === "") throw new APIError("BAD_REQUEST", { message: "No authorization code found for this subscription" });
|
|
2843
2988
|
const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
|
|
2844
2989
|
if (plan === void 0 || plan === null) throw new APIError("NOT_FOUND", { message: "Plan not found" });
|
|
2845
2990
|
const amount = bodyAmount ?? plan.amount;
|
|
@@ -2868,10 +3013,11 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
|
|
|
2868
3013
|
status: 400
|
|
2869
3014
|
});
|
|
2870
3015
|
const paystack = createPaystackAdapter(options.paystackClient);
|
|
2871
|
-
const
|
|
3016
|
+
const renewalMetadata = createRenewalMetadata({
|
|
2872
3017
|
subscriptionId,
|
|
2873
3018
|
referenceId
|
|
2874
|
-
})
|
|
3019
|
+
});
|
|
3020
|
+
const serializedRenewalMetadata = stringifyPaystackMetadata(renewalMetadata);
|
|
2875
3021
|
const typedChargeData = await paystack.chargeAuthorization({
|
|
2876
3022
|
email,
|
|
2877
3023
|
amount,
|
|
@@ -2947,8 +3093,9 @@ async function findManySafely(adapter, model) {
|
|
|
2947
3093
|
function migrationData(legacy) {
|
|
2948
3094
|
const now = /* @__PURE__ */ new Date();
|
|
2949
3095
|
const referenceId = asIdentifier(legacy.referenceId) ?? asIdentifier(legacy.userId) ?? "";
|
|
3096
|
+
const id = asIdentifier(legacy.id);
|
|
2950
3097
|
return {
|
|
2951
|
-
...
|
|
3098
|
+
...id !== void 0 ? { id } : {},
|
|
2952
3099
|
plan: asString(legacy.plan) ?? "",
|
|
2953
3100
|
referenceId,
|
|
2954
3101
|
userId: asIdentifier(legacy.userId) ?? referenceId,
|
|
@@ -2976,7 +3123,7 @@ function migrationData(legacy) {
|
|
|
2976
3123
|
async function migrateCustomer(adapter, referenceType, legacy, report) {
|
|
2977
3124
|
const customerCode = asString(legacy.paystackCustomerCode) ?? asString(legacy.customerCode);
|
|
2978
3125
|
const referenceId = asIdentifier(legacy.id);
|
|
2979
|
-
if (
|
|
3126
|
+
if (customerCode === void 0 || referenceId === void 0) return;
|
|
2980
3127
|
const referenceKey = `${referenceType}:${referenceId}`;
|
|
2981
3128
|
try {
|
|
2982
3129
|
if (await adapter.findOne({
|
|
@@ -3043,7 +3190,7 @@ async function migratePaystackSubscriptionSchema(ctx, options) {
|
|
|
3043
3190
|
const legacySubscriptions = await findManySafely(adapter, LEGACY_PAYSTACK_MODELS.subscription);
|
|
3044
3191
|
for (const legacy of legacySubscriptions) {
|
|
3045
3192
|
const id = asIdentifier(legacy.id);
|
|
3046
|
-
if (
|
|
3193
|
+
if (id === void 0) continue;
|
|
3047
3194
|
try {
|
|
3048
3195
|
if (await adapter.findOne({
|
|
3049
3196
|
model: PAYSTACK_MODELS.subscription,
|
|
@@ -3072,7 +3219,7 @@ async function migratePaystackSubscriptionSchema(ctx, options) {
|
|
|
3072
3219
|
}
|
|
3073
3220
|
const authorizationCode = asString(legacy.authorizationCode) ?? asString(legacy.paystackAuthorizationCode);
|
|
3074
3221
|
const emailToken = asString(legacy.emailToken) ?? asString(legacy.paystackEmailToken);
|
|
3075
|
-
if (authorizationCode || emailToken) try {
|
|
3222
|
+
if (authorizationCode !== void 0 || emailToken !== void 0) try {
|
|
3076
3223
|
if (await adapter.findOne({
|
|
3077
3224
|
model: PAYSTACK_MODELS.paymentCredential,
|
|
3078
3225
|
where: [{
|