better-auth-streampay 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -43,6 +43,8 @@ var $ERROR_CODES = defineErrorCodes({
43
43
  SUBSCRIPTION_EXPIRED: "The subscription has expired.",
44
44
  SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
45
45
  SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
46
+ SUBSCRIPTION_SEAT_COUNT_INVALID: "The requested seat count is invalid for this plan.",
47
+ SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED: "A different subscription change is already scheduled.",
46
48
  SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
47
49
  SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
48
50
  SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
@@ -670,7 +672,8 @@ function projectSubscriptionFields(sub) {
670
672
  }
671
673
  function parseDate(value) {
672
674
  if (!value) return null;
673
- const date = new Date(value);
675
+ const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
676
+ const date = new Date(normalized);
674
677
  return Number.isNaN(date.getTime()) ? null : date;
675
678
  }
676
679
  function minorUnitExponent(currency) {
@@ -709,13 +712,19 @@ function amountToSmallestUnit(value, currency) {
709
712
  }
710
713
  var SubscriptionItemSchema = z.object({
711
714
  product: z.object({ id: z.string() }).passthrough().optional(),
712
- product_id: z.string().optional()
715
+ product_id: z.string().optional(),
716
+ quantity: z.number().optional()
713
717
  }).passthrough();
714
718
  function subscriptionItemProductId(item) {
715
719
  const parsed = SubscriptionItemSchema.safeParse(item);
716
720
  if (!parsed.success) return null;
717
721
  return parsed.data.product?.id ?? parsed.data.product_id ?? null;
718
722
  }
723
+ function subscriptionItemQuantity(item) {
724
+ const parsed = SubscriptionItemSchema.safeParse(item);
725
+ if (!parsed.success || parsed.data.quantity === void 0) return null;
726
+ return Number.isSafeInteger(parsed.data.quantity) && parsed.data.quantity > 0 ? parsed.data.quantity : null;
727
+ }
719
728
  function inferPlanFromItems(sub, plans) {
720
729
  if (!Array.isArray(sub.items)) return null;
721
730
  return inferPlanFromItemList(sub.items, plans);
@@ -724,14 +733,32 @@ function inferPlanFromItemList(items, plans) {
724
733
  const productIds = new Set(
725
734
  items.map(subscriptionItemProductId).filter((id) => Boolean(id))
726
735
  );
727
- return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
736
+ const matches = plans.list.filter((plan) => productIds.has(plan.productId));
737
+ if (matches.length > 1) {
738
+ throw new APIError("INTERNAL_SERVER_ERROR", {
739
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
740
+ message: "StreamPay returned a subscription containing multiple configured plan products."
741
+ });
742
+ }
743
+ return matches[0]?.name ?? null;
728
744
  }
729
745
  function projectPlanFields(sub, plans) {
730
746
  const currentPlan = inferPlanFromItems(sub, plans);
731
- const currentProductId = subscriptionItemProductId(sub.items?.[0]);
732
- const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
733
- const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
734
747
  const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
748
+ const currentItem = configuredCurrent ? sub.items?.find((item) => subscriptionItemProductId(item) === configuredCurrent.productId) : sub.items?.[0];
749
+ const currentProductId = subscriptionItemProductId(currentItem);
750
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : null;
751
+ const inferredPendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
752
+ const configuredPending = inferredPendingPlan ? plans.byName.get(inferredPendingPlan) : void 0;
753
+ const pendingItem = configuredPending ? sub.pending_change?.target_items?.find(
754
+ (item) => subscriptionItemProductId(item) === configuredPending.productId
755
+ ) : currentProductId ? sub.pending_change?.target_items?.find(
756
+ (item) => subscriptionItemProductId(item) === currentProductId
757
+ ) : sub.pending_change?.target_items?.[0];
758
+ const pendingProductId = subscriptionItemProductId(pendingItem);
759
+ const pendingSeats = pendingItem ? subscriptionItemQuantity(pendingItem) ?? 1 : null;
760
+ const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
761
+ const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
735
762
  return {
736
763
  ...currentPlan ? {
737
764
  plan: currentPlan,
@@ -739,9 +766,12 @@ function projectPlanFields(sub, plans) {
739
766
  productId: currentProductId,
740
767
  group: configuredCurrent?.group ?? null
741
768
  } : currentProductId ? { productId: currentProductId } : {},
742
- pendingPlan,
743
- pendingProductId,
744
- pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
769
+ ...currentSeats === null ? {} : { seats: currentSeats },
770
+ pendingPlan: planChanges ? inferredPendingPlan : null,
771
+ pendingProductId: planChanges ? pendingProductId : null,
772
+ pendingPlanEffectiveAt: planChanges ? pendingEffectiveAt : null,
773
+ pendingSeats,
774
+ pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
745
775
  };
746
776
  }
747
777
  function subscriptionSlotKey(referenceType, referenceId, group) {
@@ -2942,9 +2972,10 @@ function checkoutInProgressError() {
2942
2972
  });
2943
2973
  }
2944
2974
  async function resumeOrReserveCheckoutSlot(args) {
2945
- const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2975
+ const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
2976
+ const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
2946
2977
  const reuseCandidate = candidates.find(
2947
- (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2978
+ (row2) => matchesCheckout(row2) && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2948
2979
  );
2949
2980
  if (reuseCandidate) {
2950
2981
  let recovery;
@@ -2983,21 +3014,23 @@ async function resumeOrReserveCheckoutSlot(args) {
2983
3014
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
2984
3015
  });
2985
3016
  if (reserved?.status !== "incomplete") throw err;
2986
- let recovery;
2987
- try {
2988
- recovery = await recoverCheckoutUrl(client, reserved);
2989
- } catch (recoveryError) {
2990
- toAPIError(
2991
- {
2992
- logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2993
- userMessage: "Unable to resume subscription checkout."
2994
- },
2995
- recoveryError,
2996
- log
2997
- );
2998
- }
2999
- if (recovery.kind === "recovered") {
3000
- return { kind: "recovered", row: reserved, url: recovery.url };
3017
+ if (matchesCheckout(reserved)) {
3018
+ let recovery;
3019
+ try {
3020
+ recovery = await recoverCheckoutUrl(client, reserved);
3021
+ } catch (recoveryError) {
3022
+ toAPIError(
3023
+ {
3024
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
3025
+ userMessage: "Unable to resume subscription checkout."
3026
+ },
3027
+ recoveryError,
3028
+ log
3029
+ );
3030
+ }
3031
+ if (recovery.kind === "recovered") {
3032
+ return { kind: "recovered", row: reserved, url: recovery.url };
3033
+ }
3001
3034
  }
3002
3035
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3003
3036
  if (!reservationIsStale) throw checkoutInProgressError();
@@ -3023,24 +3056,67 @@ async function resumeOrReserveCheckoutSlot(args) {
3023
3056
  }
3024
3057
  return { kind: "reserved", row, consumerId };
3025
3058
  }
3026
-
3027
- // src/plugins/subscriptions/lifecycle.ts
3028
3059
  function isAlreadyCanceledFreezeError(err) {
3029
3060
  const sdkError = readSdkErrorFields(err);
3030
3061
  const envelope = readEnvelope(sdkError.body);
3031
3062
  return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3032
3063
  }
3033
3064
  function subscriptionCouponIds(stream) {
3065
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3066
+ }
3067
+ function couponIdsFromMetadata(metadata) {
3034
3068
  const coupons = [];
3035
- for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
3069
+ for (const coupon of metadata?.coupons ?? []) {
3036
3070
  if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3037
3071
  }
3038
3072
  return coupons;
3039
3073
  }
3074
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3075
+ if (!stream.items?.length) {
3076
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
3077
+ }
3078
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3079
+ let matches = 0;
3080
+ const items = stream.items.map((item) => {
3081
+ const productId = subscriptionItemProductId(item);
3082
+ const quantity = item.quantity ?? 1;
3083
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3084
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3085
+ }
3086
+ const isPlanItem = productId === currentProductId;
3087
+ if (isPlanItem) matches += 1;
3088
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3089
+ (couponId) => !subscriptionCoupons.has(couponId)
3090
+ );
3091
+ return {
3092
+ product_id: isPlanItem ? targetProductId : productId,
3093
+ quantity: isPlanItem ? targetSeats : quantity,
3094
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3095
+ };
3096
+ });
3097
+ if (matches !== 1) {
3098
+ throw invalidProviderItems(
3099
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3100
+ );
3101
+ }
3102
+ return items;
3103
+ }
3104
+ function invalidProviderItems(message) {
3105
+ return new APIError("INTERNAL_SERVER_ERROR", {
3106
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3107
+ message
3108
+ });
3109
+ }
3040
3110
  function configuredPlanForSubscription(subscription, plans) {
3041
- return plans.list.find(
3111
+ const matches = plans.list.filter(
3042
3112
  (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3043
3113
  );
3114
+ if (matches.length > 1) {
3115
+ throw invalidProviderItems(
3116
+ "StreamPay returned a subscription containing multiple configured plan products."
3117
+ );
3118
+ }
3119
+ return matches[0];
3044
3120
  }
3045
3121
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3046
3122
  var PlanSchema = z.object({
@@ -3063,7 +3139,46 @@ var PlanSchema = z.object({
3063
3139
  message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
3064
3140
  }).optional(),
3065
3141
  group: z.string().min(1, "has an empty `group`.").optional(),
3142
+ seatBilling: z.object({
3143
+ default: z.number().safe().int().positive().optional(),
3144
+ minimum: z.number().safe().int().positive().optional(),
3145
+ maximum: z.number().safe().int().positive().optional(),
3146
+ customerEditable: z.boolean().optional()
3147
+ }).optional(),
3066
3148
  limits: z.record(z.string(), z.unknown()).optional()
3149
+ }).superRefine((plan, ctx) => {
3150
+ const seats = plan.seatBilling;
3151
+ if (!seats) return;
3152
+ const minimum = seats.minimum ?? 1;
3153
+ const defaultSeats = seats.default ?? minimum;
3154
+ if (seats.maximum !== void 0 && seats.maximum < minimum) {
3155
+ ctx.addIssue({
3156
+ code: "custom",
3157
+ path: ["seatBilling", "maximum"],
3158
+ message: "must be greater than or equal to `minimum`."
3159
+ });
3160
+ }
3161
+ if (defaultSeats < minimum || seats.maximum !== void 0 && defaultSeats > seats.maximum) {
3162
+ ctx.addIssue({
3163
+ code: "custom",
3164
+ path: ["seatBilling", "default"],
3165
+ message: "must be within the configured minimum and maximum."
3166
+ });
3167
+ }
3168
+ if (seats.customerEditable && (seats.minimum === void 0 || seats.maximum === void 0)) {
3169
+ ctx.addIssue({
3170
+ code: "custom",
3171
+ path: ["seatBilling", "customerEditable"],
3172
+ message: "requires explicit `minimum` and `maximum` bounds for hosted checkout editing."
3173
+ });
3174
+ }
3175
+ if (seats.maximum !== void 0 && !Number.isSafeInteger(plan.priceInSmallestUnit * seats.maximum)) {
3176
+ ctx.addIssue({
3177
+ code: "custom",
3178
+ path: ["seatBilling", "maximum"],
3179
+ message: "produces an unsafe total with `priceInSmallestUnit`."
3180
+ });
3181
+ }
3067
3182
  });
3068
3183
  var PlansSchema = z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
3069
3184
  const seenNames = /* @__PURE__ */ new Set();
@@ -3167,6 +3282,15 @@ var CheckLimitQuery = z.object({
3167
3282
  count: z.coerce.number().int().min(0),
3168
3283
  group: z.string().min(1).optional()
3169
3284
  });
3285
+ function presentSubscription(row, plans) {
3286
+ return {
3287
+ ...row,
3288
+ // The column is nullable during safe rolling migrations. Keep the public
3289
+ // contract stable while applications backfill legacy rows to one seat.
3290
+ seats: row.seats ?? 1,
3291
+ plan: plans.byName.get(row.plan) ?? null
3292
+ };
3293
+ }
3170
3294
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
3171
3295
  const user = requireUser(ctx);
3172
3296
  const reference = resolveReference(user, query);
@@ -3217,12 +3341,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3217
3341
  ]
3218
3342
  });
3219
3343
  const plans = await plansRef();
3220
- return ctx.json(
3221
- rows.map((row) => ({
3222
- ...row,
3223
- plan: plans.byName.get(row.plan) ?? null
3224
- }))
3225
- );
3344
+ return ctx.json(rows.map((row) => presentSubscription(row, plans)));
3226
3345
  }
3227
3346
  ),
3228
3347
  currentSubscription: createAuthEndpoint(
@@ -3241,7 +3360,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3241
3360
  );
3242
3361
  if (!live) return ctx.json(null);
3243
3362
  const plans = await plansRef();
3244
- return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3363
+ return ctx.json(presentSubscription(live, plans));
3245
3364
  }
3246
3365
  ),
3247
3366
  hasSubscriptionFeature: createAuthEndpoint(
@@ -3276,16 +3395,63 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3276
3395
  )
3277
3396
  };
3278
3397
  }
3398
+ function resolveSeatCount(plan, requested) {
3399
+ const seats = requested ?? plan.seatBilling?.default ?? plan.seatBilling?.minimum ?? 1;
3400
+ const minimum = plan.seatBilling?.minimum ?? 1;
3401
+ const maximum = plan.seatBilling?.maximum;
3402
+ if (!Number.isSafeInteger(seats) || seats < minimum || maximum !== void 0 && seats > maximum) {
3403
+ const range = maximum === void 0 ? `${minimum} or more` : `${minimum}\u2013${maximum}`;
3404
+ throw new APIError("BAD_REQUEST", {
3405
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3406
+ message: `Plan "${plan.name}" requires a safe-integer seat count in the range ${range}.`
3407
+ });
3408
+ }
3409
+ return seats;
3410
+ }
3411
+ function quotedSeatTotal(plan, seats) {
3412
+ const total = plan.priceInSmallestUnit * seats;
3413
+ if (!Number.isSafeInteger(total)) {
3414
+ throw new APIError("BAD_REQUEST", {
3415
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3416
+ message: `The quoted total for ${seats} seats exceeds JavaScript's safe-integer range.`
3417
+ });
3418
+ }
3419
+ return total;
3420
+ }
3421
+ function buildSeatCheckoutItem(plan, seats) {
3422
+ if (!plan.seatBilling?.customerEditable) {
3423
+ return {
3424
+ product_id: plan.productId,
3425
+ quantity: seats,
3426
+ allow_custom_quantity: false
3427
+ };
3428
+ }
3429
+ const minimum = plan.seatBilling.minimum;
3430
+ const maximum = plan.seatBilling.maximum;
3431
+ if (minimum === void 0 || maximum === void 0) {
3432
+ throw new TypeError(
3433
+ `Plan "${plan.name}" must configure seatBilling.minimum and seatBilling.maximum when customerEditable is true.`
3434
+ );
3435
+ }
3436
+ return {
3437
+ product_id: plan.productId,
3438
+ quantity: seats,
3439
+ allow_custom_quantity: true,
3440
+ min_quantity: minimum,
3441
+ max_quantity: maximum
3442
+ };
3443
+ }
3279
3444
 
3280
3445
  // src/plugins/subscriptions/endpoints.ts
3281
3446
  var SUBSCRIPTION_MODEL6 = "subscription";
3282
3447
  var UpgradeBody = z.object({
3283
3448
  plan: z.string().min(1),
3449
+ seats: z.number().int().positive().safe().optional(),
3284
3450
  referenceId: z.string().min(1).optional(),
3285
3451
  referenceType: z.enum(["user", "organization", "custom"]).optional(),
3286
3452
  successUrl: z.string().url().optional(),
3287
3453
  failureUrl: z.string().url().optional()
3288
- });
3454
+ }).strict();
3289
3455
  var SuccessQuery = z.object({
3290
3456
  subscriptionId: z.string().min(1)
3291
3457
  });
@@ -3296,7 +3462,12 @@ var CancelBody = z.object({
3296
3462
  });
3297
3463
  var ChangePlanBody = z.object({
3298
3464
  subscriptionId: z.string().min(1),
3299
- plan: z.string().min(1)
3465
+ plan: z.string().min(1),
3466
+ seats: z.number().int().positive().safe().optional()
3467
+ }).strict();
3468
+ var UpdateSeatsBody = z.object({
3469
+ subscriptionId: z.string().min(1),
3470
+ seats: z.number().int().positive().safe()
3300
3471
  }).strict();
3301
3472
  var FreezeBody = z.object({
3302
3473
  subscriptionId: z.string().min(1),
@@ -3326,11 +3497,72 @@ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3326
3497
  return true;
3327
3498
  }
3328
3499
  if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3329
- const createdAt = new Date(subscription.created_at).getTime();
3330
- return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3500
+ const createdAt = parseDate(subscription.created_at)?.getTime();
3501
+ return createdAt !== void 0 && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3331
3502
  }
3332
3503
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3333
3504
  const client = options.client;
3505
+ const cancelPendingChangeEndpoint = (path) => createAuthEndpoint(
3506
+ path,
3507
+ {
3508
+ method: "POST",
3509
+ body: UnfreezeBody,
3510
+ use: [sessionMiddleware]
3511
+ },
3512
+ async (ctx) => {
3513
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3514
+ ctx,
3515
+ ctx.body.subscriptionId,
3516
+ subsOptions,
3517
+ "cancel-plan-change"
3518
+ );
3519
+ try {
3520
+ const plans = await plansRef();
3521
+ const current = await client.getSubscription(row.streampaySubscriptionId);
3522
+ if (!current.pending_change) {
3523
+ await adapter.update({
3524
+ model: SUBSCRIPTION_MODEL6,
3525
+ update: {
3526
+ ...projectSubscriptionAgainstExisting(row, current),
3527
+ ...projectPlanFields(current, plans),
3528
+ pendingPlan: null,
3529
+ pendingProductId: null,
3530
+ pendingPlanEffectiveAt: null,
3531
+ pendingSeats: null,
3532
+ pendingSeatsEffectiveAt: null
3533
+ },
3534
+ where: [{ field: "id", value: row.id }]
3535
+ });
3536
+ return ctx.json({ canceled: true, reused: true, subscription: current });
3537
+ }
3538
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3539
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3540
+ await adapter.update({
3541
+ model: SUBSCRIPTION_MODEL6,
3542
+ update: {
3543
+ ...projectSubscriptionAgainstExisting(row, stream),
3544
+ ...projectPlanFields(stream, plans),
3545
+ pendingPlan: null,
3546
+ pendingProductId: null,
3547
+ pendingPlanEffectiveAt: null,
3548
+ pendingSeats: null,
3549
+ pendingSeatsEffectiveAt: null
3550
+ },
3551
+ where: [{ field: "id", value: row.id }]
3552
+ });
3553
+ return ctx.json({ canceled: true, reused: false, subscription: stream });
3554
+ } catch (err) {
3555
+ toAPIError(
3556
+ {
3557
+ logPrefix: `cancel pending subscription change failed for row=${row.id}:`,
3558
+ userMessage: "Canceling the pending subscription change failed."
3559
+ },
3560
+ err,
3561
+ getLogger(ctx)
3562
+ );
3563
+ }
3564
+ }
3565
+ );
3334
3566
  return {
3335
3567
  ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
3336
3568
  upgradeSubscription: createAuthEndpoint(
@@ -3353,6 +3585,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3353
3585
  message: `Plan "${ctx.body.plan}" is not configured.`
3354
3586
  });
3355
3587
  }
3588
+ const seats = resolveSeatCount(plan, ctx.body.seats);
3589
+ const quotedTotal = quotedSeatTotal(plan, seats);
3356
3590
  const adapter = getAdapter2(ctx);
3357
3591
  const existingActive = await adapter.findMany({
3358
3592
  model: SUBSCRIPTION_MODEL6,
@@ -3390,6 +3624,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3390
3624
  candidates: existingActive,
3391
3625
  activeSlotKey,
3392
3626
  planName: plan.name,
3627
+ seats,
3393
3628
  now: Date.now(),
3394
3629
  log: getLogger(ctx),
3395
3630
  createReservation: async () => {
@@ -3409,13 +3644,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3409
3644
  planVersion: plan.version ?? null,
3410
3645
  productId: plan.productId,
3411
3646
  group: plan.group ?? null,
3647
+ seats,
3412
3648
  streampayConsumerId: consumerId2,
3413
3649
  streampayPaymentLinkId: null,
3414
3650
  status: "incomplete",
3415
3651
  providerStatus: null,
3416
3652
  billingStatus: "current",
3417
- amountInSmallestUnit: plan.priceInSmallestUnit,
3418
- originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3653
+ amountInSmallestUnit: quotedTotal,
3654
+ originalAmountInSmallestUnit: quotedTotal,
3419
3655
  currency: plan.currency ?? "SAR",
3420
3656
  billingInterval: plan.billingInterval,
3421
3657
  billingIntervalCount: plan.billingIntervalCount ?? 1,
@@ -3431,6 +3667,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3431
3667
  pendingPlan: null,
3432
3668
  pendingProductId: null,
3433
3669
  pendingPlanEffectiveAt: null,
3670
+ pendingSeats: null,
3671
+ pendingSeatsEffectiveAt: null,
3434
3672
  endedAt: null,
3435
3673
  frozenAt: null,
3436
3674
  freezeEndAt: null,
@@ -3449,14 +3687,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3449
3687
  redirect: true,
3450
3688
  reused: true,
3451
3689
  status: reservation.row.status,
3452
- plan: reservation.row.plan
3690
+ plan: reservation.row.plan,
3691
+ seats: reservation.row.seats ?? 1
3453
3692
  });
3454
3693
  }
3455
3694
  const { row, consumerId } = reservation;
3456
3695
  const linkInput = {
3457
3696
  name: `Subscription \u2014 ${plan.name}`,
3458
3697
  currency: plan.currency ?? "SAR",
3459
- items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
3698
+ items: [buildSeatCheckoutItem(plan, seats)],
3460
3699
  max_number_of_payments: 1,
3461
3700
  organization_consumer_id: consumerId,
3462
3701
  custom_metadata: {
@@ -3549,7 +3788,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3549
3788
  redirect: true,
3550
3789
  reused: false,
3551
3790
  status: "incomplete",
3552
- plan: plan.name
3791
+ plan: plan.name,
3792
+ seats
3553
3793
  });
3554
3794
  }
3555
3795
  ),
@@ -3620,6 +3860,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3620
3860
  model: SUBSCRIPTION_MODEL6,
3621
3861
  update: {
3622
3862
  ...projectSubscriptionFields(match),
3863
+ ...projectPlanFields(match, plans),
3623
3864
  planVersion: plan.version ?? null,
3624
3865
  productId: plan.productId,
3625
3866
  billingStatus: "current",
@@ -3731,8 +3972,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3731
3972
  }
3732
3973
  try {
3733
3974
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3734
- const currentPlan = configuredPlanForSubscription(stream, plans);
3735
- const currentGroup = currentPlan?.group ?? row.group;
3975
+ const currentPlan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
3976
+ if (!currentPlan) {
3977
+ throw new APIError("BAD_REQUEST", {
3978
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3979
+ message: "The current StreamPay product is not a configured subscription plan."
3980
+ });
3981
+ }
3982
+ const currentGroup = currentPlan.group ?? row.group;
3736
3983
  if (currentGroup !== (nextPlan.group ?? null)) {
3737
3984
  throw new APIError("BAD_REQUEST", {
3738
3985
  code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
@@ -3745,27 +3992,35 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3745
3992
  message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3746
3993
  });
3747
3994
  }
3748
- const currentProductIsRequestedPlan = stream.items?.some(
3749
- (item) => subscriptionItemProductId(item) === nextPlan.productId
3995
+ const currentItem = stream.items?.find(
3996
+ (item) => subscriptionItemProductId(item) === currentPlan.productId
3750
3997
  );
3751
- if (currentProductIsRequestedPlan && !stream.pending_change) {
3998
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
3999
+ const nextSeats = resolveSeatCount(nextPlan, ctx.body.seats ?? currentSeats ?? 1);
4000
+ const currentProductIsRequestedPlan = currentPlan.productId === nextPlan.productId;
4001
+ if (currentProductIsRequestedPlan && currentSeats === nextSeats && !stream.pending_change) {
3752
4002
  throw new APIError("BAD_REQUEST", {
3753
4003
  code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3754
- message: `Already on plan "${nextPlan.name}".`
4004
+ message: `Already on plan "${nextPlan.name}" with ${nextSeats} seats.`
3755
4005
  });
3756
4006
  }
3757
4007
  const pendingTargets = stream.pending_change?.target_items ?? [];
3758
- const pendingTargetIsRequestedPlan = pendingTargets.some(
4008
+ const pendingTarget = pendingTargets.find(
3759
4009
  (item) => subscriptionItemProductId(item) === nextPlan.productId
3760
4010
  );
3761
- if (pendingTargetIsRequestedPlan) {
4011
+ const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
4012
+ if (pendingTargetMatches) {
4013
+ const effectiveAt2 = stream.pending_change?.effective_at ?? null;
3762
4014
  await adapter.update({
3763
4015
  model: SUBSCRIPTION_MODEL6,
3764
4016
  update: {
3765
4017
  ...projectSubscriptionAgainstExisting(row, stream),
3766
- pendingPlan: nextPlan.name,
3767
- pendingProductId: nextPlan.productId,
3768
- pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
4018
+ ...projectPlanFields(stream, plans),
4019
+ pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
4020
+ pendingProductId: currentPlan.productId === nextPlan.productId ? null : nextPlan.productId,
4021
+ pendingPlanEffectiveAt: currentPlan.productId !== nextPlan.productId && effectiveAt2 ? parseDate(effectiveAt2) : null,
4022
+ pendingSeats: nextSeats,
4023
+ pendingSeatsEffectiveAt: parseDate(effectiveAt2)
3769
4024
  },
3770
4025
  where: [{ field: "id", value: row.id }]
3771
4026
  });
@@ -3773,7 +4028,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3773
4028
  mode: "at_period_end",
3774
4029
  subscriptionId: row.id,
3775
4030
  plan: nextPlan.name,
3776
- effectiveAt: stream.pending_change?.effective_at ?? null,
4031
+ seats: nextSeats,
4032
+ effectiveAt: effectiveAt2,
3777
4033
  pendingChange: stream.pending_change,
3778
4034
  reused: true
3779
4035
  });
@@ -3785,28 +4041,36 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3785
4041
  });
3786
4042
  }
3787
4043
  const patch = {
3788
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
4044
+ items: subscriptionItemsForUpdate(
4045
+ stream,
4046
+ currentPlan.productId,
4047
+ nextPlan.productId,
4048
+ nextSeats
4049
+ ),
3789
4050
  coupons: subscriptionCouponIds(stream),
3790
4051
  recurring_interval: nextPlan.billingInterval,
3791
4052
  recurring_interval_count: nextPlan.billingIntervalCount ?? 1
3792
4053
  };
3793
4054
  const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3794
- const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
4055
+ const pending = Boolean(result.pending_change);
4056
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4057
+ const planProjection = projectPlanFields(result, plans);
3795
4058
  await adapter.update({
3796
4059
  model: SUBSCRIPTION_MODEL6,
3797
4060
  update: {
3798
4061
  ...projectSubscriptionAgainstExisting(row, result),
3799
- pendingPlan: nextPlan.name,
3800
- pendingProductId: nextPlan.productId,
3801
- pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
4062
+ ...planProjection,
3802
4063
  updatedAt: /* @__PURE__ */ new Date()
3803
4064
  },
3804
4065
  where: [{ field: "id", value: row.id }]
3805
4066
  });
4067
+ const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4068
+ const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
3806
4069
  return ctx.json({
3807
- mode: "at_period_end",
4070
+ mode: pending ? "at_period_end" : "immediate",
3808
4071
  subscriptionId: row.id,
3809
- plan: nextPlan.name,
4072
+ plan: providerPlan,
4073
+ seats: providerSeats,
3810
4074
  effectiveAt,
3811
4075
  pendingChange: result.pending_change ?? null,
3812
4076
  subscription: result,
@@ -3824,11 +4088,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3824
4088
  }
3825
4089
  }
3826
4090
  ),
3827
- cancelSubscriptionPlanChange: createAuthEndpoint(
3828
- "/subscription/change-plan/cancel",
4091
+ updateSubscriptionSeats: createAuthEndpoint(
4092
+ "/subscription/update-seats",
3829
4093
  {
3830
4094
  method: "POST",
3831
- body: UnfreezeBody,
4095
+ body: UpdateSeatsBody,
3832
4096
  use: [sessionMiddleware]
3833
4097
  },
3834
4098
  async (ctx) => {
@@ -3836,27 +4100,107 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3836
4100
  ctx,
3837
4101
  ctx.body.subscriptionId,
3838
4102
  subsOptions,
3839
- "cancel-plan-change"
4103
+ "update-seats"
3840
4104
  );
4105
+ const plans = await plansRef();
3841
4106
  try {
3842
- await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3843
4107
  const stream = await client.getSubscription(row.streampaySubscriptionId);
4108
+ const plan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
4109
+ if (!plan) {
4110
+ throw new APIError("BAD_REQUEST", {
4111
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4112
+ message: "The current StreamPay product is not a configured subscription plan."
4113
+ });
4114
+ }
4115
+ if (stream.cancel_at_period_end) {
4116
+ throw new APIError("CONFLICT", {
4117
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
4118
+ message: "Uncancel the subscription before scheduling a seat change."
4119
+ });
4120
+ }
4121
+ const seats = resolveSeatCount(plan, ctx.body.seats);
4122
+ const currentItem = stream.items?.find(
4123
+ (item) => subscriptionItemProductId(item) === plan.productId
4124
+ );
4125
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
4126
+ const pendingTarget = stream.pending_change?.target_items?.find(
4127
+ (item) => subscriptionItemProductId(item) === plan.productId
4128
+ );
4129
+ if (stream.pending_change) {
4130
+ if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4131
+ const effectiveAt2 = stream.pending_change.effective_at ?? null;
4132
+ await adapter.update({
4133
+ model: SUBSCRIPTION_MODEL6,
4134
+ update: {
4135
+ ...projectSubscriptionAgainstExisting(row, stream),
4136
+ ...projectPlanFields(stream, plans)
4137
+ },
4138
+ where: [{ field: "id", value: row.id }]
4139
+ });
4140
+ return ctx.json({
4141
+ mode: "at_period_end",
4142
+ subscriptionId: row.id,
4143
+ seats,
4144
+ effectiveAt: effectiveAt2,
4145
+ pendingChange: stream.pending_change,
4146
+ reused: true
4147
+ });
4148
+ }
4149
+ throw new APIError("CONFLICT", {
4150
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED.code,
4151
+ message: "A different subscription change is pending. Cancel it before scheduling this seat count."
4152
+ });
4153
+ }
4154
+ if (currentSeats === seats) {
4155
+ await adapter.update({
4156
+ model: SUBSCRIPTION_MODEL6,
4157
+ update: {
4158
+ ...projectSubscriptionAgainstExisting(row, stream),
4159
+ ...projectPlanFields(stream, plans)
4160
+ },
4161
+ where: [{ field: "id", value: row.id }]
4162
+ });
4163
+ return ctx.json({
4164
+ mode: "current",
4165
+ subscriptionId: row.id,
4166
+ seats,
4167
+ effectiveAt: null,
4168
+ pendingChange: null,
4169
+ reused: true
4170
+ });
4171
+ }
4172
+ const patch = {
4173
+ items: subscriptionItemsForUpdate(stream, plan.productId, plan.productId, seats),
4174
+ coupons: subscriptionCouponIds(stream)
4175
+ };
4176
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
4177
+ const pending = Boolean(result.pending_change);
4178
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4179
+ const planProjection = projectPlanFields(result, plans);
3844
4180
  await adapter.update({
3845
4181
  model: SUBSCRIPTION_MODEL6,
3846
4182
  update: {
3847
- ...projectSubscriptionAgainstExisting(row, stream),
3848
- pendingPlan: null,
3849
- pendingProductId: null,
3850
- pendingPlanEffectiveAt: null
4183
+ ...projectSubscriptionAgainstExisting(row, result),
4184
+ ...planProjection,
4185
+ updatedAt: /* @__PURE__ */ new Date()
3851
4186
  },
3852
4187
  where: [{ field: "id", value: row.id }]
3853
4188
  });
3854
- return ctx.json({ canceled: true, subscription: stream });
4189
+ const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4190
+ return ctx.json({
4191
+ mode: pending ? "at_period_end" : "immediate",
4192
+ subscriptionId: row.id,
4193
+ seats: providerSeats,
4194
+ effectiveAt,
4195
+ pendingChange: result.pending_change ?? null,
4196
+ subscription: result,
4197
+ reused: false
4198
+ });
3855
4199
  } catch (err) {
3856
4200
  toAPIError(
3857
4201
  {
3858
- logPrefix: `cancel plan change failed for row=${row.id}:`,
3859
- userMessage: "Canceling the scheduled plan change failed."
4202
+ logPrefix: `update-seats failed for row=${row.id}:`,
4203
+ userMessage: "Seat change scheduling failed."
3860
4204
  },
3861
4205
  err,
3862
4206
  getLogger(ctx)
@@ -3864,6 +4208,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3864
4208
  }
3865
4209
  }
3866
4210
  ),
4211
+ cancelSubscriptionPlanChange: cancelPendingChangeEndpoint("/subscription/change-plan/cancel"),
4212
+ cancelSubscriptionPendingChange: cancelPendingChangeEndpoint(
4213
+ "/subscription/pending-change/cancel"
4214
+ ),
3867
4215
  uncancelSubscription: createAuthEndpoint(
3868
4216
  "/subscription/uncancel",
3869
4217
  {
@@ -3963,9 +4311,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3963
4311
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3964
4312
  const active = freezes.data?.find((freeze) => {
3965
4313
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
3966
- const start = new Date(freeze.freeze_start_datetime).getTime();
3967
- const end = freeze.freeze_end_datetime ? new Date(freeze.freeze_end_datetime).getTime() : Number.POSITIVE_INFINITY;
3968
- return start <= nowMs && nowMs <= end;
4314
+ const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4315
+ const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
4316
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
3969
4317
  });
3970
4318
  if (!active?.id || !active.freeze_start_datetime) {
3971
4319
  throw new APIError("BAD_REQUEST", {
@@ -4105,6 +4453,11 @@ var subscriptionTable = {
4105
4453
  required: false,
4106
4454
  index: true
4107
4455
  },
4456
+ seats: {
4457
+ type: "number",
4458
+ required: false,
4459
+ defaultValue: 1
4460
+ },
4108
4461
  amountInSmallestUnit: {
4109
4462
  type: "number",
4110
4463
  required: false
@@ -4193,6 +4546,14 @@ var subscriptionTable = {
4193
4546
  type: "date",
4194
4547
  required: false
4195
4548
  },
4549
+ pendingSeats: {
4550
+ type: "number",
4551
+ required: false
4552
+ },
4553
+ pendingSeatsEffectiveAt: {
4554
+ type: "date",
4555
+ required: false
4556
+ },
4196
4557
  endedAt: {
4197
4558
  type: "date",
4198
4559
  required: false
@@ -4791,7 +5152,7 @@ var onUserDelete = (options) => async (user, context) => {
4791
5152
 
4792
5153
  // package.json
4793
5154
  var package_default = {
4794
- version: "2.1.0"};
5155
+ version: "2.2.0"};
4795
5156
 
4796
5157
  // src/version.ts
4797
5158
  var version = package_default.version;