better-auth-paystack 3.2.1 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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-CGC4qGOv.mjs";
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-BDMDsh7o.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";
6
- import { z } from "zod";
7
5
  import { PaystackError, PaystackResponse } from "@alexasomba/paystack-node";
6
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
7
+ import { z } from "zod";
8
8
  import { Buffer } from "node:buffer";
9
9
  import { mergeSchema } from "better-auth/db";
10
10
  //#region src/models.ts
@@ -79,7 +79,9 @@ function createBillingStoreFromAdapter(adapter) {
79
79
  return sortSubscriptionsForCurrent(groupId === void 0 ? subscriptions : subscriptions.filter((subscription) => groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId))[0] ?? null;
80
80
  },
81
81
  async retireCompetingSubscriptions(referenceId, groupId, exceptId) {
82
- const competitors = (await this.findSubscriptionsByReference(referenceId)).filter((subscription) => subscription.id !== exceptId && (subscription.status === "active" || subscription.status === "trialing") && (groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId));
82
+ const subscriptions = await this.findSubscriptionsByReference(referenceId);
83
+ const selected = subscriptions.find((subscription) => subscription.id === exceptId);
84
+ const competitors = subscriptions.filter((subscription) => subscription.id !== exceptId && (selected === void 0 || new Date(subscription.createdAt).getTime() <= new Date(selected.createdAt).getTime()) && (subscription.status === "active" || subscription.status === "trialing") && (groupId === null ? subscription.groupId === void 0 || subscription.groupId === null || subscription.groupId === "" : subscription.groupId === groupId));
83
85
  const now = /* @__PURE__ */ new Date();
84
86
  for (const subscription of competitors) await this.updateSubscription(subscription.id, {
85
87
  status: "canceled",
@@ -133,10 +135,13 @@ function createBillingStoreFromAdapter(adapter) {
133
135
  model: PAYSTACK_MODELS.webhookEvent,
134
136
  data
135
137
  }),
136
- findWebhookEvent: (eventId) => findOne(PAYSTACK_MODELS.webhookEvent, [{
137
- field: "eventId",
138
- value: eventId
139
- }]),
138
+ findWebhookEvent: (eventId) => adapter.findOne({
139
+ model: PAYSTACK_MODELS.webhookEvent,
140
+ where: [{
141
+ field: "eventId",
142
+ value: eventId
143
+ }]
144
+ }),
140
145
  updateWebhookEvent: (eventId, update) => adapter.update({
141
146
  model: PAYSTACK_MODELS.webhookEvent,
142
147
  update,
@@ -263,11 +268,12 @@ function createBillingStoreFromAdapter(adapter) {
263
268
  value: referenceKey
264
269
  }]);
265
270
  const now = /* @__PURE__ */ new Date();
271
+ const hasEmail = email !== void 0 && email !== null && email !== "";
266
272
  if (existing) return await adapter.update({
267
273
  model: PAYSTACK_MODELS.customer,
268
274
  update: {
269
275
  customerCode,
270
- ...email ? { email } : {},
276
+ ...hasEmail ? { email } : {},
271
277
  updatedAt: now
272
278
  },
273
279
  where: [{
@@ -287,7 +293,7 @@ function createBillingStoreFromAdapter(adapter) {
287
293
  referenceId,
288
294
  referenceKey,
289
295
  customerCode,
290
- ...email ? { email } : {},
296
+ ...hasEmail ? { email } : {},
291
297
  createdAt: now,
292
298
  updatedAt: now
293
299
  }
@@ -314,7 +320,7 @@ function unwrapSdkResult(result) {
314
320
  if (IsPaystackResponse(result)) try {
315
321
  return result.unwrap();
316
322
  } catch (e) {
317
- if (e instanceof PaystackError) throw new APIError("BAD_REQUEST", {
323
+ if (e instanceof PaystackError) throw new APIError(e.status === 404 ? "NOT_FOUND" : "BAD_REQUEST", {
318
324
  message: e.message,
319
325
  status: e.status
320
326
  });
@@ -391,6 +397,101 @@ function createPaystackAdapter(client) {
391
397
  };
392
398
  }
393
399
  //#endregion
400
+ //#region src/customer.ts
401
+ function isNotFound(error) {
402
+ if (error === null || typeof error !== "object") return false;
403
+ const candidate = error;
404
+ return candidate.status === 404 || candidate.statusCode === 404;
405
+ }
406
+ function customerCode(customer) {
407
+ if (customer === null || typeof customer !== "object") return void 0;
408
+ const code = customer.customer_code;
409
+ return typeof code === "string" && code !== "" ? code : void 0;
410
+ }
411
+ function ownsCustomer(customer, reference) {
412
+ if (customer === null || typeof customer !== "object") return false;
413
+ const metadata = parsePaystackMetadata(customer.metadata);
414
+ const expectedIdKey = reference.type === "user" ? "userId" : "organizationId";
415
+ const otherIdKey = reference.type === "user" ? "organizationId" : "userId";
416
+ return metadata[expectedIdKey] === reference.id && metadata[otherIdKey] === void 0 && (metadata.customerType === void 0 || metadata.customerType === reference.type);
417
+ }
418
+ function hasOwner(customer) {
419
+ if (customer === null || typeof customer !== "object") return false;
420
+ const metadata = parsePaystackMetadata(customer.metadata);
421
+ return typeof metadata.userId === "string" || typeof metadata.organizationId === "string" || typeof metadata.customerType === "string";
422
+ }
423
+ function ownershipMetadata(reference, existing) {
424
+ return stringifyPaystackMetadata({
425
+ ...parsePaystackMetadata(existing),
426
+ customerType: reference.type,
427
+ ...reference.type === "user" ? { userId: reference.id } : { organizationId: reference.id }
428
+ });
429
+ }
430
+ async function resolvePaystackCustomer(input) {
431
+ const { adapter, client, logger, reference } = input;
432
+ const store = createBillingStoreFromAdapter(adapter);
433
+ const persisted = await store.findCustomerByReference(reference.type, reference.id);
434
+ let legacyCode;
435
+ try {
436
+ legacyCode = (await adapter.findOne({
437
+ model: reference.type,
438
+ where: [{
439
+ field: "id",
440
+ value: reference.id
441
+ }],
442
+ select: ["paystackCustomerCode"]
443
+ }))?.paystackCustomerCode ?? void 0;
444
+ } catch {}
445
+ const existingCode = reference.paystackCustomerCode ?? persisted?.customerCode ?? legacyCode;
446
+ if (typeof existingCode === "string" && existingCode !== "") {
447
+ if (persisted === null) await store.saveCustomer(reference.type, reference.id, existingCode, reference.email);
448
+ return null;
449
+ }
450
+ const sdk = createPaystackAdapter(client);
451
+ let existing = null;
452
+ if (typeof client.customer?.fetch === "function") try {
453
+ existing = await sdk.fetchCustomer(reference.email) ?? null;
454
+ } catch (error) {
455
+ if (!isNotFound(error)) {
456
+ logger.error("Failed to look up Paystack customer; customer creation was skipped", error);
457
+ return null;
458
+ }
459
+ }
460
+ if (existing !== null) {
461
+ const code = customerCode(existing);
462
+ if (code === void 0) {
463
+ logger.error("Paystack customer lookup returned no customer code");
464
+ return null;
465
+ }
466
+ const owned = ownsCustomer(existing, reference);
467
+ const canClaimLegacy = reference.type === "user" && reference.emailVerified === true && !hasOwner(existing);
468
+ if (!owned && !canClaimLegacy) {
469
+ logger.error("Paystack customer belongs to another billing reference");
470
+ return null;
471
+ }
472
+ const existingMetadata = existing.metadata;
473
+ if (canClaimLegacy || parsePaystackMetadata(existingMetadata).customerType !== reference.type) await sdk.updateCustomer(code, { metadata: ownershipMetadata(reference, existingMetadata) });
474
+ await store.saveCustomer(reference.type, reference.id, code, reference.email);
475
+ return {
476
+ customer: existing,
477
+ created: false
478
+ };
479
+ }
480
+ const customer = await sdk.createCustomer({
481
+ ...input.createParams,
482
+ email: reference.email,
483
+ first_name: reference.name ?? void 0,
484
+ metadata: ownershipMetadata(reference)
485
+ });
486
+ const code = customerCode(customer);
487
+ if (code === void 0) return null;
488
+ await store.saveCustomer(reference.type, reference.id, code, reference.email);
489
+ return {
490
+ customer,
491
+ created: true
492
+ };
493
+ }
494
+ //#endregion
394
495
  //#region src/utils.ts
395
496
  function getPlanSeatAmount(plan) {
396
497
  if (plan.seatAmount !== void 0) {
@@ -530,6 +631,37 @@ async function syncSubscriptionSeats(ctx, organizationId, options) {
530
631
  }
531
632
  }
532
633
  //#endregion
634
+ //#region src/limits.ts
635
+ const getOrganizationSubscription = async (ctx, organizationId, groupId) => {
636
+ return createBillingStore(ctx).findCurrentSubscription(organizationId, groupId);
637
+ };
638
+ const checkSeatLimit = async (ctx, organizationId, seatsToAdd = 1) => {
639
+ const store = createBillingStore(ctx);
640
+ 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);
641
+ const members = await store.listMembers(organizationId);
642
+ if (seatLimit === void 0) return true;
643
+ if (members.length + seatsToAdd > seatLimit) throw new APIError("FORBIDDEN", { message: `Organization member limit reached. Used: ${members.length}, Max: ${seatLimit}` });
644
+ return true;
645
+ };
646
+ async function getOrganizationEntitlements(ctx, organizationId, options) {
647
+ const subscriptions = (await createBillingStore(ctx).findSubscriptionsByReference(organizationId)).filter((subscription) => subscription.status === "active" || subscription.status === "trialing");
648
+ const limits = {};
649
+ const features = /* @__PURE__ */ new Set();
650
+ for (const subscription of subscriptions) {
651
+ const plan = await getPlanByName(options, subscription.plan);
652
+ for (const [name, value] of Object.entries(plan?.limits ?? {})) if (typeof value === "number" && Number.isFinite(value)) limits[name] = Math.max(limits[name] ?? value, value);
653
+ for (const feature of plan?.features ?? []) features.add(feature);
654
+ }
655
+ return {
656
+ limits,
657
+ features: [...features]
658
+ };
659
+ }
660
+ const checkTeamLimit = async (ctx, organizationId, maxTeams) => {
661
+ if ((await createBillingStore(ctx).listTeams(organizationId)).length >= maxTeams) throw new APIError("FORBIDDEN", { message: `Organization team limit reached. Max teams: ${maxTeams}` });
662
+ return true;
663
+ };
664
+ //#endregion
533
665
  //#region src/reference-access.ts
534
666
  const DEFAULT_BILLING_ORG_ROLES = ["owner", "admin"];
535
667
  function normalizeBillingRoles(roles) {
@@ -599,37 +731,6 @@ const referenceMiddleware = (options, action) => createAuthMiddleware(async (ctx
599
731
  } };
600
732
  });
601
733
  //#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
734
  //#region src/credential-crypto.ts
634
735
  const ALGORITHM = "aes-256-gcm";
635
736
  const VERSION = "v1";
@@ -685,9 +786,11 @@ async function readPaystackPaymentCredentials(adapter, options, subscriptionId)
685
786
  }
686
787
  if (!row) return null;
687
788
  const key = resolveCredentialEncryptionKey(options);
789
+ const authorizationCodeEncrypted = row.authorizationCodeEncrypted;
790
+ const emailTokenEncrypted = row.emailTokenEncrypted;
688
791
  return {
689
- authorizationCode: row.authorizationCodeEncrypted ? decryptPaystackCredential(row.authorizationCodeEncrypted, key) : void 0,
690
- emailToken: row.emailTokenEncrypted ? decryptPaystackCredential(row.emailTokenEncrypted, key) : void 0
792
+ authorizationCode: typeof authorizationCodeEncrypted === "string" && authorizationCodeEncrypted !== "" ? decryptPaystackCredential(authorizationCodeEncrypted, key) : void 0,
793
+ emailToken: typeof emailTokenEncrypted === "string" && emailTokenEncrypted !== "" ? decryptPaystackCredential(emailTokenEncrypted, key) : void 0
691
794
  };
692
795
  }
693
796
  async function savePaystackPaymentCredentials(adapter, options, subscriptionId, values) {
@@ -732,242 +835,14 @@ async function savePaystackPaymentCredentials(adapter, options, subscriptionId,
732
835
  });
733
836
  }
734
837
  //#endregion
735
- //#region src/subscription-lifecycle.ts
736
- async function scheduleSubscriptionLifecycleChange(ctx, input) {
737
- const groupId = normalizeSubscriptionGroup(input.plan?.group);
738
- if (input.plan !== void 0 && input.scheduleAtPeriodEnd === true) {
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;
838
+ //#region src/reconciliation.ts
839
+ function getAllowedSubscriptionChannels$1(options) {
840
+ const channels = options.subscription?.allowedPaymentChannels;
841
+ return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
785
842
  }
786
- async function resolveTrialLifecycle(ctx, input) {
787
- const requestedDays = input.plan?.freeTrial?.days !== void 0 && input.plan.freeTrial.days > 0 ? input.plan.freeTrial.days : 0;
788
- const requested = requestedDays > 0;
789
- if (!requested) return {
790
- requestedDays,
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);
809
- return {
810
- trialStart,
811
- trialEnd,
812
- requestedDays,
813
- requested,
814
- granted: true
815
- };
816
- }
817
- async function resolveCheckoutTargetEmail(ctx, options, input) {
818
- const targetEmail = input.email ?? input.user.email;
819
- if (options.organization?.enabled !== true || input.referenceId === input.user.id || input.referenceId === "") return targetEmail;
820
- const org = await ctx.context.adapter.findOne({
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);
843
+ function isAllowedSubscriptionChannel(channel, allowedChannels) {
844
+ if (allowedChannels === void 0) return true;
845
+ return channel !== void 0 && channel !== null && allowedChannels.includes(channel);
971
846
  }
972
847
  function createSummary() {
973
848
  return {
@@ -1176,6 +1051,15 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1176
1051
  const newPlan = getMetadataString(metadataObj, "newPlan");
1177
1052
  const newSeatCount = getMetadataNumber(metadataObj, "newSeatCount");
1178
1053
  if (subscriptionId !== void 0 && subscriptionId !== "" && newPlan !== void 0 && newPlan !== "") {
1054
+ const originalSubscription = await store.findSubscriptionById(subscriptionId);
1055
+ if (!originalSubscription || originalSubscription.status === "canceled" || originalSubscription.transactionReference === reference) return {
1056
+ ok: true,
1057
+ source,
1058
+ status,
1059
+ reference,
1060
+ data,
1061
+ ...summary
1062
+ };
1179
1063
  const updatedSubscription = await store.updateSubscription(subscriptionId, {
1180
1064
  plan: newPlan,
1181
1065
  ...typeof newSeatCount === "number" ? { seats: newSeatCount } : {},
@@ -1187,7 +1071,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1187
1071
  summary.subscription.id = updatedSubscription?.id ?? subscriptionId;
1188
1072
  summary.subscription.status = updatedSubscription?.status;
1189
1073
  summary.subscription.prorationApplied = updatedSubscription !== null;
1190
- if (updatedSubscription && authorizationCode) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
1074
+ if (updatedSubscription !== null && authorizationCode !== void 0 && authorizationCode !== null && authorizationCode !== "") await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
1191
1075
  }
1192
1076
  return {
1193
1077
  ok: true,
@@ -1203,6 +1087,14 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1203
1087
  summary.subscription.found = targetSub !== void 0;
1204
1088
  summary.subscription.id = targetSub?.id;
1205
1089
  summary.subscription.status = targetSub?.status;
1090
+ if (targetSub && targetSub.status !== "incomplete") return {
1091
+ ok: true,
1092
+ source,
1093
+ status,
1094
+ reference,
1095
+ data,
1096
+ ...summary
1097
+ };
1206
1098
  if (isTrial && targetPlan !== void 0 && trialEnd !== void 0) {
1207
1099
  const email = data.customer?.email;
1208
1100
  const planConfig = (await getPlans(options.subscription)).find((plan) => plan.name.toLowerCase() === targetPlan.toLowerCase());
@@ -1237,7 +1129,7 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1237
1129
  summary.subscription.updated = updatedSubscription !== null;
1238
1130
  summary.subscription.id = updatedSubscription?.id ?? targetSub.id;
1239
1131
  summary.subscription.status = updatedSubscription?.status ?? targetSub.status;
1240
- if (authorizationCode && updatedSubscription !== null) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
1132
+ if (authorizationCode !== void 0 && authorizationCode !== null && authorizationCode !== "" && updatedSubscription !== null) await savePaystackPaymentCredentials(ctx.context.adapter, options, updatedSubscription.id, { authorizationCode });
1241
1133
  if (updatedSubscription !== null && (updatedSubscription.status === "active" || updatedSubscription.status === "trialing")) await store.retireCompetingSubscriptions(updatedSubscription.referenceId, updatedSubscription.groupId ?? null, updatedSubscription.id);
1242
1134
  }
1243
1135
  if (updatedSubscription !== void 0 && updatedSubscription !== null) {
@@ -1270,6 +1162,20 @@ async function reconcilePaystackTransaction(ctx, options, input) {
1270
1162
  };
1271
1163
  }
1272
1164
  //#endregion
1165
+ //#region src/route-modules/catalog.ts
1166
+ async function listStoredProducts(ctx) {
1167
+ return createBillingStore(ctx).listProducts();
1168
+ }
1169
+ async function listStoredPlans(ctx) {
1170
+ return createBillingStore(ctx).listPlans();
1171
+ }
1172
+ async function getConfiguredCatalog(options) {
1173
+ return {
1174
+ plans: options.subscription?.enabled === true ? await getPlans(options.subscription) : [],
1175
+ products: await getProducts(options.products)
1176
+ };
1177
+ }
1178
+ //#endregion
1273
1179
  //#region src/route-modules/checkout.ts
1274
1180
  const initializeTransactionBodySchema = z.object({
1275
1181
  plan: z.string().optional(),
@@ -1287,18 +1193,38 @@ const initializeTransactionBodySchema = z.object({
1287
1193
  prorateAndCharge: z.boolean().optional()
1288
1194
  });
1289
1195
  //#endregion
1290
- //#region src/route-modules/catalog.ts
1291
- async function listStoredProducts(ctx) {
1292
- return createBillingStore(ctx).listProducts();
1293
- }
1294
- async function listStoredPlans(ctx) {
1295
- return createBillingStore(ctx).listPlans();
1196
+ //#region src/route-modules/shared.ts
1197
+ const PAYSTACK_ERROR_CODES = defineErrorCodes({
1198
+ SUBSCRIPTION_NOT_FOUND: "Subscription not found",
1199
+ SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
1200
+ UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
1201
+ FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
1202
+ FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
1203
+ FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
1204
+ FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
1205
+ EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
1206
+ SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
1207
+ });
1208
+ function getAllowedSubscriptionChannels(options) {
1209
+ const channels = options.subscription?.allowedPaymentChannels;
1210
+ return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
1296
1211
  }
1297
- async function getConfiguredCatalog(options) {
1298
- return {
1299
- plans: options.subscription?.enabled === true ? await getPlans(options.subscription) : [],
1300
- products: await getProducts(options.products)
1301
- };
1212
+ async function hmacSha512Hex(secret, message) {
1213
+ const encoder = new TextEncoder();
1214
+ const keyData = encoder.encode(secret);
1215
+ const msgData = encoder.encode(message);
1216
+ const crypto = globalThis.crypto;
1217
+ if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
1218
+ const subtle = crypto.subtle;
1219
+ const key = await subtle.importKey("raw", keyData, {
1220
+ name: "HMAC",
1221
+ hash: "SHA-512"
1222
+ }, false, ["sign"]);
1223
+ const signature = await subtle.sign("HMAC", key, msgData);
1224
+ return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1225
+ }
1226
+ const { createHmac } = await import("node:crypto");
1227
+ return createHmac("sha512", secret).update(message).digest("hex");
1302
1228
  }
1303
1229
  //#endregion
1304
1230
  //#region src/route-modules/subscriptions.ts
@@ -1341,38 +1267,321 @@ function getWebhookClientIP(ctx, headers) {
1341
1267
  return headers?.get("x-forwarded-for")?.split(",")[0]?.trim() ?? headers?.get("x-real-ip") ?? ctx.request.ip;
1342
1268
  }
1343
1269
  //#endregion
1344
- //#region src/route-modules/shared.ts
1345
- const PAYSTACK_ERROR_CODES = defineErrorCodes({
1346
- SUBSCRIPTION_NOT_FOUND: "Subscription not found",
1347
- SUBSCRIPTION_PLAN_NOT_FOUND: "Subscription plan not found",
1348
- UNABLE_TO_CREATE_CUSTOMER: "Unable to create customer",
1349
- FAILED_TO_INITIALIZE_TRANSACTION: "Failed to initialize transaction",
1350
- FAILED_TO_VERIFY_TRANSACTION: "Failed to verify transaction",
1351
- FAILED_TO_DISABLE_SUBSCRIPTION: "Failed to disable subscription",
1352
- FAILED_TO_ENABLE_SUBSCRIPTION: "Failed to enable subscription",
1353
- EMAIL_VERIFICATION_REQUIRED: "Email verification is required before you can subscribe to a plan",
1354
- SUBSCRIPTION_PAYMENT_CHANNEL_NOT_ALLOWED: "This subscription only supports specific payment channels"
1355
- });
1356
- function getAllowedSubscriptionChannels(options) {
1357
- const channels = options.subscription?.allowedPaymentChannels;
1358
- return Array.isArray(channels) && channels.length > 0 ? channels : void 0;
1270
+ //#region src/subscription-lifecycle.ts
1271
+ /** Keep reservation context invocation-local, including concurrent requests through one plugin. */
1272
+ async function runSubscriptionOperation(ctx, options, operation, run) {
1273
+ const hooks = options?.subscription?.operationHooks;
1274
+ if (hooks === void 0) return run(void 0, () => void 0);
1275
+ const decision = await hooks.before(operation, ctx);
1276
+ if (decision.kind === "replay") {
1277
+ 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." });
1278
+ return decision.result;
1279
+ }
1280
+ if (decision.kind === "block") throw new APIError("CONFLICT", { message: decision.message ?? "Subscription operation is blocked." });
1281
+ if (decision.kind !== "proceed" || typeof decision.providerReference !== "string" || decision.providerReference.trim() === "") throw new APIError("BAD_REQUEST", { message: "Operation hook must reserve a provider reference." });
1282
+ const invocation = {
1283
+ ...operation,
1284
+ providerReference: decision.providerReference,
1285
+ context: decision.context
1286
+ };
1287
+ let phase = operation.kind === "schedule" || operation.kind === "local-change" ? "persistence" : "provider";
1288
+ try {
1289
+ const result = await run(decision.providerReference, (next) => {
1290
+ phase = next;
1291
+ });
1292
+ phase = "completion";
1293
+ await hooks.after?.({
1294
+ ...invocation,
1295
+ result
1296
+ }, ctx);
1297
+ return result;
1298
+ } catch (error) {
1299
+ try {
1300
+ await hooks.onError?.({
1301
+ ...invocation,
1302
+ phase,
1303
+ error
1304
+ }, ctx);
1305
+ } catch {
1306
+ ctx.context.logger.error("Paystack operation error hook failed", { phase });
1307
+ }
1308
+ throw error;
1309
+ }
1359
1310
  }
1360
- async function hmacSha512Hex(secret, message) {
1361
- const encoder = new TextEncoder();
1362
- const keyData = encoder.encode(secret);
1363
- const msgData = encoder.encode(message);
1364
- const crypto = globalThis.crypto;
1365
- if (crypto !== void 0 && crypto !== null && "subtle" in crypto) {
1366
- const subtle = crypto.subtle;
1367
- const key = await subtle.importKey("raw", keyData, {
1368
- name: "HMAC",
1369
- hash: "SHA-512"
1370
- }, false, ["sign"]);
1371
- const signature = await subtle.sign("HMAC", key, msgData);
1372
- return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
1311
+ async function scheduleSubscriptionLifecycleChange(ctx, input, options) {
1312
+ const groupId = normalizeSubscriptionGroup(input.plan?.group);
1313
+ if (input.plan !== void 0 && input.scheduleAtPeriodEnd === true) {
1314
+ const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
1315
+ if (existingSub?.status === "active") return runSubscriptionOperation(ctx, options, {
1316
+ actor: { id: input.userId ?? existingSub.userId },
1317
+ referenceId: input.referenceId,
1318
+ kind: "schedule",
1319
+ subscription: existingSub,
1320
+ intent: {
1321
+ plan: input.plan?.name ?? existingSub.plan,
1322
+ interval: input.plan?.interval ?? existingSub.billingInterval ?? void 0,
1323
+ groupId,
1324
+ scheduleAtPeriodEnd: input.scheduleAtPeriodEnd,
1325
+ cancelAtPeriodEnd: input.cancelAtPeriodEnd
1326
+ }
1327
+ }, async () => {
1328
+ await ctx.context.adapter.update({
1329
+ model: PAYSTACK_MODELS.subscription,
1330
+ where: [{
1331
+ field: "id",
1332
+ value: existingSub.id
1333
+ }],
1334
+ update: {
1335
+ pendingPlan: input.plan?.name,
1336
+ updatedAt: /* @__PURE__ */ new Date()
1337
+ }
1338
+ });
1339
+ return {
1340
+ kind: "scheduled",
1341
+ status: "success",
1342
+ message: "Plan change scheduled at period end.",
1343
+ scheduled: true
1344
+ };
1345
+ });
1373
1346
  }
1374
- const { createHmac } = await import("node:crypto");
1375
- return createHmac("sha512", secret).update(message).digest("hex");
1347
+ if (input.cancelAtPeriodEnd === true) {
1348
+ const existingSub = input.subscriptionId === void 0 ? await getOrganizationSubscription(ctx, input.referenceId, input.plan === void 0 ? void 0 : groupId) : await createBillingStore(ctx).findSubscriptionById(input.subscriptionId);
1349
+ if (existingSub?.status === "active") return runSubscriptionOperation(ctx, options, {
1350
+ actor: { id: input.userId ?? existingSub.userId },
1351
+ referenceId: input.referenceId,
1352
+ kind: "schedule",
1353
+ subscription: existingSub,
1354
+ intent: {
1355
+ plan: input.plan?.name ?? existingSub.plan,
1356
+ interval: input.plan?.interval ?? existingSub.billingInterval ?? void 0,
1357
+ groupId,
1358
+ scheduleAtPeriodEnd: input.scheduleAtPeriodEnd,
1359
+ cancelAtPeriodEnd: input.cancelAtPeriodEnd
1360
+ }
1361
+ }, async () => {
1362
+ await ctx.context.adapter.update({
1363
+ model: PAYSTACK_MODELS.subscription,
1364
+ where: [{
1365
+ field: "id",
1366
+ value: existingSub.id
1367
+ }],
1368
+ update: {
1369
+ cancelAtPeriodEnd: true,
1370
+ cancelAt: existingSub.periodEnd ?? null,
1371
+ canceledAt: /* @__PURE__ */ new Date(),
1372
+ updatedAt: /* @__PURE__ */ new Date()
1373
+ }
1374
+ });
1375
+ return {
1376
+ kind: "scheduled",
1377
+ status: "success",
1378
+ message: "Subscription cancellation scheduled at period end.",
1379
+ scheduled: true
1380
+ };
1381
+ });
1382
+ }
1383
+ return null;
1384
+ }
1385
+ async function resolveTrialLifecycle(ctx, input) {
1386
+ const requestedDays = input.plan?.freeTrial?.days !== void 0 && input.plan.freeTrial.days > 0 ? input.plan.freeTrial.days : 0;
1387
+ const requested = requestedDays > 0;
1388
+ if (!requested) return {
1389
+ requestedDays,
1390
+ requested: false,
1391
+ granted: false
1392
+ };
1393
+ if ((await ctx.context.adapter.findMany({
1394
+ model: PAYSTACK_MODELS.subscription,
1395
+ where: [{
1396
+ field: "referenceId",
1397
+ value: input.referenceId
1398
+ }]
1399
+ }))?.some((subscription) => subscription.trialStart !== void 0 && subscription.trialStart !== null || subscription.trialEnd !== void 0 && subscription.trialEnd !== null || subscription.status === "trialing") === true) return {
1400
+ requestedDays,
1401
+ requested,
1402
+ granted: false,
1403
+ deniedReason: "already_used"
1404
+ };
1405
+ const trialStart = /* @__PURE__ */ new Date();
1406
+ const trialEnd = /* @__PURE__ */ new Date();
1407
+ trialEnd.setDate(trialEnd.getDate() + requestedDays);
1408
+ return {
1409
+ trialStart,
1410
+ trialEnd,
1411
+ requestedDays,
1412
+ requested,
1413
+ granted: true
1414
+ };
1415
+ }
1416
+ async function resolveCheckoutTargetEmail(ctx, options, input) {
1417
+ const targetEmail = input.email ?? input.user.email;
1418
+ if (options.organization?.enabled !== true || input.referenceId === input.user.id || input.referenceId === "") return targetEmail;
1419
+ const org = await ctx.context.adapter.findOne({
1420
+ model: "organization",
1421
+ where: [{
1422
+ field: "id",
1423
+ value: input.referenceId
1424
+ }]
1425
+ });
1426
+ if (org === void 0 || org === null) return targetEmail;
1427
+ const orgWithEmail = org;
1428
+ if (orgWithEmail.email !== void 0 && orgWithEmail.email !== null && orgWithEmail.email !== "") return orgWithEmail.email;
1429
+ const ownerMember = await ctx.context.adapter.findOne({
1430
+ model: "member",
1431
+ where: [{
1432
+ field: "organizationId",
1433
+ value: input.referenceId
1434
+ }, {
1435
+ field: "role",
1436
+ value: "owner"
1437
+ }]
1438
+ });
1439
+ if (ownerMember === void 0 || ownerMember === null) return targetEmail;
1440
+ const ownerUser = await ctx.context.adapter.findOne({
1441
+ model: "user",
1442
+ where: [{
1443
+ field: "id",
1444
+ value: ownerMember.userId
1445
+ }]
1446
+ });
1447
+ return ownerUser?.email !== void 0 && ownerUser.email !== "" ? ownerUser.email : targetEmail;
1448
+ }
1449
+ async function handleProratedUpgrade(ctx, options, input) {
1450
+ const store = createBillingStore(ctx);
1451
+ const existingSub = input.subscriptionId === void 0 ? await store.findCurrentSubscription(input.referenceId, normalizeSubscriptionGroup(input.plan.group)) : await store.findSubscriptionById(input.subscriptionId);
1452
+ 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;
1453
+ const now = /* @__PURE__ */ new Date();
1454
+ const periodEnd = new Date(existingSub.periodEnd);
1455
+ const periodStart = new Date(existingSub.periodStart);
1456
+ const totalDays = Math.max(1, Math.ceil((periodEnd.getTime() - periodStart.getTime()) / 864e5));
1457
+ const remainingDays = Math.max(0, Math.ceil((periodEnd.getTime() - now.getTime()) / 864e5));
1458
+ let oldAmount = 0;
1459
+ if (existingSub.plan !== "") {
1460
+ const oldPlan = await getPlanByName(options, existingSub.plan) ?? await store.findPlanByName(existingSub.plan);
1461
+ if (oldPlan !== void 0 && oldPlan !== null) oldAmount = calculatePlanAmount(oldPlan, existingSub.seats ?? 1);
1462
+ }
1463
+ let membersCount = 1;
1464
+ let newSeatCount;
1465
+ let newAmount;
1466
+ try {
1467
+ assertLocallyManagedSubscription(existingSub, "plan or seat changes");
1468
+ if (getPlanSeatAmount(input.plan) !== void 0) {
1469
+ const members = await store.listMembers(input.referenceId);
1470
+ membersCount = members.length > 0 ? members.length : 1;
1471
+ }
1472
+ newSeatCount = input.quantity ?? existingSub.seats ?? membersCount;
1473
+ newAmount = calculatePlanAmount(input.plan, newSeatCount);
1474
+ } catch (error) {
1475
+ throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
1476
+ }
1477
+ const costDifference = newAmount - oldAmount;
1478
+ const prorationMetadata = createProrationMetadata({
1479
+ subscriptionId: existingSub.id,
1480
+ referenceId: input.referenceId,
1481
+ newPlan: input.plan.name.toLowerCase(),
1482
+ oldPlan: existingSub.plan,
1483
+ newSeatCount,
1484
+ remainingDays
1485
+ });
1486
+ const serializedProrationMetadata = stringifyPaystackMetadata(prorationMetadata);
1487
+ const proratedAmount = Math.round(costDifference / totalDays * remainingDays);
1488
+ const hasCharge = costDifference > 0 && remainingDays > 0;
1489
+ if (hasCharge && proratedAmount < 5e3) throw new APIError("BAD_REQUEST", {
1490
+ message: "Prorated upgrade amount is below Paystack's minimum charge. Schedule the change for period end instead.",
1491
+ status: 400
1492
+ });
1493
+ const credentials = hasCharge ? await readPaystackPaymentCredentials(ctx.context.adapter, options, existingSub.id) : null;
1494
+ const hasAuthorization = credentials?.authorizationCode !== void 0 && credentials.authorizationCode !== null && credentials.authorizationCode !== "";
1495
+ return runSubscriptionOperation(ctx, options, {
1496
+ actor: { id: input.userId ?? existingSub.userId },
1497
+ referenceId: input.referenceId,
1498
+ kind: hasCharge ? hasAuthorization ? "proration-charge" : "proration-initialize" : "local-change",
1499
+ subscription: existingSub,
1500
+ intent: {
1501
+ plan: input.plan.name.toLowerCase(),
1502
+ amount: hasCharge ? proratedAmount : 0,
1503
+ currency: input.finalCurrency,
1504
+ interval: input.plan.interval,
1505
+ quantity: newSeatCount,
1506
+ groupId: normalizeSubscriptionGroup(input.plan.group),
1507
+ callbackURL: input.callbackURL
1508
+ }
1509
+ }, async (providerReference, setPhase) => {
1510
+ let completedProrationReference;
1511
+ if (costDifference > 0 && remainingDays > 0) {
1512
+ const paystack = createPaystackAdapter(options.paystackClient);
1513
+ if (credentials?.authorizationCode !== void 0 && credentials.authorizationCode !== null && credentials.authorizationCode !== "") {
1514
+ const sdkRes = await paystack.chargeAuthorization({
1515
+ email: input.targetEmail,
1516
+ amount: proratedAmount,
1517
+ authorization_code: credentials.authorizationCode,
1518
+ reference: providerReference ?? `upg_${existingSub.id}_${Date.now()}_${Math.random().toString(36).substring(7)}`,
1519
+ metadata: serializedProrationMetadata
1520
+ });
1521
+ if (providerReference !== void 0 && sdkRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
1522
+ if (sdkRes?.status !== "success") throw new APIError("BAD_REQUEST", { message: "Failed to process prorated charge via saved authorization." });
1523
+ setPhase("persistence");
1524
+ await store.createTransaction({
1525
+ reference: sdkRes.reference ?? "",
1526
+ paystackId: sdkRes.id !== void 0 && sdkRes.id !== null ? String(sdkRes.id) : void 0,
1527
+ referenceId: input.referenceId,
1528
+ userId: input.userId,
1529
+ amount: sdkRes.amount ?? proratedAmount,
1530
+ currency: sdkRes.currency ?? input.finalCurrency,
1531
+ status: "success",
1532
+ plan: input.plan.name.toLowerCase(),
1533
+ metadata: serializedProrationMetadata,
1534
+ createdAt: /* @__PURE__ */ new Date(),
1535
+ updatedAt: /* @__PURE__ */ new Date()
1536
+ });
1537
+ completedProrationReference = sdkRes.reference ?? void 0;
1538
+ } else {
1539
+ const initRes = await paystack.initializeTransaction({
1540
+ ...providerReference !== void 0 ? { reference: providerReference } : {},
1541
+ email: input.targetEmail,
1542
+ amount: proratedAmount,
1543
+ currency: input.finalCurrency,
1544
+ callback_url: input.callbackURL ?? void 0,
1545
+ metadata: serializedProrationMetadata,
1546
+ ...input.allowedSubscriptionChannels !== void 0 ? { channels: input.allowedSubscriptionChannels } : {}
1547
+ });
1548
+ if (providerReference !== void 0 && initRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
1549
+ setPhase("persistence");
1550
+ await store.createTransaction({
1551
+ reference: initRes?.reference ?? "",
1552
+ referenceId: input.referenceId,
1553
+ userId: input.userId,
1554
+ amount: proratedAmount,
1555
+ currency: input.finalCurrency,
1556
+ status: "pending",
1557
+ plan: input.plan.name.toLowerCase(),
1558
+ metadata: serializedProrationMetadata,
1559
+ createdAt: /* @__PURE__ */ new Date(),
1560
+ updatedAt: /* @__PURE__ */ new Date()
1561
+ });
1562
+ return {
1563
+ kind: "checkout",
1564
+ url: initRes?.authorization_url,
1565
+ reference: initRes?.reference,
1566
+ accessCode: initRes?.access_code,
1567
+ redirect: true
1568
+ };
1569
+ }
1570
+ }
1571
+ setPhase("persistence");
1572
+ await store.updateSubscription(existingSub.id, {
1573
+ plan: input.plan.name,
1574
+ seats: newSeatCount,
1575
+ ...completedProrationReference !== void 0 ? { transactionReference: completedProrationReference } : {},
1576
+ updatedAt: /* @__PURE__ */ new Date()
1577
+ });
1578
+ return {
1579
+ kind: "prorated",
1580
+ status: "success",
1581
+ message: "Subscription successfully upgraded with prorated charge.",
1582
+ prorated: true
1583
+ };
1584
+ });
1376
1585
  }
1377
1586
  //#endregion
1378
1587
  //#region src/routes.ts
@@ -1417,200 +1626,204 @@ const paystackWebhook = (options, path = "/webhook") => {
1417
1626
  const reference = data?.reference;
1418
1627
  const eventId = createHash("sha256").update(payload).digest("hex");
1419
1628
  const store = createBillingStore(ctx);
1420
- let webhookEventsAvailable = true;
1421
- let existingEvent = null;
1629
+ let claimStatus;
1422
1630
  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 {
1631
+ let existingEvent = await store.findWebhookEvent(eventId);
1632
+ if (existingEvent?.status === "processed") return ctx.json({ received: true });
1633
+ if (existingEvent === null) try {
1634
+ existingEvent = await store.createWebhookEvent({
1635
+ eventId,
1636
+ eventType: eventName,
1637
+ reference: reference ?? null,
1638
+ payload,
1639
+ status: "pending",
1640
+ createdAt: /* @__PURE__ */ new Date(),
1641
+ updatedAt: /* @__PURE__ */ new Date()
1642
+ });
1643
+ } catch (error) {
1440
1644
  existingEvent = await store.findWebhookEvent(eventId);
1441
- if (existingEvent?.status === "processed") return ctx.json({ received: true });
1442
- } catch {}
1443
- webhookEventsAvailable = false;
1444
- }
1445
- if (eventName === "charge.success") {
1446
- const reference = data?.reference;
1447
- const paystackIdRaw = data?.id;
1448
- const paystackId = paystackIdRaw !== void 0 && paystackIdRaw !== null ? String(paystackIdRaw) : void 0;
1449
- if (reference !== void 0 && reference !== null && reference !== "") {
1450
- try {
1645
+ if (!existingEvent) throw error;
1646
+ }
1647
+ if (existingEvent.status === "processed") return ctx.json({ received: true });
1648
+ if (existingEvent.status.startsWith("processing:") && new Date(existingEvent.updatedAt).getTime() > Date.now() - 3e5) throw new Error("Webhook is already processing; retry later.");
1649
+ claimStatus = `processing:${randomUUID()}`;
1650
+ if (await ctx.context.adapter.update({
1651
+ model: PAYSTACK_MODELS.webhookEvent,
1652
+ where: [{
1653
+ field: "eventId",
1654
+ value: eventId
1655
+ }, {
1656
+ field: "status",
1657
+ value: existingEvent.status
1658
+ }],
1659
+ update: {
1660
+ status: claimStatus,
1661
+ updatedAt: /* @__PURE__ */ new Date()
1662
+ }
1663
+ }) === null) throw new Error("Webhook claim was lost; retry later.");
1664
+ if (eventName === "charge.success") {
1665
+ const reference = data?.reference;
1666
+ const paystackIdRaw = data?.id;
1667
+ const paystackId = paystackIdRaw !== void 0 && paystackIdRaw !== null ? String(paystackIdRaw) : void 0;
1668
+ if (reference !== void 0 && reference !== null && reference !== "") {
1669
+ try {
1670
+ await ctx.context.adapter.update({
1671
+ model: "paystackTransaction",
1672
+ update: {
1673
+ status: "success",
1674
+ paystackId,
1675
+ updatedAt: /* @__PURE__ */ new Date()
1676
+ },
1677
+ where: [{
1678
+ field: "reference",
1679
+ value: reference
1680
+ }]
1681
+ });
1682
+ } catch (e) {
1683
+ ctx.context.logger.warn("Failed to update transaction status for charge.success", e);
1684
+ throw e;
1685
+ }
1686
+ try {
1687
+ const transaction = await ctx.context.adapter.findOne({
1688
+ model: "paystackTransaction",
1689
+ where: [{
1690
+ field: "reference",
1691
+ value: reference
1692
+ }]
1693
+ });
1694
+ if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "") {
1695
+ if (options.paystackClient !== void 0 && options.paystackClient !== null) await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
1696
+ }
1697
+ } catch (e) {
1698
+ ctx.context.logger.warn("Failed to sync product quantity", e);
1699
+ throw e;
1700
+ }
1701
+ }
1702
+ }
1703
+ if (eventName === "charge.failure") {
1704
+ const reference = data?.reference;
1705
+ if (reference !== void 0 && reference !== null && reference !== "") try {
1451
1706
  await ctx.context.adapter.update({
1452
1707
  model: "paystackTransaction",
1453
1708
  update: {
1454
- status: "success",
1455
- paystackId,
1709
+ status: "failed",
1456
1710
  updatedAt: /* @__PURE__ */ new Date()
1457
1711
  },
1458
1712
  where: [{
1459
- field: "reference",
1460
- value: reference
1461
- }]
1462
- });
1463
- } catch (e) {
1464
- ctx.context.logger.warn("Failed to update transaction status for charge.success", e);
1465
- }
1466
- try {
1467
- const transaction = await ctx.context.adapter.findOne({
1468
- model: "paystackTransaction",
1469
- where: [{
1470
- field: "reference",
1471
- value: reference
1472
- }]
1473
- });
1474
- if (transaction !== void 0 && transaction !== null && transaction.product !== void 0 && transaction.product !== null && transaction.product !== "") {
1475
- if (options.paystackClient !== void 0 && options.paystackClient !== null) await syncProductQuantityFromPaystack(ctx, transaction.product, options.paystackClient);
1476
- }
1477
- } catch (e) {
1478
- ctx.context.logger.warn("Failed to sync product quantity", e);
1479
- }
1480
- }
1481
- }
1482
- if (eventName === "charge.failure") {
1483
- const reference = data?.reference;
1484
- if (reference !== void 0 && reference !== null && reference !== "") try {
1485
- await ctx.context.adapter.update({
1486
- model: "paystackTransaction",
1487
- update: {
1488
- status: "failed",
1489
- updatedAt: /* @__PURE__ */ new Date()
1490
- },
1491
- where: [{
1492
- field: "reference",
1493
- value: reference
1494
- }]
1495
- });
1496
- } catch (e) {
1497
- ctx.context.logger.warn("Failed to update transaction status for charge.failure", e);
1498
- }
1499
- }
1500
- if (options.subscription?.enabled === true) try {
1501
- if (eventName === "subscription.create") {
1502
- const subscriptionData = data;
1503
- const subscriptionCode = subscriptionData.subscription_code ?? "";
1504
- const customerCode = subscriptionData.customer?.customer_code;
1505
- const planCode = subscriptionData.plan?.plan_code;
1506
- const metadataObj = parsePaystackMetadata(subscriptionData.metadata);
1507
- const referenceIdFromMetadata = typeof metadataObj.referenceId === "string" ? metadataObj.referenceId : void 0;
1508
- let planNameFromMetadata = typeof metadataObj.plan === "string" ? metadataObj.plan : void 0;
1509
- if (typeof planNameFromMetadata === "string") planNameFromMetadata = planNameFromMetadata.toLowerCase();
1510
- const plans = await getPlans(options.subscription);
1511
- const planFromCode = planCode !== void 0 && planCode !== null && planCode !== "" ? plans.find((p) => p.planCode === planCode) : void 0;
1512
- const groupIdFromMetadata = typeof metadataObj.groupId === "string" ? normalizeSubscriptionGroup(metadataObj.groupId) : normalizeSubscriptionGroup(planFromCode?.group);
1513
- const planPart = planFromCode?.name ?? planNameFromMetadata;
1514
- const planName = planPart !== void 0 && planPart !== null && planPart !== "" ? planPart.toLowerCase() : void 0;
1515
- if (subscriptionCode !== void 0 && subscriptionCode !== null && subscriptionCode !== "") {
1516
- const where = [];
1517
- if (referenceIdFromMetadata !== void 0 && referenceIdFromMetadata !== null && referenceIdFromMetadata !== "") where.push({
1518
- field: "referenceId",
1519
- value: referenceIdFromMetadata
1520
- });
1521
- else if (customerCode !== void 0 && customerCode !== null && customerCode !== "") where.push({
1522
- field: "customerCode",
1523
- value: customerCode
1524
- });
1525
- if (planName !== void 0 && planName !== null && planName !== "") where.push({
1526
- field: "plan",
1527
- value: planName
1713
+ field: "reference",
1714
+ value: reference
1715
+ }]
1528
1716
  });
1529
- if (where.length > 0) {
1530
- const subscription = (await ctx.context.adapter.findMany({
1531
- model: PAYSTACK_MODELS.subscription,
1532
- where
1533
- }))?.find((candidate) => groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
1534
- if (subscription !== void 0 && subscription !== null) {
1535
- const plan = planFromCode ?? (planName !== void 0 && planName !== null && planName !== "" ? await getPlanByName(options, planName) : void 0);
1536
- const now = /* @__PURE__ */ new Date();
1537
- const persistedSubscription = {
1538
- ...subscription,
1539
- subscriptionCode,
1540
- status: "active",
1541
- billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
1542
- periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
1543
- updatedAt: now
1544
- };
1545
- await ctx.context.adapter.update({
1717
+ } catch (e) {
1718
+ ctx.context.logger.warn("Failed to update transaction status for charge.failure", e);
1719
+ throw e;
1720
+ }
1721
+ }
1722
+ if (options.subscription?.enabled === true) try {
1723
+ if (eventName === "subscription.create") {
1724
+ const subscriptionData = data;
1725
+ const subscriptionCode = subscriptionData.subscription_code ?? "";
1726
+ const customerCode = subscriptionData.customer?.customer_code;
1727
+ const planCode = subscriptionData.plan?.plan_code;
1728
+ const metadataObj = parsePaystackMetadata(subscriptionData.metadata);
1729
+ const referenceIdFromMetadata = typeof metadataObj.referenceId === "string" ? metadataObj.referenceId : void 0;
1730
+ let planNameFromMetadata = typeof metadataObj.plan === "string" ? metadataObj.plan : void 0;
1731
+ if (typeof planNameFromMetadata === "string") planNameFromMetadata = planNameFromMetadata.toLowerCase();
1732
+ const plans = await getPlans(options.subscription);
1733
+ const planFromCode = planCode !== void 0 && planCode !== null && planCode !== "" ? plans.find((p) => p.planCode === planCode) : void 0;
1734
+ const groupIdFromMetadata = typeof metadataObj.groupId === "string" ? normalizeSubscriptionGroup(metadataObj.groupId) : normalizeSubscriptionGroup(planFromCode?.group);
1735
+ const planPart = planFromCode?.name ?? planNameFromMetadata;
1736
+ const planName = planPart !== void 0 && planPart !== null && planPart !== "" ? planPart.toLowerCase() : void 0;
1737
+ if (subscriptionCode !== void 0 && subscriptionCode !== null && subscriptionCode !== "") {
1738
+ const where = [];
1739
+ if (referenceIdFromMetadata !== void 0 && referenceIdFromMetadata !== null && referenceIdFromMetadata !== "") where.push({
1740
+ field: "referenceId",
1741
+ value: referenceIdFromMetadata
1742
+ });
1743
+ else if (customerCode !== void 0 && customerCode !== null && customerCode !== "") where.push({
1744
+ field: "customerCode",
1745
+ value: customerCode
1746
+ });
1747
+ if (planName !== void 0 && planName !== null && planName !== "") where.push({
1748
+ field: "plan",
1749
+ value: planName
1750
+ });
1751
+ if (where.length > 0) {
1752
+ const subscription = (await ctx.context.adapter.findMany({
1546
1753
  model: PAYSTACK_MODELS.subscription,
1547
- update: {
1548
- subscriptionCode: persistedSubscription.subscriptionCode,
1549
- status: persistedSubscription.status,
1550
- billingInterval: persistedSubscription.billingInterval,
1551
- periodEnd: persistedSubscription.periodEnd,
1552
- updatedAt: persistedSubscription.updatedAt
1553
- },
1554
- where: [{
1555
- field: "id",
1556
- value: subscription.id
1557
- }]
1558
- });
1559
- await createBillingStore(ctx).retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
1560
- if (plan !== void 0 && plan !== null) {
1561
- const callbackData = {
1562
- event,
1563
- subscription: persistedSubscription,
1564
- plan
1754
+ where
1755
+ }))?.find((candidate) => candidate.status !== "canceled" && (candidate.subscriptionCode === subscriptionCode || candidate.status === "incomplete" || candidate.status === "trialing" && (candidate.subscriptionCode === void 0 || candidate.subscriptionCode === null || candidate.subscriptionCode === "")) && groupIdFromMetadata === null ? candidate.groupId === void 0 || candidate.groupId === null || candidate.groupId === "" : candidate.groupId === groupIdFromMetadata);
1756
+ if (subscription !== void 0 && subscription !== null) {
1757
+ const plan = planFromCode ?? (planName !== void 0 && planName !== null && planName !== "" ? await getPlanByName(options, planName) : void 0);
1758
+ const now = /* @__PURE__ */ new Date();
1759
+ const persistedSubscription = {
1760
+ ...subscription,
1761
+ subscriptionCode,
1762
+ status: "active",
1763
+ billingInterval: plan?.interval ?? subscription.billingInterval ?? null,
1764
+ periodEnd: subscriptionData.next_payment_date !== void 0 && subscriptionData.next_payment_date !== null ? new Date(subscriptionData.next_payment_date) : subscription.periodEnd,
1765
+ updatedAt: now
1565
1766
  };
1566
- for (const callback of [
1567
- options.subscription.onSubscriptionComplete,
1568
- options.subscription.onSubscriptionCreated,
1569
- options.subscription.onSubscriptionUpdate
1570
- ]) try {
1571
- await callback?.(callbackData, ctx);
1572
- } catch (error) {
1573
- ctx.context.logger.error("Paystack subscription callback failed", error);
1574
- }
1575
- if (subscription.status === "trialing") try {
1576
- await plan.freeTrial?.onTrialEnd?.(persistedSubscription);
1577
- } catch (error) {
1578
- ctx.context.logger.error("Paystack trial end callback failed", error);
1767
+ await ctx.context.adapter.update({
1768
+ model: PAYSTACK_MODELS.subscription,
1769
+ update: {
1770
+ subscriptionCode: persistedSubscription.subscriptionCode,
1771
+ status: persistedSubscription.status,
1772
+ billingInterval: persistedSubscription.billingInterval,
1773
+ periodEnd: persistedSubscription.periodEnd,
1774
+ updatedAt: persistedSubscription.updatedAt
1775
+ },
1776
+ where: [{
1777
+ field: "id",
1778
+ value: subscription.id
1779
+ }]
1780
+ });
1781
+ await createBillingStore(ctx).retireCompetingSubscriptions(subscription.referenceId, subscription.groupId ?? null, subscription.id);
1782
+ if (plan !== void 0 && plan !== null) {
1783
+ const callbackData = {
1784
+ event,
1785
+ subscription: persistedSubscription,
1786
+ plan
1787
+ };
1788
+ for (const callback of [
1789
+ options.subscription.onSubscriptionComplete,
1790
+ options.subscription.onSubscriptionCreated,
1791
+ options.subscription.onSubscriptionUpdate
1792
+ ]) try {
1793
+ await callback?.(callbackData, ctx);
1794
+ } catch (error) {
1795
+ ctx.context.logger.error("Paystack subscription callback failed", error);
1796
+ throw error;
1797
+ }
1798
+ if (subscription.status === "trialing") try {
1799
+ await plan.freeTrial?.onTrialEnd?.(persistedSubscription);
1800
+ } catch (error) {
1801
+ ctx.context.logger.error("Paystack trial end callback failed", error);
1802
+ throw error;
1803
+ }
1579
1804
  }
1580
1805
  }
1581
1806
  }
1582
1807
  }
1583
1808
  }
1584
- }
1585
- if (eventName === "subscription.disable" || eventName === "subscription.not_renew") {
1586
- const subscriptionData = data;
1587
- const subscriptionCode = subscriptionData.subscription_code ?? "";
1588
- if (subscriptionCode !== "") {
1589
- const existing = await ctx.context.adapter.findOne({
1590
- model: PAYSTACK_MODELS.subscription,
1591
- where: [{
1592
- field: "subscriptionCode",
1593
- value: subscriptionCode
1594
- }]
1595
- });
1596
- let newStatus = "canceled";
1597
- const nextPaymentDate = subscriptionData.next_payment_date;
1598
- const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : existing?.periodEnd !== void 0 && existing.periodEnd !== null ? new Date(existing.periodEnd) : void 0;
1599
- if (periodEnd !== void 0 && periodEnd.getTime() > Date.now()) newStatus = "active";
1600
- const now = /* @__PURE__ */ new Date();
1601
- const persistedSubscription = existing === null || existing === void 0 ? void 0 : {
1602
- ...existing,
1603
- status: newStatus,
1604
- cancelAtPeriodEnd: newStatus === "active",
1605
- cancelAt: newStatus === "active" ? periodEnd ?? null : null,
1606
- canceledAt: now,
1607
- endedAt: newStatus === "canceled" ? now : null,
1608
- ...periodEnd ? { periodEnd } : {},
1609
- updatedAt: now
1610
- };
1611
- await ctx.context.adapter.update({
1612
- model: PAYSTACK_MODELS.subscription,
1613
- update: {
1809
+ if (eventName === "subscription.disable" || eventName === "subscription.not_renew") {
1810
+ const subscriptionData = data;
1811
+ const subscriptionCode = subscriptionData.subscription_code ?? "";
1812
+ if (subscriptionCode !== "") {
1813
+ const existing = await ctx.context.adapter.findOne({
1814
+ model: PAYSTACK_MODELS.subscription,
1815
+ where: [{
1816
+ field: "subscriptionCode",
1817
+ value: subscriptionCode
1818
+ }]
1819
+ });
1820
+ let newStatus = "canceled";
1821
+ const nextPaymentDate = subscriptionData.next_payment_date;
1822
+ const periodEnd = nextPaymentDate !== void 0 && nextPaymentDate !== null && nextPaymentDate !== "" ? new Date(nextPaymentDate) : existing?.periodEnd !== void 0 && existing.periodEnd !== null ? new Date(existing.periodEnd) : void 0;
1823
+ if (periodEnd !== void 0 && periodEnd.getTime() > Date.now()) newStatus = "active";
1824
+ const now = /* @__PURE__ */ new Date();
1825
+ const persistedSubscription = existing === null || existing === void 0 ? void 0 : {
1826
+ ...existing,
1614
1827
  status: newStatus,
1615
1828
  cancelAtPeriodEnd: newStatus === "active",
1616
1829
  cancelAt: newStatus === "active" ? periodEnd ?? null : null,
@@ -1618,88 +1831,129 @@ const paystackWebhook = (options, path = "/webhook") => {
1618
1831
  endedAt: newStatus === "canceled" ? now : null,
1619
1832
  ...periodEnd ? { periodEnd } : {},
1620
1833
  updatedAt: now
1621
- },
1622
- where: [{
1623
- field: "subscriptionCode",
1624
- value: subscriptionCode
1625
- }]
1626
- });
1627
- if (persistedSubscription !== void 0) {
1628
- try {
1629
- await options.subscription.onSubscriptionCancel?.({
1630
- event,
1631
- subscription: persistedSubscription
1632
- }, ctx);
1633
- } catch (error) {
1634
- ctx.context.logger.error("Paystack subscription cancel callback failed", error);
1635
- }
1636
- const plan = await getPlanByName(options, persistedSubscription.plan);
1637
- if (plan !== void 0 && plan !== null) {
1834
+ };
1835
+ await ctx.context.adapter.update({
1836
+ model: PAYSTACK_MODELS.subscription,
1837
+ update: {
1838
+ status: newStatus,
1839
+ cancelAtPeriodEnd: newStatus === "active",
1840
+ cancelAt: newStatus === "active" ? periodEnd ?? null : null,
1841
+ canceledAt: now,
1842
+ endedAt: newStatus === "canceled" ? now : null,
1843
+ ...periodEnd ? { periodEnd } : {},
1844
+ updatedAt: now
1845
+ },
1846
+ where: [{
1847
+ field: "subscriptionCode",
1848
+ value: subscriptionCode
1849
+ }]
1850
+ });
1851
+ if (persistedSubscription !== void 0) {
1638
1852
  try {
1639
- await options.subscription.onSubscriptionUpdate?.({
1853
+ await options.subscription.onSubscriptionCancel?.({
1640
1854
  event,
1641
- subscription: persistedSubscription,
1642
- plan
1855
+ subscription: persistedSubscription
1643
1856
  }, ctx);
1644
1857
  } catch (error) {
1645
- ctx.context.logger.error("Paystack subscription update callback failed", error);
1858
+ ctx.context.logger.error("Paystack subscription cancel callback failed", error);
1646
1859
  }
1647
- if (existing?.status === "trialing" && newStatus === "canceled") try {
1648
- await plan.freeTrial?.onTrialExpired?.(persistedSubscription);
1649
- } catch (error) {
1650
- ctx.context.logger.error("Paystack trial expiry callback failed", error);
1860
+ const plan = await getPlanByName(options, persistedSubscription.plan);
1861
+ if (plan !== void 0 && plan !== null) {
1862
+ try {
1863
+ await options.subscription.onSubscriptionUpdate?.({
1864
+ event,
1865
+ subscription: persistedSubscription,
1866
+ plan
1867
+ }, ctx);
1868
+ } catch (error) {
1869
+ ctx.context.logger.error("Paystack subscription update callback failed", error);
1870
+ }
1871
+ if (existing?.status === "trialing" && newStatus === "canceled") try {
1872
+ await plan.freeTrial?.onTrialExpired?.(persistedSubscription);
1873
+ } catch (error) {
1874
+ ctx.context.logger.error("Paystack trial expiry callback failed", error);
1875
+ }
1651
1876
  }
1652
1877
  }
1653
1878
  }
1654
1879
  }
1655
- }
1656
- if (eventName === "charge.success" || eventName === "invoice.update") {
1657
- const subscriptionCodeRaw = (data?.subscription)?.subscription_code ?? data?.subscription_code;
1658
- const subscriptionCode = subscriptionCodeRaw !== void 0 && subscriptionCodeRaw !== null && subscriptionCodeRaw !== "" ? subscriptionCodeRaw : void 0;
1659
- if (subscriptionCode !== void 0) {
1660
- const existingSub = await ctx.context.adapter.findOne({
1661
- model: PAYSTACK_MODELS.subscription,
1662
- where: [{
1663
- field: "subscriptionCode",
1664
- value: subscriptionCode
1665
- }]
1666
- });
1667
- if (existingSub !== void 0 && existingSub !== null && existingSub.pendingPlan !== void 0 && existingSub.pendingPlan !== null && existingSub.pendingPlan !== "") await ctx.context.adapter.update({
1668
- model: PAYSTACK_MODELS.subscription,
1669
- update: {
1670
- plan: existingSub.pendingPlan,
1671
- pendingPlan: null,
1672
- updatedAt: /* @__PURE__ */ new Date()
1673
- },
1674
- where: [{
1675
- field: "id",
1676
- value: existingSub.id
1677
- }]
1678
- });
1880
+ if (eventName === "charge.success" || eventName === "invoice.update") {
1881
+ const subscriptionCodeRaw = (data?.subscription)?.subscription_code ?? data?.subscription_code;
1882
+ const subscriptionCode = subscriptionCodeRaw !== void 0 && subscriptionCodeRaw !== null && subscriptionCodeRaw !== "" ? subscriptionCodeRaw : void 0;
1883
+ if (subscriptionCode !== void 0) {
1884
+ const existingSub = await ctx.context.adapter.findOne({
1885
+ model: PAYSTACK_MODELS.subscription,
1886
+ where: [{
1887
+ field: "subscriptionCode",
1888
+ value: subscriptionCode
1889
+ }]
1890
+ });
1891
+ if (existingSub !== void 0 && existingSub !== null && existingSub.pendingPlan !== void 0 && existingSub.pendingPlan !== null && existingSub.pendingPlan !== "") await ctx.context.adapter.update({
1892
+ model: PAYSTACK_MODELS.subscription,
1893
+ update: {
1894
+ plan: existingSub.pendingPlan,
1895
+ pendingPlan: null,
1896
+ updatedAt: /* @__PURE__ */ new Date()
1897
+ },
1898
+ where: [{
1899
+ field: "id",
1900
+ value: existingSub.id
1901
+ }]
1902
+ });
1903
+ }
1679
1904
  }
1905
+ } catch (_e) {
1906
+ ctx.context.logger.error("Failed to sync Paystack webhook event", _e);
1907
+ throw _e;
1680
1908
  }
1681
- } catch (_e) {
1682
- ctx.context.logger.error("Failed to sync Paystack webhook event", _e);
1909
+ await options.onEvent?.(event);
1910
+ if (await ctx.context.adapter.update({
1911
+ model: PAYSTACK_MODELS.webhookEvent,
1912
+ where: [{
1913
+ field: "eventId",
1914
+ value: eventId
1915
+ }, {
1916
+ field: "status",
1917
+ value: claimStatus
1918
+ }],
1919
+ update: {
1920
+ status: "processed",
1921
+ processedAt: /* @__PURE__ */ new Date(),
1922
+ updatedAt: /* @__PURE__ */ new Date()
1923
+ }
1924
+ }) === null) throw new Error("Webhook processing lease was lost.");
1925
+ return ctx.json({ received: true });
1926
+ } catch (error) {
1927
+ if (claimStatus !== void 0) await ctx.context.adapter.update({
1928
+ model: PAYSTACK_MODELS.webhookEvent,
1929
+ where: [{
1930
+ field: "eventId",
1931
+ value: eventId
1932
+ }, {
1933
+ field: "status",
1934
+ value: claimStatus
1935
+ }],
1936
+ update: {
1937
+ status: "pending",
1938
+ updatedAt: /* @__PURE__ */ new Date()
1939
+ }
1940
+ });
1941
+ ctx.context.logger.error("Paystack webhook processing failed; delivery must be retried", error);
1942
+ throw new APIError("SERVICE_UNAVAILABLE", { message: "Webhook processing failed; retry delivery." });
1683
1943
  }
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
- });
1690
- return ctx.json({ received: true });
1691
1944
  });
1692
1945
  };
1693
1946
  const initializeTransaction = (options, path = "/initialize-transaction") => {
1694
1947
  const subscriptionOptions = options.subscription;
1948
+ const useMiddlewares = subscriptionOptions?.enabled === true ? [
1949
+ sessionMiddleware,
1950
+ originCheck,
1951
+ referenceMiddleware(options, "initialize-transaction")
1952
+ ] : [sessionMiddleware, originCheck];
1695
1953
  return createAuthEndpoint(path, {
1696
1954
  method: "POST",
1697
1955
  body: initializeTransactionBodySchema,
1698
- use: subscriptionOptions?.enabled === true ? [
1699
- sessionMiddleware,
1700
- originCheck,
1701
- referenceMiddleware(options, "initialize-transaction")
1702
- ] : [sessionMiddleware, originCheck]
1956
+ use: useMiddlewares
1703
1957
  }, async (ctx) => {
1704
1958
  const paystack = getPaystackOps(options.paystackClient);
1705
1959
  const { plan: planName, product: productName, amount: bodyAmount, currency, email, metadata: extraMetadata, callbackURL, quantity, scheduleAtPeriodEnd, cancelAtPeriodEnd, prorateAndCharge, subscriptionId } = ctx.body;
@@ -1775,8 +2029,8 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
1775
2029
  message: "Either 'plan', 'product', or 'amount' is required to initialize a transaction.",
1776
2030
  status: 400
1777
2031
  });
1778
- let amount = bodyAmount ?? product?.price ?? product?.amount;
1779
- const finalCurrency = currency ?? product?.currency ?? product?.currency ?? plan?.currency ?? "NGN";
2032
+ let amount = plan !== void 0 ? plan.amount : product ? product.price ?? product.amount : bodyAmount;
2033
+ const finalCurrency = plan !== void 0 || product ? product?.currency ?? product?.currency ?? plan?.currency ?? "NGN" : currency ?? "NGN";
1780
2034
  const referenceIdFromCtx = ctx.context.referenceId;
1781
2035
  const referenceId = ctx.body.referenceId ?? referenceIdFromCtx ?? session.user.id;
1782
2036
  const groupId = normalizeSubscriptionGroup(plan?.group);
@@ -1785,13 +2039,17 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
1785
2039
  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
2040
  }
1787
2041
  const scheduledChange = await scheduleSubscriptionLifecycleChange(ctx, {
2042
+ userId: user.id,
1788
2043
  referenceId,
1789
2044
  subscriptionId,
1790
2045
  plan,
1791
2046
  scheduleAtPeriodEnd,
1792
2047
  cancelAtPeriodEnd
1793
- });
2048
+ }, options);
1794
2049
  if (scheduledChange !== null) return ctx.json(scheduledChange);
2050
+ let validatedQuantity = quantity ?? 1;
2051
+ if (product && amount !== void 0) amount *= quantity ?? 1;
2052
+ if (amount !== void 0 && (!Number.isSafeInteger(amount) || amount <= 0)) throw new APIError("BAD_REQUEST", { message: "Catalog amount must be a positive safe integer." });
1795
2053
  if (plan !== void 0) try {
1796
2054
  if (getPlanSeatAmount(plan) !== void 0) {
1797
2055
  const members = await ctx.context.adapter.findMany({
@@ -1802,7 +2060,9 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
1802
2060
  }]
1803
2061
  });
1804
2062
  const seatCount = members.length > 0 ? members.length : 1;
1805
- amount = calculatePlanAmount(plan, quantity ?? seatCount);
2063
+ const quantityToUse = quantity ?? seatCount;
2064
+ validatedQuantity = quantityToUse;
2065
+ amount = calculatePlanAmount(plan, quantityToUse);
1806
2066
  }
1807
2067
  } catch (error) {
1808
2068
  throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Invalid seat configuration for plan." });
@@ -1815,7 +2075,14 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
1815
2075
  plan
1816
2076
  });
1817
2077
  const { trialStart, trialEnd } = trial;
1818
- try {
2078
+ const normalizeInitializationError = (error) => {
2079
+ ctx.context.logger.error("Failed to initialize Paystack transaction", error);
2080
+ return new APIError("BAD_REQUEST", {
2081
+ code: "FAILED_TO_INITIALIZE_TRANSACTION",
2082
+ message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_INITIALIZE_TRANSACTION.message
2083
+ });
2084
+ };
2085
+ const prepared = await (async () => {
1819
2086
  const targetEmail = await resolveCheckoutTargetEmail(ctx, options, {
1820
2087
  email,
1821
2088
  referenceId,
@@ -1857,108 +2124,136 @@ const initializeTransaction = (options, path = "/initialize-transaction") => {
1857
2124
  callbackURL,
1858
2125
  allowedSubscriptionChannels
1859
2126
  });
1860
- if (proration?.kind === "checkout") return ctx.json({
2127
+ if (proration?.kind === "checkout") return { earlyResult: {
1861
2128
  kind: "checkout",
1862
2129
  url: proration.url ?? "",
1863
2130
  reference: proration.reference ?? "",
1864
2131
  accessCode: proration.accessCode ?? "",
1865
2132
  redirect: proration.redirect
1866
- });
1867
- if (proration?.kind === "prorated") return ctx.json({
2133
+ } };
2134
+ if (proration?.kind === "prorated") return { earlyResult: {
1868
2135
  kind: "prorated",
1869
2136
  status: proration.status,
1870
2137
  message: proration.message,
1871
2138
  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);
2139
+ } };
1884
2140
  }
1885
- else {
2141
+ if (plan !== void 0) {
2142
+ if (trialStart !== void 0) initBody.amount = 5e3;
2143
+ else {
2144
+ initBody.plan = plan.planCode;
2145
+ initBody.invoice_limit = plan.invoiceLimit;
2146
+ let finalAmount;
2147
+ if (amount !== void 0 && amount !== null) {
2148
+ finalAmount = amount;
2149
+ initBody.quantity = 1;
2150
+ } else finalAmount = (plan.amount ?? 0) * (quantity ?? 1);
2151
+ initBody.amount = Math.max(Math.round(finalAmount), 5e3);
2152
+ }
2153
+ } else {
1886
2154
  if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Amount is required for one-time payments" });
1887
2155
  initBody.amount = Math.round(amount);
1888
2156
  }
1889
- const sdkRes = unwrapSdkResult(await paystack?.transaction?.initialize({ body: initBody }));
1890
- url = sdkRes?.authorization_url;
1891
- reference = sdkRes?.reference;
1892
- accessCode = sdkRes?.access_code;
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
- }
2157
+ return { initBody };
2158
+ })().catch((error) => {
2159
+ if (options.subscription?.operationHooks === void 0) throw normalizeInitializationError(error);
2160
+ throw error;
1915
2161
  });
1916
- if (plan !== void 0) {
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",
1922
- where: [{
1923
- field: "id",
1924
- value: referenceId
1925
- }],
1926
- select: ["paystackCustomerCode"]
1927
- }))?.paystackCustomerCode ?? void 0;
1928
- if (customerCode) await store.saveCustomer(referenceId === user.id ? "user" : "organization", referenceId, customerCode);
1929
- } catch {}
1930
- const newSubscription = await ctx.context.adapter.create({
1931
- model: PAYSTACK_MODELS.subscription,
2162
+ if (prepared.earlyResult !== void 0) return ctx.json(prepared.earlyResult);
2163
+ const initBody = prepared.initBody;
2164
+ const operation = plan !== void 0 && options.subscription?.operationHooks !== void 0 ? {
2165
+ actor: { id: user.id },
2166
+ referenceId,
2167
+ kind: "initialize",
2168
+ subscription: subscriptionId !== void 0 ? await createBillingStore(ctx).findSubscriptionById(subscriptionId) : await createBillingStore(ctx).findCurrentSubscription(referenceId, groupId),
2169
+ intent: {
2170
+ plan: plan.name.toLowerCase(),
2171
+ amount: initBody.amount,
2172
+ currency: finalCurrency,
2173
+ interval: plan.interval,
2174
+ quantity: validatedQuantity,
2175
+ groupId,
2176
+ callbackURL,
2177
+ trialStart,
2178
+ trialEnd
2179
+ }
2180
+ } : void 0;
2181
+ const execute = async (providerReference, setPhase) => {
2182
+ if (providerReference !== void 0) initBody.reference = providerReference;
2183
+ try {
2184
+ const sdkRes = unwrapSdkResult(await paystack?.transaction?.initialize({ body: initBody }));
2185
+ if (providerReference !== void 0 && sdkRes?.reference !== providerReference) throw new APIError("BAD_REQUEST", { message: "Provider reference does not match reserved operation." });
2186
+ url = sdkRes?.authorization_url;
2187
+ reference = sdkRes?.reference;
2188
+ accessCode = sdkRes?.access_code;
2189
+ } catch (error) {
2190
+ throw normalizeInitializationError(error);
2191
+ }
2192
+ setPhase("persistence");
2193
+ await ctx.context.adapter.create({
2194
+ model: PAYSTACK_MODELS.transaction,
1932
2195
  data: {
1933
- plan: plan.name.toLowerCase(),
1934
- groupId,
2196
+ reference: reference ?? "",
1935
2197
  referenceId,
1936
2198
  userId: user.id,
1937
- customerCode,
1938
- subscriptionCode: void 0,
1939
- planCode: plan.planCode,
1940
- transactionReference: reference ?? "",
1941
- status: trialStart !== void 0 ? "trialing" : "incomplete",
1942
- billingInterval: plan.interval ?? null,
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,
2199
+ amount: amount ?? 0,
2200
+ currency: finalCurrency,
2201
+ status: "pending",
2202
+ plan: plan !== void 0 ? plan.name.toLowerCase() : void 0,
2203
+ product: product !== void 0 ? product.name.toLowerCase() : void 0,
2204
+ metadata: hasPaystackMetadata(extraMetadata) ? stringifyPaystackMetadata(extraMetadata) : void 0,
1949
2205
  createdAt: /* @__PURE__ */ new Date(),
1950
2206
  updatedAt: /* @__PURE__ */ new Date()
1951
2207
  }
1952
2208
  });
1953
- if (trialStart !== void 0 && newSubscription !== void 0 && newSubscription !== null && plan.freeTrial?.onTrialStart !== void 0) await plan.freeTrial.onTrialStart(newSubscription);
1954
- }
1955
- return ctx.json({
1956
- kind: "checkout",
1957
- url: url ?? "",
1958
- reference: reference ?? "",
1959
- accessCode: accessCode ?? "",
1960
- redirect: true
1961
- });
2209
+ if (plan !== void 0) {
2210
+ const store = createBillingStore(ctx);
2211
+ let customerCode = (await store.findCustomerByReference(referenceId === user.id ? "user" : "organization", referenceId))?.customerCode;
2212
+ if (customerCode === void 0) try {
2213
+ customerCode = (await ctx.context.adapter.findOne({
2214
+ model: referenceId === user.id ? "user" : "organization",
2215
+ where: [{
2216
+ field: "id",
2217
+ value: referenceId
2218
+ }],
2219
+ select: ["paystackCustomerCode"]
2220
+ }))?.paystackCustomerCode ?? void 0;
2221
+ if (customerCode !== void 0 && customerCode !== null && customerCode !== "") await store.saveCustomer(referenceId === user.id ? "user" : "organization", referenceId, customerCode);
2222
+ } catch {}
2223
+ const newSubscription = await ctx.context.adapter.create({
2224
+ model: PAYSTACK_MODELS.subscription,
2225
+ data: {
2226
+ plan: plan.name.toLowerCase(),
2227
+ groupId,
2228
+ referenceId,
2229
+ userId: user.id,
2230
+ customerCode,
2231
+ subscriptionCode: void 0,
2232
+ planCode: plan.planCode,
2233
+ transactionReference: reference ?? "",
2234
+ status: trialStart !== void 0 ? "trialing" : "incomplete",
2235
+ billingInterval: plan.interval ?? null,
2236
+ seats: quantity ?? 1,
2237
+ periodStart: /* @__PURE__ */ new Date(),
2238
+ periodEnd: new Date(Date.now() + 2592e6),
2239
+ cancelAtPeriodEnd: false,
2240
+ trialStart,
2241
+ trialEnd,
2242
+ createdAt: /* @__PURE__ */ new Date(),
2243
+ updatedAt: /* @__PURE__ */ new Date()
2244
+ }
2245
+ });
2246
+ if (trialStart !== void 0 && newSubscription !== void 0 && newSubscription !== null && plan.freeTrial?.onTrialStart !== void 0) await plan.freeTrial.onTrialStart(newSubscription);
2247
+ }
2248
+ return ctx.json({
2249
+ kind: "checkout",
2250
+ url: url ?? "",
2251
+ reference: reference ?? "",
2252
+ accessCode: accessCode ?? "",
2253
+ redirect: true
2254
+ });
2255
+ };
2256
+ return operation !== void 0 ? runSubscriptionOperation(ctx, options, operation, execute) : execute(void 0, () => void 0);
1962
2257
  });
1963
2258
  };
1964
2259
  const createSubscription = (options, path = "/create-subscription") => initializeTransaction(options, path);
@@ -1966,14 +2261,16 @@ const upgradeSubscription = (options, path = "/upgrade-subscription") => initial
1966
2261
  const cancelSubscription = (options, path = "/cancel-subscription") => disablePaystackSubscription(options, path);
1967
2262
  const restoreSubscription = (options, path = "/restore-subscription") => enablePaystackSubscription(options, path);
1968
2263
  const verifyTransaction = (options, path = "/verify-transaction") => {
2264
+ const verifyBodySchema = z.object({ reference: z.string() });
2265
+ const useMiddlewares = options.subscription?.enabled === true ? [
2266
+ sessionMiddleware,
2267
+ originCheck,
2268
+ referenceMiddleware(options, "verify-transaction")
2269
+ ] : [sessionMiddleware, originCheck];
1969
2270
  return createAuthEndpoint(path, {
1970
2271
  method: "POST",
1971
- body: z.object({ reference: z.string() }),
1972
- use: options.subscription?.enabled === true ? [
1973
- sessionMiddleware,
1974
- originCheck,
1975
- referenceMiddleware(options, "verify-transaction")
1976
- ] : [sessionMiddleware, originCheck]
2272
+ body: verifyBodySchema,
2273
+ use: useMiddlewares
1977
2274
  }, async (ctx) => {
1978
2275
  const session = await getSessionFromCtx(ctx);
1979
2276
  const result = await reconcilePaystackTransaction(ctx, options, {
@@ -2000,14 +2297,15 @@ const verifyTransaction = (options, path = "/verify-transaction") => {
2000
2297
  const listSubscriptions = (options, path = "/list-subscriptions") => {
2001
2298
  const listQuerySchema = z.object({ referenceId: z.string().optional() });
2002
2299
  const subscriptionOptions = options.subscription;
2300
+ const useMiddlewares = subscriptionOptions?.enabled === true ? [
2301
+ sessionMiddleware,
2302
+ originCheck,
2303
+ referenceMiddleware(options, "list-subscriptions")
2304
+ ] : [sessionMiddleware, originCheck];
2003
2305
  return createAuthEndpoint(path, {
2004
2306
  method: "GET",
2005
2307
  query: listQuerySchema,
2006
- use: subscriptionOptions?.enabled === true ? [
2007
- sessionMiddleware,
2008
- originCheck,
2009
- referenceMiddleware(options, "list-subscriptions")
2010
- ] : [sessionMiddleware, originCheck]
2308
+ use: useMiddlewares
2011
2309
  }, async (ctx) => {
2012
2310
  if (subscriptionOptions?.enabled !== true) throw new APIError("BAD_REQUEST", { message: "Subscriptions are not enabled in the Paystack options." });
2013
2311
  const session = await getSessionFromCtx(ctx);
@@ -2028,14 +2326,16 @@ const listSubscriptions = (options, path = "/list-subscriptions") => {
2028
2326
  });
2029
2327
  };
2030
2328
  const listTransactions = (options, path = "/list-transactions") => {
2329
+ const listQuerySchema = z.object({ referenceId: z.string().optional() });
2330
+ const useMiddlewares = options.subscription?.enabled === true ? [
2331
+ sessionMiddleware,
2332
+ originCheck,
2333
+ referenceMiddleware(options, "list-transactions")
2334
+ ] : [sessionMiddleware, originCheck];
2031
2335
  return createAuthEndpoint(path, {
2032
2336
  method: "GET",
2033
- query: z.object({ referenceId: z.string().optional() }),
2034
- use: options.subscription?.enabled === true ? [
2035
- sessionMiddleware,
2036
- originCheck,
2037
- referenceMiddleware(options, "list-transactions")
2038
- ] : [sessionMiddleware, originCheck]
2337
+ query: listQuerySchema,
2338
+ use: useMiddlewares
2039
2339
  }, async (ctx) => {
2040
2340
  const session = await getSessionFromCtx(ctx);
2041
2341
  if (session === void 0 || session === null) throw new APIError("UNAUTHORIZED");
@@ -2055,14 +2355,15 @@ const listTransactions = (options, path = "/list-transactions") => {
2055
2355
  });
2056
2356
  };
2057
2357
  const disablePaystackSubscription = (options, path = "/disable-subscription") => {
2358
+ const useMiddlewares = options.subscription?.enabled === true ? [
2359
+ sessionMiddleware,
2360
+ originCheck,
2361
+ referenceMiddleware(options, "disable-subscription")
2362
+ ] : [sessionMiddleware, originCheck];
2058
2363
  return createAuthEndpoint(path, {
2059
2364
  method: "POST",
2060
2365
  body: enableDisableBodySchema,
2061
- use: options.subscription?.enabled === true ? [
2062
- sessionMiddleware,
2063
- originCheck,
2064
- referenceMiddleware(options, "disable-subscription")
2065
- ] : [sessionMiddleware, originCheck]
2366
+ use: useMiddlewares
2066
2367
  }, async (ctx) => {
2067
2368
  const { subscriptionCode, atPeriodEnd } = ctx.body;
2068
2369
  const paystack = getPaystackOps(options.paystackClient);
@@ -2149,22 +2450,24 @@ const disablePaystackSubscription = (options, path = "/disable-subscription") =>
2149
2450
  return ctx.json({ status: "success" });
2150
2451
  } catch (error) {
2151
2452
  ctx.context.logger.error("Failed to disable subscription", error);
2453
+ const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION.message;
2152
2454
  throw new APIError("BAD_REQUEST", {
2153
2455
  code: "FAILED_TO_DISABLE_SUBSCRIPTION",
2154
- message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_DISABLE_SUBSCRIPTION.message
2456
+ message: errorMessage
2155
2457
  });
2156
2458
  }
2157
2459
  });
2158
2460
  };
2159
2461
  const enablePaystackSubscription = (options, path = "/enable-subscription") => {
2462
+ const useMiddlewares = options.subscription?.enabled === true ? [
2463
+ sessionMiddleware,
2464
+ originCheck,
2465
+ referenceMiddleware(options, "enable-subscription")
2466
+ ] : [sessionMiddleware, originCheck];
2160
2467
  return createAuthEndpoint(path, {
2161
2468
  method: "POST",
2162
2469
  body: enableDisableBodySchema,
2163
- use: options.subscription?.enabled === true ? [
2164
- sessionMiddleware,
2165
- originCheck,
2166
- referenceMiddleware(options, "enable-subscription")
2167
- ] : [sessionMiddleware, originCheck]
2470
+ use: useMiddlewares
2168
2471
  }, async (ctx) => {
2169
2472
  const { subscriptionCode } = ctx.body;
2170
2473
  const paystack = getPaystackOps(options.paystackClient);
@@ -2204,9 +2507,10 @@ const enablePaystackSubscription = (options, path = "/enable-subscription") => {
2204
2507
  return ctx.json({ status: "success" });
2205
2508
  } catch (error) {
2206
2509
  ctx.context.logger.error("Failed to enable subscription", error);
2510
+ const errorMessage = error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION.message;
2207
2511
  throw new APIError("BAD_REQUEST", {
2208
2512
  code: "FAILED_TO_ENABLE_SUBSCRIPTION",
2209
- message: error instanceof Error ? error.message : PAYSTACK_ERROR_CODES.FAILED_TO_ENABLE_SUBSCRIPTION.message
2513
+ message: errorMessage
2210
2514
  });
2211
2515
  }
2212
2516
  });
@@ -2230,7 +2534,8 @@ const getSubscriptionManageLink = (options, path = "/subscription-manage-link")
2230
2534
  return ctx.json({ link: res?.link || null });
2231
2535
  } catch (error) {
2232
2536
  ctx.context.logger.error("Failed to get subscription manage link", error);
2233
- throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to get subscription manage link" });
2537
+ const errorMessage = error instanceof Error ? error.message : "Failed to get subscription manage link";
2538
+ throw new APIError("BAD_REQUEST", { message: errorMessage });
2234
2539
  }
2235
2540
  };
2236
2541
  return createAuthEndpoint(path, {
@@ -2259,7 +2564,8 @@ const listPlans = (_options, path = "/list-plans") => {
2259
2564
  return ctx.json({ plans });
2260
2565
  } catch (error) {
2261
2566
  ctx.context.logger.error("Failed to list plans", error);
2262
- throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to list plans" });
2567
+ const errorMessage = error instanceof Error ? error.message : "Failed to list plans";
2568
+ throw new APIError("BAD_REQUEST", { message: errorMessage });
2263
2569
  }
2264
2570
  });
2265
2571
  };
@@ -2664,101 +2970,6 @@ const getSchema = (options) => {
2664
2970
  return mergeSchema(baseSchema, optionSchema);
2665
2971
  };
2666
2972
  //#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
2973
  //#region src/operations.ts
2763
2974
  async function syncPaystackProducts(ctx, options) {
2764
2975
  const paystack = createPaystackAdapter(options.paystackClient);
@@ -2794,7 +3005,8 @@ async function syncPaystackProducts(ctx, options) {
2794
3005
  };
2795
3006
  } catch (error) {
2796
3007
  ctx.context.logger.error("Failed to sync products", error);
2797
- throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to sync products" });
3008
+ const errorMessage = error instanceof Error ? error.message : "Failed to sync products";
3009
+ throw new APIError("BAD_REQUEST", { message: errorMessage });
2798
3010
  }
2799
3011
  }
2800
3012
  async function syncPaystackPlans(ctx, options) {
@@ -2830,19 +3042,20 @@ async function syncPaystackPlans(ctx, options) {
2830
3042
  };
2831
3043
  } catch (error) {
2832
3044
  ctx.context.logger.error("Failed to sync plans", error);
2833
- throw new APIError("BAD_REQUEST", { message: error instanceof Error ? error.message : "Failed to sync plans" });
3045
+ const errorMessage = error instanceof Error ? error.message : "Failed to sync plans";
3046
+ throw new APIError("BAD_REQUEST", { message: errorMessage });
2834
3047
  }
2835
3048
  }
2836
3049
  async function chargeSubscriptionRenewal(ctx, options, input) {
2837
- const { subscriptionId, amount: bodyAmount } = input;
3050
+ const { subscriptionId } = input;
2838
3051
  const store = createBillingStore(ctx);
2839
3052
  const subscription = await store.findSubscriptionById(subscriptionId);
2840
3053
  if (subscription === void 0 || subscription === null) throw new APIError("NOT_FOUND", { message: "Subscription not found" });
2841
3054
  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" });
3055
+ if (credentials?.authorizationCode === void 0 || credentials.authorizationCode === null || credentials.authorizationCode === "") throw new APIError("BAD_REQUEST", { message: "No authorization code found for this subscription" });
2843
3056
  const plan = (await getPlans(options.subscription)).find((candidate) => candidate.name.toLowerCase() === subscription.plan.toLowerCase());
2844
3057
  if (plan === void 0 || plan === null) throw new APIError("NOT_FOUND", { message: "Plan not found" });
2845
- const amount = bodyAmount ?? plan.amount;
3058
+ const amount = calculatePlanAmount(plan, subscription.seats ?? 1);
2846
3059
  if (amount === void 0 || amount === null) throw new APIError("BAD_REQUEST", { message: "Plan amount is not defined" });
2847
3060
  let email;
2848
3061
  let billingUserId = subscription.userId;
@@ -2868,10 +3081,11 @@ async function chargeSubscriptionRenewal(ctx, options, input) {
2868
3081
  status: 400
2869
3082
  });
2870
3083
  const paystack = createPaystackAdapter(options.paystackClient);
2871
- const serializedRenewalMetadata = stringifyPaystackMetadata(createRenewalMetadata({
3084
+ const renewalMetadata = createRenewalMetadata({
2872
3085
  subscriptionId,
2873
3086
  referenceId
2874
- }));
3087
+ });
3088
+ const serializedRenewalMetadata = stringifyPaystackMetadata(renewalMetadata);
2875
3089
  const typedChargeData = await paystack.chargeAuthorization({
2876
3090
  email,
2877
3091
  amount,
@@ -2947,8 +3161,9 @@ async function findManySafely(adapter, model) {
2947
3161
  function migrationData(legacy) {
2948
3162
  const now = /* @__PURE__ */ new Date();
2949
3163
  const referenceId = asIdentifier(legacy.referenceId) ?? asIdentifier(legacy.userId) ?? "";
3164
+ const id = asIdentifier(legacy.id);
2950
3165
  return {
2951
- ...asIdentifier(legacy.id) ? { id: asIdentifier(legacy.id) } : {},
3166
+ ...id !== void 0 ? { id } : {},
2952
3167
  plan: asString(legacy.plan) ?? "",
2953
3168
  referenceId,
2954
3169
  userId: asIdentifier(legacy.userId) ?? referenceId,
@@ -2976,7 +3191,7 @@ function migrationData(legacy) {
2976
3191
  async function migrateCustomer(adapter, referenceType, legacy, report) {
2977
3192
  const customerCode = asString(legacy.paystackCustomerCode) ?? asString(legacy.customerCode);
2978
3193
  const referenceId = asIdentifier(legacy.id);
2979
- if (!customerCode || !referenceId) return;
3194
+ if (customerCode === void 0 || referenceId === void 0) return;
2980
3195
  const referenceKey = `${referenceType}:${referenceId}`;
2981
3196
  try {
2982
3197
  if (await adapter.findOne({
@@ -3043,7 +3258,7 @@ async function migratePaystackSubscriptionSchema(ctx, options) {
3043
3258
  const legacySubscriptions = await findManySafely(adapter, LEGACY_PAYSTACK_MODELS.subscription);
3044
3259
  for (const legacy of legacySubscriptions) {
3045
3260
  const id = asIdentifier(legacy.id);
3046
- if (!id) continue;
3261
+ if (id === void 0) continue;
3047
3262
  try {
3048
3263
  if (await adapter.findOne({
3049
3264
  model: PAYSTACK_MODELS.subscription,
@@ -3072,7 +3287,7 @@ async function migratePaystackSubscriptionSchema(ctx, options) {
3072
3287
  }
3073
3288
  const authorizationCode = asString(legacy.authorizationCode) ?? asString(legacy.paystackAuthorizationCode);
3074
3289
  const emailToken = asString(legacy.emailToken) ?? asString(legacy.paystackEmailToken);
3075
- if (authorizationCode || emailToken) try {
3290
+ if (authorizationCode !== void 0 || emailToken !== void 0) try {
3076
3291
  if (await adapter.findOne({
3077
3292
  model: PAYSTACK_MODELS.paymentCredential,
3078
3293
  where: [{