better-auth-streampay 2.0.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/README.md +92 -8
- package/dist/client.cjs +5 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +7 -2
- package/dist/client.d.ts +7 -2
- package/dist/client.js +5 -0
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +718 -176
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +15 -2
- package/dist/index.d.ts +15 -2
- package/dist/index.js +718 -176
- package/dist/index.js.map +1 -1
- package/dist/{streampay-CYAHE6Qj.d.cts → streampay-B3vf7Hvq.d.cts} +1435 -154
- package/dist/{streampay-CYAHE6Qj.d.ts → streampay-B3vf7Hvq.d.ts} +1435 -154
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -22,6 +22,8 @@ var $ERROR_CODES = defineErrorCodes({
|
|
|
22
22
|
FORBIDDEN: "You do not have permission to perform this action.",
|
|
23
23
|
NOT_FOUND: "The requested resource was not found.",
|
|
24
24
|
CONSUMER_DUPLICATE: "A consumer with one of the provided identifiers already exists.",
|
|
25
|
+
STREAMPAY_CONSUMER_LINK_CONFLICT: "This StreamPay consumer is already linked to another account.",
|
|
26
|
+
STREAMPAY_CONSUMER_LINK_WRITE_FAILED: "The StreamPay consumer link could not be saved.",
|
|
25
27
|
CONSUMER_HAS_ONGOING_ACTIVITY: "The consumer has ongoing invoices or active subscriptions and cannot be modified.",
|
|
26
28
|
INVOICE_INVALID_STATE: "The invoice is in a state that forbids this action.",
|
|
27
29
|
PAYMENT_DUPLICATE: "A payment with the same information already exists.",
|
|
@@ -33,6 +35,7 @@ var $ERROR_CODES = defineErrorCodes({
|
|
|
33
35
|
PAYMENT_METHOD_INVALID: "The supplied payment method is invalid for this flow.",
|
|
34
36
|
PRODUCT_LOCKED: "The product is referenced by a finalized invoice and cannot be modified.",
|
|
35
37
|
COUPON_LOCKED: "The coupon is referenced by a finalized invoice and cannot be modified.",
|
|
38
|
+
CHECKOUT_CLIENT_FIELDS_FORBIDDEN: "Checkout fields must be resolved by the server.",
|
|
36
39
|
SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
|
|
37
40
|
SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
|
|
38
41
|
SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
|
|
@@ -42,6 +45,8 @@ var $ERROR_CODES = defineErrorCodes({
|
|
|
42
45
|
SUBSCRIPTION_EXPIRED: "The subscription has expired.",
|
|
43
46
|
SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
|
|
44
47
|
SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
|
|
48
|
+
SUBSCRIPTION_SEAT_COUNT_INVALID: "The requested seat count is invalid for this plan.",
|
|
49
|
+
SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED: "A different subscription change is already scheduled.",
|
|
45
50
|
SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
|
|
46
51
|
SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
|
|
47
52
|
SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
|
|
@@ -344,12 +349,17 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
344
349
|
if (isDuplicateConsumerError(err)) {
|
|
345
350
|
const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
|
|
346
351
|
if (reusedId) {
|
|
352
|
+
await assertConsumerUnclaimed(ctx, reusedId, user.id);
|
|
347
353
|
try {
|
|
348
354
|
await options.client.updateConsumer(reusedId, { external_id: user.id });
|
|
349
355
|
} catch (backfillErr) {
|
|
350
356
|
getLogger(ctx).error(
|
|
351
357
|
`consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
|
|
352
358
|
);
|
|
359
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
360
|
+
code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
|
|
361
|
+
message: "StreamPay consumer linking failed. Please try again."
|
|
362
|
+
});
|
|
353
363
|
}
|
|
354
364
|
await persistConsumerId(ctx, user.id, reusedId);
|
|
355
365
|
return { consumerId: reusedId, created: false };
|
|
@@ -363,7 +373,40 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
363
373
|
});
|
|
364
374
|
}
|
|
365
375
|
}
|
|
376
|
+
function consumerLinkUnavailable() {
|
|
377
|
+
return new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
378
|
+
code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
|
|
379
|
+
message: "StreamPay consumer linking failed. Please try again."
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async function findConsumerOwner(ctx, consumerId) {
|
|
383
|
+
try {
|
|
384
|
+
return await ctx.context.adapter.findOne({
|
|
385
|
+
model: "user",
|
|
386
|
+
where: [{ field: "streampayConsumerId", value: consumerId }]
|
|
387
|
+
});
|
|
388
|
+
} catch (err) {
|
|
389
|
+
getLogger(ctx).error(
|
|
390
|
+
`consumer ownership check failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
|
|
391
|
+
);
|
|
392
|
+
throw consumerLinkUnavailable();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async function assertConsumerUnclaimed(ctx, consumerId, userId) {
|
|
396
|
+
const owner = await findConsumerOwner(ctx, consumerId);
|
|
397
|
+
if (!owner) return;
|
|
398
|
+
if (typeof owner.id !== "string") {
|
|
399
|
+
getLogger(ctx).error(`consumer ownership check returned a user without an id: ${consumerId}`);
|
|
400
|
+
throw consumerLinkUnavailable();
|
|
401
|
+
}
|
|
402
|
+
if (owner.id === userId) return;
|
|
403
|
+
throw new api.APIError("CONFLICT", {
|
|
404
|
+
code: "STREAMPAY_CONSUMER_LINK_CONFLICT",
|
|
405
|
+
message: "This StreamPay consumer is already linked to another account."
|
|
406
|
+
});
|
|
407
|
+
}
|
|
366
408
|
async function persistConsumerId(ctx, userId, consumerId) {
|
|
409
|
+
await assertConsumerUnclaimed(ctx, consumerId, userId);
|
|
367
410
|
try {
|
|
368
411
|
await ctx.context.internalAdapter.updateUser(userId, {
|
|
369
412
|
streampayConsumerId: consumerId
|
|
@@ -372,6 +415,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
|
|
|
372
415
|
getLogger(ctx).error(
|
|
373
416
|
`consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
|
|
374
417
|
);
|
|
418
|
+
await assertConsumerUnclaimed(ctx, consumerId, userId);
|
|
419
|
+
throw consumerLinkUnavailable();
|
|
375
420
|
}
|
|
376
421
|
}
|
|
377
422
|
|
|
@@ -629,7 +674,8 @@ function projectSubscriptionFields(sub) {
|
|
|
629
674
|
}
|
|
630
675
|
function parseDate(value) {
|
|
631
676
|
if (!value) return null;
|
|
632
|
-
const
|
|
677
|
+
const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
|
|
678
|
+
const date = new Date(normalized);
|
|
633
679
|
return Number.isNaN(date.getTime()) ? null : date;
|
|
634
680
|
}
|
|
635
681
|
function minorUnitExponent(currency) {
|
|
@@ -668,13 +714,19 @@ function amountToSmallestUnit(value, currency) {
|
|
|
668
714
|
}
|
|
669
715
|
var SubscriptionItemSchema = zod.z.object({
|
|
670
716
|
product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
|
|
671
|
-
product_id: zod.z.string().optional()
|
|
717
|
+
product_id: zod.z.string().optional(),
|
|
718
|
+
quantity: zod.z.number().optional()
|
|
672
719
|
}).passthrough();
|
|
673
720
|
function subscriptionItemProductId(item) {
|
|
674
721
|
const parsed = SubscriptionItemSchema.safeParse(item);
|
|
675
722
|
if (!parsed.success) return null;
|
|
676
723
|
return parsed.data.product?.id ?? parsed.data.product_id ?? null;
|
|
677
724
|
}
|
|
725
|
+
function subscriptionItemQuantity(item) {
|
|
726
|
+
const parsed = SubscriptionItemSchema.safeParse(item);
|
|
727
|
+
if (!parsed.success || parsed.data.quantity === void 0) return null;
|
|
728
|
+
return Number.isSafeInteger(parsed.data.quantity) && parsed.data.quantity > 0 ? parsed.data.quantity : null;
|
|
729
|
+
}
|
|
678
730
|
function inferPlanFromItems(sub, plans) {
|
|
679
731
|
if (!Array.isArray(sub.items)) return null;
|
|
680
732
|
return inferPlanFromItemList(sub.items, plans);
|
|
@@ -683,14 +735,32 @@ function inferPlanFromItemList(items, plans) {
|
|
|
683
735
|
const productIds = new Set(
|
|
684
736
|
items.map(subscriptionItemProductId).filter((id) => Boolean(id))
|
|
685
737
|
);
|
|
686
|
-
|
|
738
|
+
const matches = plans.list.filter((plan) => productIds.has(plan.productId));
|
|
739
|
+
if (matches.length > 1) {
|
|
740
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
741
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
742
|
+
message: "StreamPay returned a subscription containing multiple configured plan products."
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
return matches[0]?.name ?? null;
|
|
687
746
|
}
|
|
688
747
|
function projectPlanFields(sub, plans) {
|
|
689
748
|
const currentPlan = inferPlanFromItems(sub, plans);
|
|
690
|
-
const currentProductId = subscriptionItemProductId(sub.items?.[0]);
|
|
691
|
-
const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
|
|
692
|
-
const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
|
|
693
749
|
const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
|
|
750
|
+
const currentItem = configuredCurrent ? sub.items?.find((item) => subscriptionItemProductId(item) === configuredCurrent.productId) : sub.items?.[0];
|
|
751
|
+
const currentProductId = subscriptionItemProductId(currentItem);
|
|
752
|
+
const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : null;
|
|
753
|
+
const inferredPendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
|
|
754
|
+
const configuredPending = inferredPendingPlan ? plans.byName.get(inferredPendingPlan) : void 0;
|
|
755
|
+
const pendingItem = configuredPending ? sub.pending_change?.target_items?.find(
|
|
756
|
+
(item) => subscriptionItemProductId(item) === configuredPending.productId
|
|
757
|
+
) : currentProductId ? sub.pending_change?.target_items?.find(
|
|
758
|
+
(item) => subscriptionItemProductId(item) === currentProductId
|
|
759
|
+
) : sub.pending_change?.target_items?.[0];
|
|
760
|
+
const pendingProductId = subscriptionItemProductId(pendingItem);
|
|
761
|
+
const pendingSeats = pendingItem ? subscriptionItemQuantity(pendingItem) ?? 1 : null;
|
|
762
|
+
const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
|
|
763
|
+
const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
|
|
694
764
|
return {
|
|
695
765
|
...currentPlan ? {
|
|
696
766
|
plan: currentPlan,
|
|
@@ -698,9 +768,12 @@ function projectPlanFields(sub, plans) {
|
|
|
698
768
|
productId: currentProductId,
|
|
699
769
|
group: configuredCurrent?.group ?? null
|
|
700
770
|
} : currentProductId ? { productId: currentProductId } : {},
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
771
|
+
...currentSeats === null ? {} : { seats: currentSeats },
|
|
772
|
+
pendingPlan: planChanges ? inferredPendingPlan : null,
|
|
773
|
+
pendingProductId: planChanges ? pendingProductId : null,
|
|
774
|
+
pendingPlanEffectiveAt: planChanges ? pendingEffectiveAt : null,
|
|
775
|
+
pendingSeats,
|
|
776
|
+
pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
|
|
704
777
|
};
|
|
705
778
|
}
|
|
706
779
|
function subscriptionSlotKey(referenceType, referenceId, group) {
|
|
@@ -2359,15 +2432,15 @@ var admin = (adminOptions = {}) => (options, registry) => {
|
|
|
2359
2432
|
var RelativeOrAbsoluteUrl = zod.z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
|
|
2360
2433
|
message: "Must be a valid URL or a relative path starting with /"
|
|
2361
2434
|
});
|
|
2362
|
-
var
|
|
2435
|
+
var CheckoutRequestBody = zod.z.object({
|
|
2363
2436
|
products: zod.z.union([
|
|
2364
2437
|
zod.z.array(
|
|
2365
2438
|
zod.z.object({
|
|
2366
2439
|
productId: zod.z.string().uuid(),
|
|
2367
2440
|
quantity: zod.z.number().int().positive().optional()
|
|
2368
2441
|
})
|
|
2369
|
-
).
|
|
2370
|
-
zod.z.array(zod.z.string().uuid()).
|
|
2442
|
+
).min(1, "`products` must contain at least one item."),
|
|
2443
|
+
zod.z.array(zod.z.string().uuid()).min(1, "`products` must contain at least one item."),
|
|
2371
2444
|
zod.z.string().uuid()
|
|
2372
2445
|
]).optional(),
|
|
2373
2446
|
slug: zod.z.string().optional(),
|
|
@@ -2381,10 +2454,26 @@ var CheckoutBody = zod.z.object({
|
|
|
2381
2454
|
validUntil: zod.z.string().datetime().optional(),
|
|
2382
2455
|
couponIds: zod.z.array(zod.z.string().uuid()).optional(),
|
|
2383
2456
|
redirect: zod.z.coerce.boolean().optional()
|
|
2384
|
-
}).refine((data) => data.slug !== void 0 || data.products !== void 0, {
|
|
2385
|
-
message: "Either `slug` or `products` is required.",
|
|
2386
|
-
path: ["products"]
|
|
2387
2457
|
});
|
|
2458
|
+
var CheckoutBody = CheckoutRequestBody.refine(
|
|
2459
|
+
(data) => data.slug !== void 0 || data.products !== void 0,
|
|
2460
|
+
{
|
|
2461
|
+
message: "Either `slug` or `products` is required.",
|
|
2462
|
+
path: ["products"]
|
|
2463
|
+
}
|
|
2464
|
+
);
|
|
2465
|
+
var SERVER_ONLY_CHECKOUT_FIELDS = [
|
|
2466
|
+
"products",
|
|
2467
|
+
"slug",
|
|
2468
|
+
"name",
|
|
2469
|
+
"description",
|
|
2470
|
+
"metadata",
|
|
2471
|
+
"successUrl",
|
|
2472
|
+
"failureUrl",
|
|
2473
|
+
"maxNumberOfPayments",
|
|
2474
|
+
"validUntil",
|
|
2475
|
+
"couponIds"
|
|
2476
|
+
];
|
|
2388
2477
|
function buildItem(productId, quantity) {
|
|
2389
2478
|
return {
|
|
2390
2479
|
product_id: productId,
|
|
@@ -2409,6 +2498,69 @@ async function resolveProducts(body, options) {
|
|
|
2409
2498
|
(entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
|
|
2410
2499
|
);
|
|
2411
2500
|
}
|
|
2501
|
+
function rejectUntrustedClientFields(body) {
|
|
2502
|
+
const supplied = SERVER_ONLY_CHECKOUT_FIELDS.filter(
|
|
2503
|
+
(field) => Object.hasOwn(body, field) && body[field] !== void 0
|
|
2504
|
+
);
|
|
2505
|
+
if (supplied.length === 0) return;
|
|
2506
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
2507
|
+
code: "CHECKOUT_CLIENT_FIELDS_FORBIDDEN",
|
|
2508
|
+
message: "Checkout product and payment fields must be resolved by the server."
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
function mergeCheckoutOverrides(body, overrides) {
|
|
2512
|
+
const effective = { ...body };
|
|
2513
|
+
if (overrides.products !== void 0) {
|
|
2514
|
+
effective.products = overrides.products;
|
|
2515
|
+
delete effective.slug;
|
|
2516
|
+
}
|
|
2517
|
+
if (overrides.name !== void 0) effective.name = overrides.name;
|
|
2518
|
+
if (overrides.description !== void 0) effective.description = overrides.description;
|
|
2519
|
+
if (overrides.successUrl !== void 0) effective.successUrl = overrides.successUrl;
|
|
2520
|
+
if (overrides.failureUrl !== void 0) effective.failureUrl = overrides.failureUrl;
|
|
2521
|
+
if (overrides.maxNumberOfPayments !== void 0) {
|
|
2522
|
+
effective.maxNumberOfPayments = overrides.maxNumberOfPayments;
|
|
2523
|
+
}
|
|
2524
|
+
if (overrides.validUntil !== void 0) effective.validUntil = overrides.validUntil;
|
|
2525
|
+
if (overrides.couponIds !== void 0) effective.couponIds = overrides.couponIds;
|
|
2526
|
+
if (overrides.referenceId !== void 0) effective.referenceId = overrides.referenceId;
|
|
2527
|
+
if (overrides.metadata !== void 0) {
|
|
2528
|
+
effective.metadata = { ...body.metadata ?? {}, ...overrides.metadata };
|
|
2529
|
+
}
|
|
2530
|
+
return effective;
|
|
2531
|
+
}
|
|
2532
|
+
function validateEffectiveCheckout(body, logger2) {
|
|
2533
|
+
const parsed = CheckoutBody.safeParse(body);
|
|
2534
|
+
if (parsed.success) return parsed.data;
|
|
2535
|
+
const invalidPaths = [
|
|
2536
|
+
...new Set(
|
|
2537
|
+
parsed.error.issues.map((issue) => issue.path.length > 0 ? issue.path.join(".") : "<root>")
|
|
2538
|
+
)
|
|
2539
|
+
].join(", ");
|
|
2540
|
+
logger2.error(`resolved checkout validation failed at: ${invalidPaths}`);
|
|
2541
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2542
|
+
message: "Checkout resolution produced invalid parameters."
|
|
2543
|
+
});
|
|
2544
|
+
}
|
|
2545
|
+
function checkoutUser(rawUser, user) {
|
|
2546
|
+
if (!user || rawUser === null || typeof rawUser !== "object") return null;
|
|
2547
|
+
return { ...rawUser, ...user };
|
|
2548
|
+
}
|
|
2549
|
+
async function deactivatePaymentLinkBestEffort(client, paymentLinkId, logger2) {
|
|
2550
|
+
if (!client.updatePaymentLinkStatus) {
|
|
2551
|
+
logger2.error(
|
|
2552
|
+
`checkout compensation unavailable for payment_link=${paymentLinkId}: client does not implement updatePaymentLinkStatus`
|
|
2553
|
+
);
|
|
2554
|
+
return;
|
|
2555
|
+
}
|
|
2556
|
+
try {
|
|
2557
|
+
await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
|
|
2558
|
+
} catch (err) {
|
|
2559
|
+
logger2.error(
|
|
2560
|
+
`checkout compensation failed for payment_link=${paymentLinkId}: ${formatStreamPayError(err)}`
|
|
2561
|
+
);
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2412
2564
|
function resolveRedirectUrl(urlOrPath, request, baseURL) {
|
|
2413
2565
|
if (!urlOrPath) return void 0;
|
|
2414
2566
|
return new URL(urlOrPath, request?.url ?? baseURL).toString();
|
|
@@ -2418,99 +2570,157 @@ async function resolveConsumerId(options, ctx, user) {
|
|
|
2418
2570
|
const { consumerId } = await ensureConsumerForUser(options, ctx, user);
|
|
2419
2571
|
return consumerId;
|
|
2420
2572
|
}
|
|
2421
|
-
var checkout = (checkoutOptions = {}) =>
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2573
|
+
var checkout = (checkoutOptions = {}) => {
|
|
2574
|
+
return (options) => {
|
|
2575
|
+
const client = options.client;
|
|
2576
|
+
return {
|
|
2577
|
+
endpoints: {
|
|
2578
|
+
checkout: api.createAuthEndpoint(
|
|
2579
|
+
"/checkout",
|
|
2580
|
+
{
|
|
2581
|
+
method: "POST",
|
|
2582
|
+
body: checkoutOptions.resolveCheckout ? CheckoutRequestBody : CheckoutBody
|
|
2583
|
+
},
|
|
2584
|
+
async (ctx) => {
|
|
2585
|
+
const session = await api.getSessionFromCtx(ctx);
|
|
2586
|
+
const sessionUser = asSessionUser(session?.user);
|
|
2587
|
+
const user = checkoutUser(session?.user, sessionUser);
|
|
2588
|
+
if (checkoutOptions.authenticatedUsersOnly) {
|
|
2589
|
+
if (!sessionUser) {
|
|
2590
|
+
throw new api.APIError("UNAUTHORIZED", {
|
|
2591
|
+
message: "You must be logged in to checkout."
|
|
2592
|
+
});
|
|
2593
|
+
}
|
|
2594
|
+
if (sessionUser.isAnonymous) {
|
|
2595
|
+
throw new api.APIError("UNAUTHORIZED", {
|
|
2596
|
+
message: "Anonymous users cannot checkout."
|
|
2597
|
+
});
|
|
2598
|
+
}
|
|
2439
2599
|
}
|
|
2440
|
-
if (
|
|
2441
|
-
|
|
2442
|
-
message: "Anonymous users cannot checkout."
|
|
2443
|
-
});
|
|
2600
|
+
if (checkoutOptions.resolveCheckout) {
|
|
2601
|
+
rejectUntrustedClientFields(ctx.body);
|
|
2444
2602
|
}
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
const customMetadata = (() => {
|
|
2459
|
-
const base = ctx.body.metadata ?? {};
|
|
2460
|
-
const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
|
|
2461
|
-
return Object.keys(merged).length > 0 ? merged : null;
|
|
2462
|
-
})();
|
|
2463
|
-
const payload = {
|
|
2464
|
-
name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
2465
|
-
description: ctx.body.description ?? null,
|
|
2466
|
-
currency: checkoutOptions.currency ?? "SAR",
|
|
2467
|
-
items
|
|
2468
|
-
};
|
|
2469
|
-
if (consumerId !== null) payload.organization_consumer_id = consumerId;
|
|
2470
|
-
if (successUrl) payload.success_redirect_url = successUrl;
|
|
2471
|
-
if (failureUrl) payload.failure_redirect_url = failureUrl;
|
|
2472
|
-
if (ctx.body.maxNumberOfPayments !== void 0) {
|
|
2473
|
-
payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
|
|
2474
|
-
}
|
|
2475
|
-
if (ctx.body.validUntil !== void 0) {
|
|
2476
|
-
payload.valid_until = ctx.body.validUntil;
|
|
2477
|
-
}
|
|
2478
|
-
if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
|
|
2479
|
-
payload.coupons = ctx.body.couponIds;
|
|
2480
|
-
}
|
|
2481
|
-
if (customMetadata !== null) payload.custom_metadata = customMetadata;
|
|
2482
|
-
if (checkoutOptions.customFields) {
|
|
2483
|
-
payload.custom_fields = checkoutOptions.customFields;
|
|
2484
|
-
}
|
|
2485
|
-
if (checkoutOptions.contactInformationType) {
|
|
2486
|
-
payload.contact_information_type = checkoutOptions.contactInformationType;
|
|
2487
|
-
}
|
|
2488
|
-
try {
|
|
2489
|
-
const link = await client.createPaymentLink(payload);
|
|
2490
|
-
const url = client.getPaymentUrl(link);
|
|
2491
|
-
if (!url) {
|
|
2492
|
-
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2493
|
-
message: "StreamPay payment link created but no URL was returned."
|
|
2494
|
-
});
|
|
2603
|
+
let effective = ctx.body;
|
|
2604
|
+
if (checkoutOptions.resolveCheckout) {
|
|
2605
|
+
let overrides;
|
|
2606
|
+
try {
|
|
2607
|
+
overrides = await checkoutOptions.resolveCheckout({ user, body: ctx.body }, ctx);
|
|
2608
|
+
} catch (err) {
|
|
2609
|
+
if (err instanceof api.APIError) throw err;
|
|
2610
|
+
getLogger(ctx).error(`resolveCheckout failed: ${formatStreamPayError(err)}`);
|
|
2611
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2612
|
+
message: "Checkout resolution failed."
|
|
2613
|
+
});
|
|
2614
|
+
}
|
|
2615
|
+
effective = mergeCheckoutOverrides(ctx.body, overrides);
|
|
2495
2616
|
}
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
getLogger(ctx)
|
|
2617
|
+
effective = validateEffectiveCheckout(effective, getLogger(ctx));
|
|
2618
|
+
const items = await resolveProducts(effective, checkoutOptions);
|
|
2619
|
+
const consumerId = await resolveConsumerId(options, ctx, sessionUser);
|
|
2620
|
+
const successUrl = resolveRedirectUrl(
|
|
2621
|
+
effective.successUrl ?? checkoutOptions.successUrl,
|
|
2622
|
+
ctx.request,
|
|
2623
|
+
ctx.context.baseURL
|
|
2624
|
+
);
|
|
2625
|
+
const failureUrl = resolveRedirectUrl(
|
|
2626
|
+
effective.failureUrl ?? checkoutOptions.failureUrl,
|
|
2627
|
+
ctx.request,
|
|
2628
|
+
ctx.context.baseURL
|
|
2509
2629
|
);
|
|
2630
|
+
const customMetadata = (() => {
|
|
2631
|
+
const merged = { ...effective.metadata ?? {} };
|
|
2632
|
+
if (effective.referenceId !== void 0) {
|
|
2633
|
+
merged.referenceId = effective.referenceId;
|
|
2634
|
+
}
|
|
2635
|
+
return Object.keys(merged).length > 0 ? merged : null;
|
|
2636
|
+
})();
|
|
2637
|
+
const payload = {
|
|
2638
|
+
name: effective.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
2639
|
+
description: effective.description ?? null,
|
|
2640
|
+
currency: checkoutOptions.currency ?? "SAR",
|
|
2641
|
+
items
|
|
2642
|
+
};
|
|
2643
|
+
if (consumerId !== null) payload.organization_consumer_id = consumerId;
|
|
2644
|
+
if (successUrl) payload.success_redirect_url = successUrl;
|
|
2645
|
+
if (failureUrl) payload.failure_redirect_url = failureUrl;
|
|
2646
|
+
if (effective.maxNumberOfPayments !== void 0) {
|
|
2647
|
+
payload.max_number_of_payments = effective.maxNumberOfPayments;
|
|
2648
|
+
}
|
|
2649
|
+
if (effective.validUntil !== void 0) {
|
|
2650
|
+
payload.valid_until = effective.validUntil;
|
|
2651
|
+
}
|
|
2652
|
+
if (effective.couponIds && effective.couponIds.length > 0) {
|
|
2653
|
+
payload.coupons = effective.couponIds;
|
|
2654
|
+
}
|
|
2655
|
+
if (customMetadata !== null) payload.custom_metadata = customMetadata;
|
|
2656
|
+
if (checkoutOptions.customFields) {
|
|
2657
|
+
payload.custom_fields = checkoutOptions.customFields;
|
|
2658
|
+
}
|
|
2659
|
+
if (checkoutOptions.contactInformationType) {
|
|
2660
|
+
payload.contact_information_type = checkoutOptions.contactInformationType;
|
|
2661
|
+
}
|
|
2662
|
+
try {
|
|
2663
|
+
const link = await client.createPaymentLink(payload);
|
|
2664
|
+
const paymentLinkId = typeof link.id === "string" && link.id.length > 0 ? link.id : null;
|
|
2665
|
+
let url;
|
|
2666
|
+
try {
|
|
2667
|
+
const resolvedUrl = client.getPaymentUrl(link);
|
|
2668
|
+
if (!resolvedUrl) {
|
|
2669
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2670
|
+
message: "StreamPay payment link created but no URL was returned."
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
url = resolvedUrl;
|
|
2674
|
+
if (checkoutOptions.onCheckoutCreated) {
|
|
2675
|
+
if (!paymentLinkId) {
|
|
2676
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2677
|
+
message: "StreamPay payment link created but no id was returned."
|
|
2678
|
+
});
|
|
2679
|
+
}
|
|
2680
|
+
try {
|
|
2681
|
+
const callbackData = {
|
|
2682
|
+
user,
|
|
2683
|
+
paymentLinkId,
|
|
2684
|
+
url,
|
|
2685
|
+
payload
|
|
2686
|
+
};
|
|
2687
|
+
if (effective.referenceId !== void 0) {
|
|
2688
|
+
callbackData.referenceId = effective.referenceId;
|
|
2689
|
+
}
|
|
2690
|
+
await checkoutOptions.onCheckoutCreated(callbackData, ctx);
|
|
2691
|
+
} catch (err) {
|
|
2692
|
+
if (err instanceof api.APIError) throw err;
|
|
2693
|
+
getLogger(ctx).error(`onCheckoutCreated failed: ${formatStreamPayError(err)}`);
|
|
2694
|
+
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
2695
|
+
message: "Checkout persistence failed."
|
|
2696
|
+
});
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
} catch (err) {
|
|
2700
|
+
if (paymentLinkId) {
|
|
2701
|
+
await deactivatePaymentLinkBestEffort(client, paymentLinkId, getLogger(ctx));
|
|
2702
|
+
}
|
|
2703
|
+
throw err;
|
|
2704
|
+
}
|
|
2705
|
+
return ctx.json({
|
|
2706
|
+
url,
|
|
2707
|
+
id: paymentLinkId,
|
|
2708
|
+
redirect: ctx.body.redirect ?? true
|
|
2709
|
+
});
|
|
2710
|
+
} catch (err) {
|
|
2711
|
+
toAPIError(
|
|
2712
|
+
{
|
|
2713
|
+
logPrefix: "checkout creation failed:",
|
|
2714
|
+
userMessage: "StreamPay checkout creation failed."
|
|
2715
|
+
},
|
|
2716
|
+
err,
|
|
2717
|
+
getLogger(ctx)
|
|
2718
|
+
);
|
|
2719
|
+
}
|
|
2510
2720
|
}
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
}
|
|
2721
|
+
)
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2514
2724
|
};
|
|
2515
2725
|
};
|
|
2516
2726
|
var DEFAULT_PAGE_SIZE = 100;
|
|
@@ -2764,9 +2974,10 @@ function checkoutInProgressError() {
|
|
|
2764
2974
|
});
|
|
2765
2975
|
}
|
|
2766
2976
|
async function resumeOrReserveCheckoutSlot(args) {
|
|
2767
|
-
const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
|
|
2977
|
+
const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
|
|
2978
|
+
const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
|
|
2768
2979
|
const reuseCandidate = candidates.find(
|
|
2769
|
-
(row2) => row2
|
|
2980
|
+
(row2) => matchesCheckout(row2) && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
|
|
2770
2981
|
);
|
|
2771
2982
|
if (reuseCandidate) {
|
|
2772
2983
|
let recovery;
|
|
@@ -2805,21 +3016,23 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
2805
3016
|
where: [{ field: "activeSlotKey", value: activeSlotKey }]
|
|
2806
3017
|
});
|
|
2807
3018
|
if (reserved?.status !== "incomplete") throw err;
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
3019
|
+
if (matchesCheckout(reserved)) {
|
|
3020
|
+
let recovery;
|
|
3021
|
+
try {
|
|
3022
|
+
recovery = await recoverCheckoutUrl(client, reserved);
|
|
3023
|
+
} catch (recoveryError) {
|
|
3024
|
+
toAPIError(
|
|
3025
|
+
{
|
|
3026
|
+
logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
|
|
3027
|
+
userMessage: "Unable to resume subscription checkout."
|
|
3028
|
+
},
|
|
3029
|
+
recoveryError,
|
|
3030
|
+
log
|
|
3031
|
+
);
|
|
3032
|
+
}
|
|
3033
|
+
if (recovery.kind === "recovered") {
|
|
3034
|
+
return { kind: "recovered", row: reserved, url: recovery.url };
|
|
3035
|
+
}
|
|
2823
3036
|
}
|
|
2824
3037
|
const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
|
|
2825
3038
|
if (!reservationIsStale) throw checkoutInProgressError();
|
|
@@ -2845,24 +3058,67 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
2845
3058
|
}
|
|
2846
3059
|
return { kind: "reserved", row, consumerId };
|
|
2847
3060
|
}
|
|
2848
|
-
|
|
2849
|
-
// src/plugins/subscriptions/lifecycle.ts
|
|
2850
3061
|
function isAlreadyCanceledFreezeError(err) {
|
|
2851
3062
|
const sdkError = readSdkErrorFields(err);
|
|
2852
3063
|
const envelope = readEnvelope(sdkError.body);
|
|
2853
3064
|
return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
|
|
2854
3065
|
}
|
|
2855
3066
|
function subscriptionCouponIds(stream) {
|
|
3067
|
+
return couponIdsFromMetadata(stream.coupon_calculation_metadata);
|
|
3068
|
+
}
|
|
3069
|
+
function couponIdsFromMetadata(metadata) {
|
|
2856
3070
|
const coupons = [];
|
|
2857
|
-
for (const coupon of
|
|
3071
|
+
for (const coupon of metadata?.coupons ?? []) {
|
|
2858
3072
|
if (coupon.coupon_id) coupons.push(coupon.coupon_id);
|
|
2859
3073
|
}
|
|
2860
3074
|
return coupons;
|
|
2861
3075
|
}
|
|
3076
|
+
function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
|
|
3077
|
+
if (!stream.items?.length) {
|
|
3078
|
+
throw invalidProviderItems("StreamPay returned a subscription without any items.");
|
|
3079
|
+
}
|
|
3080
|
+
const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
|
|
3081
|
+
let matches = 0;
|
|
3082
|
+
const items = stream.items.map((item) => {
|
|
3083
|
+
const productId = subscriptionItemProductId(item);
|
|
3084
|
+
const quantity = item.quantity ?? 1;
|
|
3085
|
+
if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
|
|
3086
|
+
throw invalidProviderItems("StreamPay returned an invalid subscription item.");
|
|
3087
|
+
}
|
|
3088
|
+
const isPlanItem = productId === currentProductId;
|
|
3089
|
+
if (isPlanItem) matches += 1;
|
|
3090
|
+
const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
|
|
3091
|
+
(couponId) => !subscriptionCoupons.has(couponId)
|
|
3092
|
+
);
|
|
3093
|
+
return {
|
|
3094
|
+
product_id: isPlanItem ? targetProductId : productId,
|
|
3095
|
+
quantity: isPlanItem ? targetSeats : quantity,
|
|
3096
|
+
...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
|
|
3097
|
+
};
|
|
3098
|
+
});
|
|
3099
|
+
if (matches !== 1) {
|
|
3100
|
+
throw invalidProviderItems(
|
|
3101
|
+
`Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
|
|
3102
|
+
);
|
|
3103
|
+
}
|
|
3104
|
+
return items;
|
|
3105
|
+
}
|
|
3106
|
+
function invalidProviderItems(message) {
|
|
3107
|
+
return new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
3108
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3109
|
+
message
|
|
3110
|
+
});
|
|
3111
|
+
}
|
|
2862
3112
|
function configuredPlanForSubscription(subscription, plans) {
|
|
2863
|
-
|
|
3113
|
+
const matches = plans.list.filter(
|
|
2864
3114
|
(plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
|
|
2865
3115
|
);
|
|
3116
|
+
if (matches.length > 1) {
|
|
3117
|
+
throw invalidProviderItems(
|
|
3118
|
+
"StreamPay returned a subscription containing multiple configured plan products."
|
|
3119
|
+
);
|
|
3120
|
+
}
|
|
3121
|
+
return matches[0];
|
|
2866
3122
|
}
|
|
2867
3123
|
var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
|
|
2868
3124
|
var PlanSchema = zod.z.object({
|
|
@@ -2885,7 +3141,46 @@ var PlanSchema = zod.z.object({
|
|
|
2885
3141
|
message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
|
|
2886
3142
|
}).optional(),
|
|
2887
3143
|
group: zod.z.string().min(1, "has an empty `group`.").optional(),
|
|
3144
|
+
seatBilling: zod.z.object({
|
|
3145
|
+
default: zod.z.number().safe().int().positive().optional(),
|
|
3146
|
+
minimum: zod.z.number().safe().int().positive().optional(),
|
|
3147
|
+
maximum: zod.z.number().safe().int().positive().optional(),
|
|
3148
|
+
customerEditable: zod.z.boolean().optional()
|
|
3149
|
+
}).optional(),
|
|
2888
3150
|
limits: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
|
|
3151
|
+
}).superRefine((plan, ctx) => {
|
|
3152
|
+
const seats = plan.seatBilling;
|
|
3153
|
+
if (!seats) return;
|
|
3154
|
+
const minimum = seats.minimum ?? 1;
|
|
3155
|
+
const defaultSeats = seats.default ?? minimum;
|
|
3156
|
+
if (seats.maximum !== void 0 && seats.maximum < minimum) {
|
|
3157
|
+
ctx.addIssue({
|
|
3158
|
+
code: "custom",
|
|
3159
|
+
path: ["seatBilling", "maximum"],
|
|
3160
|
+
message: "must be greater than or equal to `minimum`."
|
|
3161
|
+
});
|
|
3162
|
+
}
|
|
3163
|
+
if (defaultSeats < minimum || seats.maximum !== void 0 && defaultSeats > seats.maximum) {
|
|
3164
|
+
ctx.addIssue({
|
|
3165
|
+
code: "custom",
|
|
3166
|
+
path: ["seatBilling", "default"],
|
|
3167
|
+
message: "must be within the configured minimum and maximum."
|
|
3168
|
+
});
|
|
3169
|
+
}
|
|
3170
|
+
if (seats.customerEditable && (seats.minimum === void 0 || seats.maximum === void 0)) {
|
|
3171
|
+
ctx.addIssue({
|
|
3172
|
+
code: "custom",
|
|
3173
|
+
path: ["seatBilling", "customerEditable"],
|
|
3174
|
+
message: "requires explicit `minimum` and `maximum` bounds for hosted checkout editing."
|
|
3175
|
+
});
|
|
3176
|
+
}
|
|
3177
|
+
if (seats.maximum !== void 0 && !Number.isSafeInteger(plan.priceInSmallestUnit * seats.maximum)) {
|
|
3178
|
+
ctx.addIssue({
|
|
3179
|
+
code: "custom",
|
|
3180
|
+
path: ["seatBilling", "maximum"],
|
|
3181
|
+
message: "produces an unsafe total with `priceInSmallestUnit`."
|
|
3182
|
+
});
|
|
3183
|
+
}
|
|
2889
3184
|
});
|
|
2890
3185
|
var PlansSchema = zod.z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
|
|
2891
3186
|
const seenNames = /* @__PURE__ */ new Set();
|
|
@@ -2989,6 +3284,15 @@ var CheckLimitQuery = zod.z.object({
|
|
|
2989
3284
|
count: zod.z.coerce.number().int().min(0),
|
|
2990
3285
|
group: zod.z.string().min(1).optional()
|
|
2991
3286
|
});
|
|
3287
|
+
function presentSubscription(row, plans) {
|
|
3288
|
+
return {
|
|
3289
|
+
...row,
|
|
3290
|
+
// The column is nullable during safe rolling migrations. Keep the public
|
|
3291
|
+
// contract stable while applications backfill legacy rows to one seat.
|
|
3292
|
+
seats: row.seats ?? 1,
|
|
3293
|
+
plan: plans.byName.get(row.plan) ?? null
|
|
3294
|
+
};
|
|
3295
|
+
}
|
|
2992
3296
|
async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
|
|
2993
3297
|
const user = requireUser(ctx);
|
|
2994
3298
|
const reference = resolveReference(user, query);
|
|
@@ -3039,12 +3343,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
|
|
|
3039
3343
|
]
|
|
3040
3344
|
});
|
|
3041
3345
|
const plans = await plansRef();
|
|
3042
|
-
return ctx.json(
|
|
3043
|
-
rows.map((row) => ({
|
|
3044
|
-
...row,
|
|
3045
|
-
plan: plans.byName.get(row.plan) ?? null
|
|
3046
|
-
}))
|
|
3047
|
-
);
|
|
3346
|
+
return ctx.json(rows.map((row) => presentSubscription(row, plans)));
|
|
3048
3347
|
}
|
|
3049
3348
|
),
|
|
3050
3349
|
currentSubscription: api.createAuthEndpoint(
|
|
@@ -3063,7 +3362,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
|
|
|
3063
3362
|
);
|
|
3064
3363
|
if (!live) return ctx.json(null);
|
|
3065
3364
|
const plans = await plansRef();
|
|
3066
|
-
return ctx.json(
|
|
3365
|
+
return ctx.json(presentSubscription(live, plans));
|
|
3067
3366
|
}
|
|
3068
3367
|
),
|
|
3069
3368
|
hasSubscriptionFeature: api.createAuthEndpoint(
|
|
@@ -3098,16 +3397,63 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
|
|
|
3098
3397
|
)
|
|
3099
3398
|
};
|
|
3100
3399
|
}
|
|
3400
|
+
function resolveSeatCount(plan, requested) {
|
|
3401
|
+
const seats = requested ?? plan.seatBilling?.default ?? plan.seatBilling?.minimum ?? 1;
|
|
3402
|
+
const minimum = plan.seatBilling?.minimum ?? 1;
|
|
3403
|
+
const maximum = plan.seatBilling?.maximum;
|
|
3404
|
+
if (!Number.isSafeInteger(seats) || seats < minimum || maximum !== void 0 && seats > maximum) {
|
|
3405
|
+
const range = maximum === void 0 ? `${minimum} or more` : `${minimum}\u2013${maximum}`;
|
|
3406
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
3407
|
+
code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
|
|
3408
|
+
message: `Plan "${plan.name}" requires a safe-integer seat count in the range ${range}.`
|
|
3409
|
+
});
|
|
3410
|
+
}
|
|
3411
|
+
return seats;
|
|
3412
|
+
}
|
|
3413
|
+
function quotedSeatTotal(plan, seats) {
|
|
3414
|
+
const total = plan.priceInSmallestUnit * seats;
|
|
3415
|
+
if (!Number.isSafeInteger(total)) {
|
|
3416
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
3417
|
+
code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
|
|
3418
|
+
message: `The quoted total for ${seats} seats exceeds JavaScript's safe-integer range.`
|
|
3419
|
+
});
|
|
3420
|
+
}
|
|
3421
|
+
return total;
|
|
3422
|
+
}
|
|
3423
|
+
function buildSeatCheckoutItem(plan, seats) {
|
|
3424
|
+
if (!plan.seatBilling?.customerEditable) {
|
|
3425
|
+
return {
|
|
3426
|
+
product_id: plan.productId,
|
|
3427
|
+
quantity: seats,
|
|
3428
|
+
allow_custom_quantity: false
|
|
3429
|
+
};
|
|
3430
|
+
}
|
|
3431
|
+
const minimum = plan.seatBilling.minimum;
|
|
3432
|
+
const maximum = plan.seatBilling.maximum;
|
|
3433
|
+
if (minimum === void 0 || maximum === void 0) {
|
|
3434
|
+
throw new TypeError(
|
|
3435
|
+
`Plan "${plan.name}" must configure seatBilling.minimum and seatBilling.maximum when customerEditable is true.`
|
|
3436
|
+
);
|
|
3437
|
+
}
|
|
3438
|
+
return {
|
|
3439
|
+
product_id: plan.productId,
|
|
3440
|
+
quantity: seats,
|
|
3441
|
+
allow_custom_quantity: true,
|
|
3442
|
+
min_quantity: minimum,
|
|
3443
|
+
max_quantity: maximum
|
|
3444
|
+
};
|
|
3445
|
+
}
|
|
3101
3446
|
|
|
3102
3447
|
// src/plugins/subscriptions/endpoints.ts
|
|
3103
3448
|
var SUBSCRIPTION_MODEL6 = "subscription";
|
|
3104
3449
|
var UpgradeBody = zod.z.object({
|
|
3105
3450
|
plan: zod.z.string().min(1),
|
|
3451
|
+
seats: zod.z.number().int().positive().safe().optional(),
|
|
3106
3452
|
referenceId: zod.z.string().min(1).optional(),
|
|
3107
3453
|
referenceType: zod.z.enum(["user", "organization", "custom"]).optional(),
|
|
3108
3454
|
successUrl: zod.z.string().url().optional(),
|
|
3109
3455
|
failureUrl: zod.z.string().url().optional()
|
|
3110
|
-
});
|
|
3456
|
+
}).strict();
|
|
3111
3457
|
var SuccessQuery = zod.z.object({
|
|
3112
3458
|
subscriptionId: zod.z.string().min(1)
|
|
3113
3459
|
});
|
|
@@ -3118,7 +3464,12 @@ var CancelBody = zod.z.object({
|
|
|
3118
3464
|
});
|
|
3119
3465
|
var ChangePlanBody = zod.z.object({
|
|
3120
3466
|
subscriptionId: zod.z.string().min(1),
|
|
3121
|
-
plan: zod.z.string().min(1)
|
|
3467
|
+
plan: zod.z.string().min(1),
|
|
3468
|
+
seats: zod.z.number().int().positive().safe().optional()
|
|
3469
|
+
}).strict();
|
|
3470
|
+
var UpdateSeatsBody = zod.z.object({
|
|
3471
|
+
subscriptionId: zod.z.string().min(1),
|
|
3472
|
+
seats: zod.z.number().int().positive().safe()
|
|
3122
3473
|
}).strict();
|
|
3123
3474
|
var FreezeBody = zod.z.object({
|
|
3124
3475
|
subscriptionId: zod.z.string().min(1),
|
|
@@ -3148,11 +3499,72 @@ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
|
|
|
3148
3499
|
return true;
|
|
3149
3500
|
}
|
|
3150
3501
|
if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
|
|
3151
|
-
const createdAt =
|
|
3152
|
-
return
|
|
3502
|
+
const createdAt = parseDate(subscription.created_at)?.getTime();
|
|
3503
|
+
return createdAt !== void 0 && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
|
|
3153
3504
|
}
|
|
3154
3505
|
function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
3155
3506
|
const client = options.client;
|
|
3507
|
+
const cancelPendingChangeEndpoint = (path) => api.createAuthEndpoint(
|
|
3508
|
+
path,
|
|
3509
|
+
{
|
|
3510
|
+
method: "POST",
|
|
3511
|
+
body: UnfreezeBody,
|
|
3512
|
+
use: [api.sessionMiddleware]
|
|
3513
|
+
},
|
|
3514
|
+
async (ctx) => {
|
|
3515
|
+
const { adapter, row } = await requireConfirmedOwnedSubscription(
|
|
3516
|
+
ctx,
|
|
3517
|
+
ctx.body.subscriptionId,
|
|
3518
|
+
subsOptions,
|
|
3519
|
+
"cancel-plan-change"
|
|
3520
|
+
);
|
|
3521
|
+
try {
|
|
3522
|
+
const plans = await plansRef();
|
|
3523
|
+
const current = await client.getSubscription(row.streampaySubscriptionId);
|
|
3524
|
+
if (!current.pending_change) {
|
|
3525
|
+
await adapter.update({
|
|
3526
|
+
model: SUBSCRIPTION_MODEL6,
|
|
3527
|
+
update: {
|
|
3528
|
+
...projectSubscriptionAgainstExisting(row, current),
|
|
3529
|
+
...projectPlanFields(current, plans),
|
|
3530
|
+
pendingPlan: null,
|
|
3531
|
+
pendingProductId: null,
|
|
3532
|
+
pendingPlanEffectiveAt: null,
|
|
3533
|
+
pendingSeats: null,
|
|
3534
|
+
pendingSeatsEffectiveAt: null
|
|
3535
|
+
},
|
|
3536
|
+
where: [{ field: "id", value: row.id }]
|
|
3537
|
+
});
|
|
3538
|
+
return ctx.json({ canceled: true, reused: true, subscription: current });
|
|
3539
|
+
}
|
|
3540
|
+
await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
|
|
3541
|
+
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3542
|
+
await adapter.update({
|
|
3543
|
+
model: SUBSCRIPTION_MODEL6,
|
|
3544
|
+
update: {
|
|
3545
|
+
...projectSubscriptionAgainstExisting(row, stream),
|
|
3546
|
+
...projectPlanFields(stream, plans),
|
|
3547
|
+
pendingPlan: null,
|
|
3548
|
+
pendingProductId: null,
|
|
3549
|
+
pendingPlanEffectiveAt: null,
|
|
3550
|
+
pendingSeats: null,
|
|
3551
|
+
pendingSeatsEffectiveAt: null
|
|
3552
|
+
},
|
|
3553
|
+
where: [{ field: "id", value: row.id }]
|
|
3554
|
+
});
|
|
3555
|
+
return ctx.json({ canceled: true, reused: false, subscription: stream });
|
|
3556
|
+
} catch (err) {
|
|
3557
|
+
toAPIError(
|
|
3558
|
+
{
|
|
3559
|
+
logPrefix: `cancel pending subscription change failed for row=${row.id}:`,
|
|
3560
|
+
userMessage: "Canceling the pending subscription change failed."
|
|
3561
|
+
},
|
|
3562
|
+
err,
|
|
3563
|
+
getLogger(ctx)
|
|
3564
|
+
);
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
);
|
|
3156
3568
|
return {
|
|
3157
3569
|
...buildSubscriptionReadEndpoints(subsOptions, plansRef),
|
|
3158
3570
|
upgradeSubscription: api.createAuthEndpoint(
|
|
@@ -3175,6 +3587,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3175
3587
|
message: `Plan "${ctx.body.plan}" is not configured.`
|
|
3176
3588
|
});
|
|
3177
3589
|
}
|
|
3590
|
+
const seats = resolveSeatCount(plan, ctx.body.seats);
|
|
3591
|
+
const quotedTotal = quotedSeatTotal(plan, seats);
|
|
3178
3592
|
const adapter = getAdapter2(ctx);
|
|
3179
3593
|
const existingActive = await adapter.findMany({
|
|
3180
3594
|
model: SUBSCRIPTION_MODEL6,
|
|
@@ -3212,6 +3626,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3212
3626
|
candidates: existingActive,
|
|
3213
3627
|
activeSlotKey,
|
|
3214
3628
|
planName: plan.name,
|
|
3629
|
+
seats,
|
|
3215
3630
|
now: Date.now(),
|
|
3216
3631
|
log: getLogger(ctx),
|
|
3217
3632
|
createReservation: async () => {
|
|
@@ -3231,13 +3646,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3231
3646
|
planVersion: plan.version ?? null,
|
|
3232
3647
|
productId: plan.productId,
|
|
3233
3648
|
group: plan.group ?? null,
|
|
3649
|
+
seats,
|
|
3234
3650
|
streampayConsumerId: consumerId2,
|
|
3235
3651
|
streampayPaymentLinkId: null,
|
|
3236
3652
|
status: "incomplete",
|
|
3237
3653
|
providerStatus: null,
|
|
3238
3654
|
billingStatus: "current",
|
|
3239
|
-
amountInSmallestUnit:
|
|
3240
|
-
originalAmountInSmallestUnit:
|
|
3655
|
+
amountInSmallestUnit: quotedTotal,
|
|
3656
|
+
originalAmountInSmallestUnit: quotedTotal,
|
|
3241
3657
|
currency: plan.currency ?? "SAR",
|
|
3242
3658
|
billingInterval: plan.billingInterval,
|
|
3243
3659
|
billingIntervalCount: plan.billingIntervalCount ?? 1,
|
|
@@ -3253,6 +3669,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3253
3669
|
pendingPlan: null,
|
|
3254
3670
|
pendingProductId: null,
|
|
3255
3671
|
pendingPlanEffectiveAt: null,
|
|
3672
|
+
pendingSeats: null,
|
|
3673
|
+
pendingSeatsEffectiveAt: null,
|
|
3256
3674
|
endedAt: null,
|
|
3257
3675
|
frozenAt: null,
|
|
3258
3676
|
freezeEndAt: null,
|
|
@@ -3271,14 +3689,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3271
3689
|
redirect: true,
|
|
3272
3690
|
reused: true,
|
|
3273
3691
|
status: reservation.row.status,
|
|
3274
|
-
plan: reservation.row.plan
|
|
3692
|
+
plan: reservation.row.plan,
|
|
3693
|
+
seats: reservation.row.seats ?? 1
|
|
3275
3694
|
});
|
|
3276
3695
|
}
|
|
3277
3696
|
const { row, consumerId } = reservation;
|
|
3278
3697
|
const linkInput = {
|
|
3279
3698
|
name: `Subscription \u2014 ${plan.name}`,
|
|
3280
3699
|
currency: plan.currency ?? "SAR",
|
|
3281
|
-
items: [
|
|
3700
|
+
items: [buildSeatCheckoutItem(plan, seats)],
|
|
3282
3701
|
max_number_of_payments: 1,
|
|
3283
3702
|
organization_consumer_id: consumerId,
|
|
3284
3703
|
custom_metadata: {
|
|
@@ -3371,7 +3790,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3371
3790
|
redirect: true,
|
|
3372
3791
|
reused: false,
|
|
3373
3792
|
status: "incomplete",
|
|
3374
|
-
plan: plan.name
|
|
3793
|
+
plan: plan.name,
|
|
3794
|
+
seats
|
|
3375
3795
|
});
|
|
3376
3796
|
}
|
|
3377
3797
|
),
|
|
@@ -3442,6 +3862,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3442
3862
|
model: SUBSCRIPTION_MODEL6,
|
|
3443
3863
|
update: {
|
|
3444
3864
|
...projectSubscriptionFields(match),
|
|
3865
|
+
...projectPlanFields(match, plans),
|
|
3445
3866
|
planVersion: plan.version ?? null,
|
|
3446
3867
|
productId: plan.productId,
|
|
3447
3868
|
billingStatus: "current",
|
|
@@ -3553,8 +3974,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3553
3974
|
}
|
|
3554
3975
|
try {
|
|
3555
3976
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3556
|
-
const currentPlan = configuredPlanForSubscription(stream, plans);
|
|
3557
|
-
|
|
3977
|
+
const currentPlan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
|
|
3978
|
+
if (!currentPlan) {
|
|
3979
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
3980
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3981
|
+
message: "The current StreamPay product is not a configured subscription plan."
|
|
3982
|
+
});
|
|
3983
|
+
}
|
|
3984
|
+
const currentGroup = currentPlan.group ?? row.group;
|
|
3558
3985
|
if (currentGroup !== (nextPlan.group ?? null)) {
|
|
3559
3986
|
throw new api.APIError("BAD_REQUEST", {
|
|
3560
3987
|
code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
|
|
@@ -3567,27 +3994,35 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3567
3994
|
message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
|
|
3568
3995
|
});
|
|
3569
3996
|
}
|
|
3570
|
-
const
|
|
3571
|
-
(item) => subscriptionItemProductId(item) ===
|
|
3997
|
+
const currentItem = stream.items?.find(
|
|
3998
|
+
(item) => subscriptionItemProductId(item) === currentPlan.productId
|
|
3572
3999
|
);
|
|
3573
|
-
|
|
4000
|
+
const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
|
|
4001
|
+
const nextSeats = resolveSeatCount(nextPlan, ctx.body.seats ?? currentSeats ?? 1);
|
|
4002
|
+
const currentProductIsRequestedPlan = currentPlan.productId === nextPlan.productId;
|
|
4003
|
+
if (currentProductIsRequestedPlan && currentSeats === nextSeats && !stream.pending_change) {
|
|
3574
4004
|
throw new api.APIError("BAD_REQUEST", {
|
|
3575
4005
|
code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
|
|
3576
|
-
message: `Already on plan "${nextPlan.name}".`
|
|
4006
|
+
message: `Already on plan "${nextPlan.name}" with ${nextSeats} seats.`
|
|
3577
4007
|
});
|
|
3578
4008
|
}
|
|
3579
4009
|
const pendingTargets = stream.pending_change?.target_items ?? [];
|
|
3580
|
-
const
|
|
4010
|
+
const pendingTarget = pendingTargets.find(
|
|
3581
4011
|
(item) => subscriptionItemProductId(item) === nextPlan.productId
|
|
3582
4012
|
);
|
|
3583
|
-
|
|
4013
|
+
const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
|
|
4014
|
+
if (pendingTargetMatches) {
|
|
4015
|
+
const effectiveAt2 = stream.pending_change?.effective_at ?? null;
|
|
3584
4016
|
await adapter.update({
|
|
3585
4017
|
model: SUBSCRIPTION_MODEL6,
|
|
3586
4018
|
update: {
|
|
3587
4019
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
4020
|
+
...projectPlanFields(stream, plans),
|
|
4021
|
+
pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
|
|
4022
|
+
pendingProductId: currentPlan.productId === nextPlan.productId ? null : nextPlan.productId,
|
|
4023
|
+
pendingPlanEffectiveAt: currentPlan.productId !== nextPlan.productId && effectiveAt2 ? parseDate(effectiveAt2) : null,
|
|
4024
|
+
pendingSeats: nextSeats,
|
|
4025
|
+
pendingSeatsEffectiveAt: parseDate(effectiveAt2)
|
|
3591
4026
|
},
|
|
3592
4027
|
where: [{ field: "id", value: row.id }]
|
|
3593
4028
|
});
|
|
@@ -3595,7 +4030,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3595
4030
|
mode: "at_period_end",
|
|
3596
4031
|
subscriptionId: row.id,
|
|
3597
4032
|
plan: nextPlan.name,
|
|
3598
|
-
|
|
4033
|
+
seats: nextSeats,
|
|
4034
|
+
effectiveAt: effectiveAt2,
|
|
3599
4035
|
pendingChange: stream.pending_change,
|
|
3600
4036
|
reused: true
|
|
3601
4037
|
});
|
|
@@ -3607,28 +4043,36 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3607
4043
|
});
|
|
3608
4044
|
}
|
|
3609
4045
|
const patch = {
|
|
3610
|
-
items:
|
|
4046
|
+
items: subscriptionItemsForUpdate(
|
|
4047
|
+
stream,
|
|
4048
|
+
currentPlan.productId,
|
|
4049
|
+
nextPlan.productId,
|
|
4050
|
+
nextSeats
|
|
4051
|
+
),
|
|
3611
4052
|
coupons: subscriptionCouponIds(stream),
|
|
3612
4053
|
recurring_interval: nextPlan.billingInterval,
|
|
3613
4054
|
recurring_interval_count: nextPlan.billingIntervalCount ?? 1
|
|
3614
4055
|
};
|
|
3615
4056
|
const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
|
|
3616
|
-
const
|
|
4057
|
+
const pending = Boolean(result.pending_change);
|
|
4058
|
+
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4059
|
+
const planProjection = projectPlanFields(result, plans);
|
|
3617
4060
|
await adapter.update({
|
|
3618
4061
|
model: SUBSCRIPTION_MODEL6,
|
|
3619
4062
|
update: {
|
|
3620
4063
|
...projectSubscriptionAgainstExisting(row, result),
|
|
3621
|
-
|
|
3622
|
-
pendingProductId: nextPlan.productId,
|
|
3623
|
-
pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
|
|
4064
|
+
...planProjection,
|
|
3624
4065
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3625
4066
|
},
|
|
3626
4067
|
where: [{ field: "id", value: row.id }]
|
|
3627
4068
|
});
|
|
4069
|
+
const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
|
|
4070
|
+
const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
|
|
3628
4071
|
return ctx.json({
|
|
3629
|
-
mode: "at_period_end",
|
|
4072
|
+
mode: pending ? "at_period_end" : "immediate",
|
|
3630
4073
|
subscriptionId: row.id,
|
|
3631
|
-
plan:
|
|
4074
|
+
plan: providerPlan,
|
|
4075
|
+
seats: providerSeats,
|
|
3632
4076
|
effectiveAt,
|
|
3633
4077
|
pendingChange: result.pending_change ?? null,
|
|
3634
4078
|
subscription: result,
|
|
@@ -3646,11 +4090,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3646
4090
|
}
|
|
3647
4091
|
}
|
|
3648
4092
|
),
|
|
3649
|
-
|
|
3650
|
-
"/subscription/
|
|
4093
|
+
updateSubscriptionSeats: api.createAuthEndpoint(
|
|
4094
|
+
"/subscription/update-seats",
|
|
3651
4095
|
{
|
|
3652
4096
|
method: "POST",
|
|
3653
|
-
body:
|
|
4097
|
+
body: UpdateSeatsBody,
|
|
3654
4098
|
use: [api.sessionMiddleware]
|
|
3655
4099
|
},
|
|
3656
4100
|
async (ctx) => {
|
|
@@ -3658,27 +4102,107 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3658
4102
|
ctx,
|
|
3659
4103
|
ctx.body.subscriptionId,
|
|
3660
4104
|
subsOptions,
|
|
3661
|
-
"
|
|
4105
|
+
"update-seats"
|
|
3662
4106
|
);
|
|
4107
|
+
const plans = await plansRef();
|
|
3663
4108
|
try {
|
|
3664
|
-
await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
|
|
3665
4109
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
4110
|
+
const plan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
|
|
4111
|
+
if (!plan) {
|
|
4112
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
4113
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
4114
|
+
message: "The current StreamPay product is not a configured subscription plan."
|
|
4115
|
+
});
|
|
4116
|
+
}
|
|
4117
|
+
if (stream.cancel_at_period_end) {
|
|
4118
|
+
throw new api.APIError("CONFLICT", {
|
|
4119
|
+
code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
|
|
4120
|
+
message: "Uncancel the subscription before scheduling a seat change."
|
|
4121
|
+
});
|
|
4122
|
+
}
|
|
4123
|
+
const seats = resolveSeatCount(plan, ctx.body.seats);
|
|
4124
|
+
const currentItem = stream.items?.find(
|
|
4125
|
+
(item) => subscriptionItemProductId(item) === plan.productId
|
|
4126
|
+
);
|
|
4127
|
+
const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
|
|
4128
|
+
const pendingTarget = stream.pending_change?.target_items?.find(
|
|
4129
|
+
(item) => subscriptionItemProductId(item) === plan.productId
|
|
4130
|
+
);
|
|
4131
|
+
if (stream.pending_change) {
|
|
4132
|
+
if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
|
|
4133
|
+
const effectiveAt2 = stream.pending_change.effective_at ?? null;
|
|
4134
|
+
await adapter.update({
|
|
4135
|
+
model: SUBSCRIPTION_MODEL6,
|
|
4136
|
+
update: {
|
|
4137
|
+
...projectSubscriptionAgainstExisting(row, stream),
|
|
4138
|
+
...projectPlanFields(stream, plans)
|
|
4139
|
+
},
|
|
4140
|
+
where: [{ field: "id", value: row.id }]
|
|
4141
|
+
});
|
|
4142
|
+
return ctx.json({
|
|
4143
|
+
mode: "at_period_end",
|
|
4144
|
+
subscriptionId: row.id,
|
|
4145
|
+
seats,
|
|
4146
|
+
effectiveAt: effectiveAt2,
|
|
4147
|
+
pendingChange: stream.pending_change,
|
|
4148
|
+
reused: true
|
|
4149
|
+
});
|
|
4150
|
+
}
|
|
4151
|
+
throw new api.APIError("CONFLICT", {
|
|
4152
|
+
code: $ERROR_CODES.SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED.code,
|
|
4153
|
+
message: "A different subscription change is pending. Cancel it before scheduling this seat count."
|
|
4154
|
+
});
|
|
4155
|
+
}
|
|
4156
|
+
if (currentSeats === seats) {
|
|
4157
|
+
await adapter.update({
|
|
4158
|
+
model: SUBSCRIPTION_MODEL6,
|
|
4159
|
+
update: {
|
|
4160
|
+
...projectSubscriptionAgainstExisting(row, stream),
|
|
4161
|
+
...projectPlanFields(stream, plans)
|
|
4162
|
+
},
|
|
4163
|
+
where: [{ field: "id", value: row.id }]
|
|
4164
|
+
});
|
|
4165
|
+
return ctx.json({
|
|
4166
|
+
mode: "current",
|
|
4167
|
+
subscriptionId: row.id,
|
|
4168
|
+
seats,
|
|
4169
|
+
effectiveAt: null,
|
|
4170
|
+
pendingChange: null,
|
|
4171
|
+
reused: true
|
|
4172
|
+
});
|
|
4173
|
+
}
|
|
4174
|
+
const patch = {
|
|
4175
|
+
items: subscriptionItemsForUpdate(stream, plan.productId, plan.productId, seats),
|
|
4176
|
+
coupons: subscriptionCouponIds(stream)
|
|
4177
|
+
};
|
|
4178
|
+
const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
|
|
4179
|
+
const pending = Boolean(result.pending_change);
|
|
4180
|
+
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4181
|
+
const planProjection = projectPlanFields(result, plans);
|
|
3666
4182
|
await adapter.update({
|
|
3667
4183
|
model: SUBSCRIPTION_MODEL6,
|
|
3668
4184
|
update: {
|
|
3669
|
-
...projectSubscriptionAgainstExisting(row,
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
pendingPlanEffectiveAt: null
|
|
4185
|
+
...projectSubscriptionAgainstExisting(row, result),
|
|
4186
|
+
...planProjection,
|
|
4187
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
3673
4188
|
},
|
|
3674
4189
|
where: [{ field: "id", value: row.id }]
|
|
3675
4190
|
});
|
|
3676
|
-
|
|
4191
|
+
const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
|
|
4192
|
+
return ctx.json({
|
|
4193
|
+
mode: pending ? "at_period_end" : "immediate",
|
|
4194
|
+
subscriptionId: row.id,
|
|
4195
|
+
seats: providerSeats,
|
|
4196
|
+
effectiveAt,
|
|
4197
|
+
pendingChange: result.pending_change ?? null,
|
|
4198
|
+
subscription: result,
|
|
4199
|
+
reused: false
|
|
4200
|
+
});
|
|
3677
4201
|
} catch (err) {
|
|
3678
4202
|
toAPIError(
|
|
3679
4203
|
{
|
|
3680
|
-
logPrefix: `
|
|
3681
|
-
userMessage: "
|
|
4204
|
+
logPrefix: `update-seats failed for row=${row.id}:`,
|
|
4205
|
+
userMessage: "Seat change scheduling failed."
|
|
3682
4206
|
},
|
|
3683
4207
|
err,
|
|
3684
4208
|
getLogger(ctx)
|
|
@@ -3686,6 +4210,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3686
4210
|
}
|
|
3687
4211
|
}
|
|
3688
4212
|
),
|
|
4213
|
+
cancelSubscriptionPlanChange: cancelPendingChangeEndpoint("/subscription/change-plan/cancel"),
|
|
4214
|
+
cancelSubscriptionPendingChange: cancelPendingChangeEndpoint(
|
|
4215
|
+
"/subscription/pending-change/cancel"
|
|
4216
|
+
),
|
|
3689
4217
|
uncancelSubscription: api.createAuthEndpoint(
|
|
3690
4218
|
"/subscription/uncancel",
|
|
3691
4219
|
{
|
|
@@ -3785,9 +4313,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3785
4313
|
const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
|
|
3786
4314
|
const active = freezes.data?.find((freeze) => {
|
|
3787
4315
|
if (!freeze.id || !freeze.freeze_start_datetime) return false;
|
|
3788
|
-
const start =
|
|
3789
|
-
const end = freeze.freeze_end_datetime ?
|
|
3790
|
-
return start <= nowMs && nowMs <= end;
|
|
4316
|
+
const start = parseDate(freeze.freeze_start_datetime)?.getTime();
|
|
4317
|
+
const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
|
|
4318
|
+
return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
|
|
3791
4319
|
});
|
|
3792
4320
|
if (!active?.id || !active.freeze_start_datetime) {
|
|
3793
4321
|
throw new api.APIError("BAD_REQUEST", {
|
|
@@ -3927,6 +4455,11 @@ var subscriptionTable = {
|
|
|
3927
4455
|
required: false,
|
|
3928
4456
|
index: true
|
|
3929
4457
|
},
|
|
4458
|
+
seats: {
|
|
4459
|
+
type: "number",
|
|
4460
|
+
required: false,
|
|
4461
|
+
defaultValue: 1
|
|
4462
|
+
},
|
|
3930
4463
|
amountInSmallestUnit: {
|
|
3931
4464
|
type: "number",
|
|
3932
4465
|
required: false
|
|
@@ -4015,6 +4548,14 @@ var subscriptionTable = {
|
|
|
4015
4548
|
type: "date",
|
|
4016
4549
|
required: false
|
|
4017
4550
|
},
|
|
4551
|
+
pendingSeats: {
|
|
4552
|
+
type: "number",
|
|
4553
|
+
required: false
|
|
4554
|
+
},
|
|
4555
|
+
pendingSeatsEffectiveAt: {
|
|
4556
|
+
type: "date",
|
|
4557
|
+
required: false
|
|
4558
|
+
},
|
|
4018
4559
|
endedAt: {
|
|
4019
4560
|
type: "date",
|
|
4020
4561
|
required: false
|
|
@@ -4613,7 +5154,7 @@ var onUserDelete = (options) => async (user, context) => {
|
|
|
4613
5154
|
|
|
4614
5155
|
// package.json
|
|
4615
5156
|
var package_default = {
|
|
4616
|
-
version: "2.
|
|
5157
|
+
version: "2.2.0"};
|
|
4617
5158
|
|
|
4618
5159
|
// src/version.ts
|
|
4619
5160
|
var version = package_default.version;
|
|
@@ -4640,7 +5181,8 @@ var streampay = (options) => {
|
|
|
4640
5181
|
streampayConsumerId: {
|
|
4641
5182
|
type: "string",
|
|
4642
5183
|
required: false,
|
|
4643
|
-
input: false
|
|
5184
|
+
input: false,
|
|
5185
|
+
unique: true
|
|
4644
5186
|
}
|
|
4645
5187
|
}
|
|
4646
5188
|
},
|