Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(billing): restore cancel after failed seat update

Richie McIlroyccfd334e6c29
diff --git a/apps/web/__tests__/unit/update-seat-quantity.test.ts b/apps/web/__tests__/unit/update-seat-quantity.test.ts
index 838531a96..5c15fce60 100644
--- a/apps/web/__tests__/unit/update-seat-quantity.test.ts
+++ b/apps/web/__tests__/unit/update-seat-quantity.test.ts
@@ -109,6 +109,7 @@ function mockSeatLookup({
.mockResolvedValueOnce([]);
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ cancel_at_period_end: false,
items: {
data: [{ id: "si_1", quantity: currentQuantity }],
},
@@ -133,7 +134,11 @@ describe("updateSeatQuantity", () => {
const result = await updateSeatQuantity("org-1" as never, 2);
- expect(result).toEqual({ success: true, newQuantity: 2 });
+ expect(result).toEqual({
+ success: true,
+ newQuantity: 2,
+ cancelAtPeriodEnd: false,
+ });
expect(mockStripe.subscriptions.update).toHaveBeenCalledWith("sub_1", {
items: [{ id: "si_1", quantity: 2 }],
payment_behavior: "pending_if_incomplete",
@@ -158,17 +163,107 @@ describe("updateSeatQuantity", () => {
expect(mockDb.set).not.toHaveBeenCalled();
});
- it("keeps prorated credits for seat reductions on the next invoice", async () => {
+ it("does not credit the current period when seats decrease", async () => {
+ mockSeatLookup({ currentQuantity: 3 });
+ const { updateSeatQuantity } = await import(
+ "@/actions/organization/update-seat-quantity"
+ );
+
+ await updateSeatQuantity("org-1" as never, 2);
+
+ expect(mockStripe.subscriptions.update).toHaveBeenCalledWith("sub_1", {
+ items: [{ id: "si_1", quantity: 2 }],
+ proration_behavior: "none",
+ });
+ });
+
+ it("clears scheduled cancellation in the same decrease update", async () => {
mockSeatLookup({ currentQuantity: 3 });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ id: "sub_1",
+ cancel_at_period_end: true,
+ items: {
+ data: [{ id: "si_1", quantity: 3 }],
+ },
+ });
const { updateSeatQuantity } = await import(
"@/actions/organization/update-seat-quantity"
);
await updateSeatQuantity("org-1" as never, 2);
+ expect(mockStripe.subscriptions.update).toHaveBeenCalledTimes(1);
expect(mockStripe.subscriptions.update).toHaveBeenCalledWith("sub_1", {
items: [{ id: "si_1", quantity: 2 }],
- proration_behavior: "create_prorations",
+ proration_behavior: "none",
+ cancel_at_period_end: false,
});
});
+
+ it("restores scheduled cancellation when a seat increase fails", async () => {
+ mockSeatLookup({ currentQuantity: 1 });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ id: "sub_1",
+ cancel_at_period_end: true,
+ items: {
+ data: [{ id: "si_1", quantity: 1 }],
+ },
+ });
+ mockStripe.subscriptions.update
+ .mockResolvedValueOnce({ id: "sub_1", pending_update: null })
+ .mockRejectedValueOnce(new Error("card declined"));
+ const { updateSeatQuantity } = await import(
+ "@/actions/organization/update-seat-quantity"
+ );
+
+ await expect(updateSeatQuantity("org-1" as never, 2)).rejects.toThrow(
+ "card declined",
+ );
+ expect(mockStripe.subscriptions.update).toHaveBeenNthCalledWith(
+ 1,
+ "sub_1",
+ {
+ cancel_at_period_end: false,
+ },
+ );
+ expect(mockStripe.subscriptions.update).toHaveBeenNthCalledWith(
+ 3,
+ "sub_1",
+ {
+ cancel_at_period_end: true,
+ },
+ );
+ expect(mockDb.set).not.toHaveBeenCalled();
+ });
+
+ it("restores scheduled cancellation when added seats stay pending", async () => {
+ mockSeatLookup({ currentQuantity: 1 });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ id: "sub_1",
+ cancel_at_period_end: true,
+ items: {
+ data: [{ id: "si_1", quantity: 1 }],
+ },
+ });
+ mockStripe.subscriptions.update
+ .mockResolvedValueOnce({ id: "sub_1", pending_update: null })
+ .mockResolvedValueOnce({
+ id: "sub_1",
+ pending_update: { expires_at: 123 },
+ });
+ const { updateSeatQuantity } = await import(
+ "@/actions/organization/update-seat-quantity"
+ );
+
+ await expect(updateSeatQuantity("org-1" as never, 2)).rejects.toThrow(
+ "Payment for the added seats could not be completed.",
+ );
+ expect(mockStripe.subscriptions.update).toHaveBeenNthCalledWith(
+ 3,
+ "sub_1",
+ {
+ cancel_at_period_end: true,
+ },
+ );
+ });
});
diff --git a/apps/web/actions/organization/update-seat-quantity.ts b/apps/web/actions/organization/update-seat-quantity.ts
index 43eb2e8d5..c05cdc520 100644
--- a/apps/web/actions/organization/update-seat-quantity.ts
+++ b/apps/web/actions/organization/update-seat-quantity.ts
@@ -193,55 +193,81 @@ export async function updateSeatQuantity(
}
const isSeatIncrease = newQuantity > currentQuantity;
- // Choosing a seat count revokes any scheduled cancellation. Stripe rejects
- // cancel_at_period_end combined with payment_behavior=pending_if_incomplete,
- // so it must be cleared in a separate call before the quantity update.
- if (subscription.cancel_at_period_end) {
- await stripe().subscriptions.update(subscription.id, {
- cancel_at_period_end: false,
- });
- }
- // Increases charge the prorated difference immediately; decreases take
- // effect immediately but never credit or refund the already-paid period —
- // the next renewal simply bills the lower quantity.
- const updatedSubscription = await stripe().subscriptions.update(
- subscription.id,
- {
- items: [
- {
- id: subscriptionItem.id,
- quantity: newQuantity,
- },
- ],
- proration_behavior: isSeatIncrease ? "always_invoice" : "none",
- ...(isSeatIncrease
- ? { payment_behavior: "pending_if_incomplete" as const }
- : {}),
- },
- );
-
- if (isSeatIncrease && updatedSubscription.pending_update) {
- throw new Error(
- "Payment for the added seats could not be completed. Update your payment method and try again.",
- );
- }
+ const wasCanceling = subscription.cancel_at_period_end;
+ // Stripe rejects cancel_at_period_end combined with
+ // payment_behavior=pending_if_incomplete, so increases clear cancellation
+ // first. If that later update fails, restore the scheduled cancel.
+ const restoreScheduledCancellation = async () => {
+ try {
+ await stripe().subscriptions.update(subscription.id, {
+ cancel_at_period_end: true,
+ });
+ } catch (restoreError) {
+ console.error(
+ "Failed to restore scheduled Cap Pro cancellation",
+ subscription.id,
+ restoreError,
+ );
+ }
+ };
+ let quantityUpdated = false;
try {
- await db()
- .update(users)
- .set({ inviteQuota: newQuantity })
- .where(eq(users.id, user.id));
- } catch (dbError) {
- console.error(
- "CRITICAL: Stripe updated to quantity",
- newQuantity,
- "but DB update failed for user",
- user.id,
- dbError,
- );
- throw new Error(
- "Billing update succeeded but local state could not be saved. Please contact support.",
+ if (isSeatIncrease && wasCanceling) {
+ await stripe().subscriptions.update(subscription.id, {
+ cancel_at_period_end: false,
+ });
+ }
+
+ const updatedSubscription = await stripe().subscriptions.update(
+ subscription.id,
+ {
+ items: [
+ {
+ id: subscriptionItem.id,
+ quantity: newQuantity,
+ },
+ ],
+ proration_behavior: isSeatIncrease ? "always_invoice" : "none",
+ ...(isSeatIncrease
+ ? { payment_behavior: "pending_if_incomplete" as const }
+ : {}),
+ ...(!isSeatIncrease && wasCanceling
+ ? { cancel_at_period_end: false }
+ : {}),
+ },
);
+
+ if (isSeatIncrease && updatedSubscription.pending_update) {
+ throw new Error(
+ "Payment for the added seats could not be completed. Update your payment method and try again.",
+ );
+ }
+
+ quantityUpdated = true;
+
+ try {
+ await db()
+ .update(users)
+ .set({ inviteQuota: newQuantity })
+ .where(eq(users.id, user.id));
+ } catch (dbError) {
+ console.error(
+ "CRITICAL: Stripe updated to quantity",
+ newQuantity,
+ "but DB update failed for user",
+ user.id,
+ dbError,
+ );
+ throw new Error(
+ "Billing update succeeded but local state could not be saved. Please contact support.",
+ );
+ }
+ } catch (error) {
+ if (wasCanceling && !quantityUpdated) {
+ await restoreScheduledCancellation();
+ }
+ throw error;
}
revalidatePath("/dashboard/settings/organization");