Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

fix(billing): retain paid tier during payment retries

Mohamed Bassem62c133cbaa00
diff --git a/apps/web/components/settings/SubscriptionSettings.tsx b/apps/web/components/settings/SubscriptionSettings.tsx
index fdfc8ab7..3eadab3d 100644
--- a/apps/web/components/settings/SubscriptionSettings.tsx
+++ b/apps/web/components/settings/SubscriptionSettings.tsx
@@ -4,11 +4,11 @@ import { useEffect, useState } from "react";
import { toast } from "@/components/ui/sonner";
import { useTranslation } from "@/lib/i18n/client";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { Check, Loader2 } from "lucide-react";
+import { Check, Loader2, TriangleAlert } from "lucide-react";
import { useTRPC } from "@karakeep/shared-react/trpc";
-import { Alert, AlertDescription } from "../ui/alert";
+import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
@@ -160,6 +160,11 @@ export default function SubscriptionSettings() {
<div className="flex items-center gap-2">
{subscriptionStatus?.tier &&
getStatusBadge(subscriptionStatus.tier)}
+ {subscriptionStatus?.paymentFailed && (
+ <Badge variant="destructive">
+ {t("settings.subscription.payment_failed")}
+ </Badge>
+ )}
</div>
</div>
@@ -282,14 +287,30 @@ export default function SubscriptionSettings() {
</div>
) : (
<div className="space-y-4">
+ {subscriptionStatus.paymentFailed && (
+ <Alert variant="destructive">
+ <TriangleAlert className="h-4 w-4" />
+ <AlertTitle>
+ {t("settings.subscription.payment_failed_title")}
+ </AlertTitle>
+ <AlertDescription>
+ {t("settings.subscription.payment_failed_description")}
+ </AlertDescription>
+ </Alert>
+ )}
+
<div className="flex gap-2">
<Button
onClick={() => createPortalSession.mutate()}
disabled={isLoading}
- variant="outline"
+ variant={
+ subscriptionStatus.paymentFailed ? "default" : "outline"
+ }
>
{isLoading && <Loader2 className="h-4 w-4 animate-spin" />}
- {t("settings.subscription.manage_billing")}
+ {subscriptionStatus.paymentFailed
+ ? t("settings.subscription.update_payment_method")
+ : t("settings.subscription.manage_billing")}
</Button>
</div>
diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.json
index b6c0e768..6a205751 100644
--- a/apps/web/lib/i18n/locales/en/translation.json
+++ b/apps/web/lib/i18n/locales/en/translation.json
@@ -544,6 +544,10 @@
"unlock_bigger_quota": "Unlock bigger quota and support the project",
"subscribe_now": "Subscribe Now",
"manage_billing": "Manage Billing",
+ "update_payment_method": "Update Payment Method",
+ "payment_failed": "Payment failed",
+ "payment_failed_title": "Your last payment failed",
+ "payment_failed_description": "We couldn't charge your payment method. Update it to keep your Paid plan. We'll retry the charge in the meantime, and your plan will switch to Free if all retries fail.",
"subscription_canceled": "Your subscription has been canceled and will end on {{date}}. You can resubscribe at any time.",
"usage_quotas": "Usage & Quotas",
"track_usage": "Track your current usage against your plan limits",
diff --git a/packages/shared-server/src/eventLogTypes.ts b/packages/shared-server/src/eventLogTypes.ts
index e8623159..8bc7b201 100644
--- a/packages/shared-server/src/eventLogTypes.ts
+++ b/packages/shared-server/src/eventLogTypes.ts
@@ -197,6 +197,7 @@ type EventLogInternal =
| "renewed"
| "scheduled_cancellation"
| "resubscribe"
+ | "payment_failed"
| "no_change";
}
| {
diff --git a/packages/trpc/routers/subscriptions.test.ts b/packages/trpc/routers/subscriptions.test.ts
index a590b734..d574da1c 100644
--- a/packages/trpc/routers/subscriptions.test.ts
+++ b/packages/trpc/routers/subscriptions.test.ts
@@ -124,6 +124,7 @@ describe("Subscription Routes", () => {
startDate: null,
endDate: null,
hasActiveSubscription: false,
+ paymentFailed: false,
cancelAtPeriodEnd: false,
});
});
@@ -162,9 +163,35 @@ describe("Subscription Routes", () => {
startDate,
endDate,
hasActiveSubscription: true,
+ paymentFailed: false,
cancelAtPeriodEnd: true,
});
});
+
+ test<CustomTestContext>("keeps the paid tier and flags the failed payment while past_due", async ({
+ db,
+ }) => {
+ const user = await createTestUser(db, {
+ name: "Test User",
+ email: "[email protected]",
+ password: "pass1234",
+ });
+ const caller = getApiCaller(db, user.id);
+
+ await db.insert(subscriptions).values({
+ userId: user.id,
+ stripeCustomerId: "cus_123",
+ stripeSubscriptionId: "sub_123",
+ status: "past_due",
+ tier: "paid",
+ });
+
+ const status = await caller.subscriptions.getSubscriptionStatus();
+
+ expect(status.tier).toBe("paid");
+ expect(status.hasActiveSubscription).toBe(true);
+ expect(status.paymentFailed).toBe(true);
+ });
});
describe("manual tier", () => {
@@ -192,6 +219,7 @@ describe("Subscription Routes", () => {
startDate: null,
endDate: null,
hasActiveSubscription: false,
+ paymentFailed: false,
cancelAtPeriodEnd: false,
});
});
@@ -1112,7 +1140,7 @@ describe("Subscription Routes", () => {
});
expect(subscription?.status).toBe("past_due");
- expect(subscription?.tier).toBe("free"); // past_due status should set tier to free
+ expect(subscription?.tier).toBe("paid"); // past_due keeps the paid tier while Stripe retries
});
test<CustomTestContext>("handles customer.subscription.deleted event", async ({
@@ -1530,7 +1558,7 @@ describe("Subscription Routes", () => {
object: {
id: "sub_123",
customer: "cus_123",
- status: "past_due",
+ status: "unpaid",
current_period_start: 1640995200,
current_period_end: 1643673600,
metadata: {
@@ -1540,12 +1568,12 @@ describe("Subscription Routes", () => {
},
};
- // Mock the Stripe subscriptions.list response for past_due status
+ // Mock the Stripe subscriptions.list response for unpaid status
mockSubscriptionsList.mockResolvedValue({
data: [
{
id: "sub_123",
- status: "past_due",
+ status: "unpaid",
cancel_at_period_end: false,
items: {
data: [
diff --git a/packages/trpc/routers/subscriptions.ts b/packages/trpc/routers/subscriptions.ts
index 8cbf7830..3df5ebf4 100644
--- a/packages/trpc/routers/subscriptions.ts
+++ b/packages/trpc/routers/subscriptions.ts
@@ -62,12 +62,21 @@ const allowedEvents: Stripe.Event.Type[] = [
"payment_intent.canceled",
];
+// Statuses that keep the paid entitlements. `past_due` means a renewal charge
+// failed and Stripe is still retrying it; the user keeps the paid tier during
+// that window and gets downgraded once Stripe gives up and moves the
+// subscription to `canceled` or `unpaid`.
+function isPaidStatus(status: string | null | undefined) {
+ return status === "active" || status === "trialing" || status === "past_due";
+}
+
type SubscriptionTransition =
| "upgrade"
| "downgrade"
| "renewed"
| "scheduled_cancellation"
| "resubscribe"
+ | "payment_failed"
| "no_change";
function computeSubscriptionTransition(
@@ -82,6 +91,9 @@ function computeSubscriptionTransition(
if (wasPaid && !isPaid) {
return "downgrade";
}
+ if (prev.status !== "past_due" && next.status === "past_due") {
+ return "payment_failed";
+ }
if (!prev.cancelAtPeriodEnd && next.cancelAtPeriodEnd) {
return "scheduled_cancellation";
}
@@ -201,17 +213,17 @@ export async function syncStripeDataToDatabase(
// A customer can have more than one subscription. For example, while
// upgrading from a monthly to a yearly plan the old monthly subscription
// lingers until its period ends. The subscription that reflects the
- // user's entitlement is the active/trialing one whose period extends
+ // user's entitlement is the paid one whose period extends
// furthest into the future: when the old monthly plan is finally
// canceled it fires `customer.subscription.deleted`, and a naive
// `data[0]` (or `limit: 1`) can pick up that canceled subscription and
// wrongly downgrade a user who still has an active yearly plan. Prefer
- // the active/trialing subscription with the latest end date, and only
- // fall back to the newest one when none are active.
+ // the paid subscription with the latest end date, and only fall back to
+ // the newest one when none are paid.
const periodEnd = (sub: Stripe.Subscription) =>
sub.items.data[0]?.current_period_end ?? 0;
- const activeSubscriptions = subscriptionsList.data.filter(
- (sub) => sub.status === "active" || sub.status === "trialing",
+ const activeSubscriptions = subscriptionsList.data.filter((sub) =>
+ isPaidStatus(sub.status),
);
const subscription =
activeSubscriptions.length > 0
@@ -224,10 +236,9 @@ export async function syncStripeDataToDatabase(
const subData = {
stripeSubscriptionId: subscription.id,
status: subscription.status,
- tier:
- subscription.status === "active" || subscription.status === "trialing"
- ? ("paid" as const)
- : ("free" as const),
+ tier: isPaidStatus(subscription.status)
+ ? ("paid" as const)
+ : ("free" as const),
priceId: subscription.items.data[0]?.price.id || null,
cancelAtPeriodEnd: subscription.cancel_at_period_end,
startDate: subscriptionItem.current_period_start
@@ -254,7 +265,7 @@ export async function syncStripeDataToDatabase(
.where(eq(subscriptions.stripeCustomerId, customerId))
.run();
- if (subData.status === "active" || subData.status === "trialing") {
+ if (subData.tier === "paid") {
// Enable paid tier quotas and browser crawling. A real subscription
// supersedes a manually granted tier, so clear it.
trx
@@ -357,6 +368,7 @@ export const subscriptionsRouter = router({
startDate: null,
endDate: null,
hasActiveSubscription: false,
+ paymentFailed: false,
cancelAtPeriodEnd: false,
};
}
@@ -367,8 +379,8 @@ export const subscriptionsRouter = router({
status: subscription.status,
startDate: subscription.startDate,
endDate: subscription.endDate,
- hasActiveSubscription:
- subscription.status === "active" || subscription.status === "trialing",
+ hasActiveSubscription: isPaidStatus(subscription.status),
+ paymentFailed: subscription.status === "past_due",
cancelAtPeriodEnd: subscription.cancelAtPeriodEnd || false,
};
}),
@@ -452,7 +464,7 @@ export const subscriptionsRouter = router({
const existingSubscription = user.subscription;
- if (existingSubscription?.status === "active") {
+ if (isPaidStatus(existingSubscription?.status)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "User already has an active subscription",
@@ -641,11 +653,7 @@ export const subscriptionsRouter = router({
});
}
- if (
- input.manualTierName &&
- (user.subscription?.status === "active" ||
- user.subscription?.status === "trialing")
- ) {
+ if (input.manualTierName && isPaidStatus(user.subscription?.status)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "User already has an active Stripe subscription",