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 persistence

Richie McIlroy3573e8e3925d
diff --git a/apps/web/__tests__/unit/update-seat-quantity.test.ts b/apps/web/__tests__/unit/update-seat-quantity.test.ts
index 402f701a6..a2a84fa0a 100644
--- a/apps/web/__tests__/unit/update-seat-quantity.test.ts
+++ b/apps/web/__tests__/unit/update-seat-quantity.test.ts
@@ -267,7 +267,7 @@ describe("updateSeatQuantity", () => {
);
});
- it("does not restore cancellation after Stripe applies the new quantity", async () => {
+ it("restores scheduled cancellation when the local quota write fails", async () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
@@ -284,9 +284,9 @@ describe("updateSeatQuantity", () => {
);
await expect(updateSeatQuantity("org-1" as never, 2)).rejects.toThrow(
- "local state could not be saved",
+ "scheduled cancellation is still in effect",
);
- expect(mockStripe.subscriptions.update).not.toHaveBeenCalledWith("sub_1", {
+ expect(mockStripe.subscriptions.update).toHaveBeenCalledWith("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 415ffbda6..af1b19089 100644
--- a/apps/web/actions/organization/update-seat-quantity.ts
+++ b/apps/web/actions/organization/update-seat-quantity.ts
@@ -196,7 +196,7 @@ export async function updateSeatQuantity(
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.
+ // first. Restore it if the quantity update or local persistence fails.
const restoreScheduledCancellation = async () => {
try {
await stripe().subscriptions.update(subscription.id, {
@@ -255,6 +255,9 @@ export async function updateSeatQuantity(
.set({ inviteQuota: newQuantity })
.where(eq(users.id, user.id));
} catch (dbError) {
+ if (wasCanceling) {
+ await restoreScheduledCancellation();
+ }
console.error(
"CRITICAL: Stripe updated to quantity",
newQuantity,
@@ -263,7 +266,9 @@ export async function updateSeatQuantity(
dbError,
);
throw new Error(
- "Billing update succeeded but local state could not be saved. Please contact support.",
+ wasCanceling
+ ? "We couldn't save the seat change. Your scheduled cancellation is still in effect. Please try again."
+ : "Billing update succeeded but local state could not be saved. Please contact support.",
);
}