Merge pull request #6073 from Dokploy/fix/5770-stale-subscription-events

This commit is contained in:
Narciso E. Núñez Arias
2026-11-18 23:32:51 -04:00
committed by GitHub
4 changed files with 132 additions and 50 deletions
@@ -202,11 +202,13 @@ export const ShowBilling = () => {
productId,
serverQuantity,
isAnnual,
}).then(async (session) => {
await stripe?.redirectToCheckout({
sessionId: session.sessionId,
});
});
})
.then(async (session) => {
await stripe?.redirectToCheckout({
sessionId: session.sessionId,
});
})
.catch((error) => toast.error(error.message));
}
};
@@ -228,7 +230,8 @@ export const ShowBilling = () => {
const canSubscribe =
!isEnterpriseCloud &&
(data?.subscriptions?.length ?? 0) === 0 &&
!billingStatus?.isOnTrial;
!billingStatus?.isOnTrial &&
!billingStatus?.hasPaymentIssue;
const maxServers = admin?.user.serversQuantity ?? 1;
const percentage = ((servers ?? 0) / maxServers) * 100;
const safePercentage = Math.min(percentage, 100);
@@ -429,6 +432,33 @@ export const ShowBilling = () => {
)}
</div>
)}
{!isEnterpriseCloud &&
billingStatus?.hasPaymentIssue &&
admin?.user.stripeCustomerId && (
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-destructive/40 bg-destructive/5 p-4 max-w-2xl">
<div className="flex items-center gap-3">
<AlertTriangle className="h-5 w-5 text-destructive shrink-0" />
<div className="flex flex-col">
<span className="text-sm font-medium">
Payment failed
</span>
<span className="text-sm text-muted-foreground">
We couldn't charge your last invoice. Update your
payment method to reactivate your servers.
</span>
</div>
</div>
<Button
size="sm"
onClick={async () => {
const session = await createCustomerPortalSession();
window.open(session.url);
}}
>
Update payment method
</Button>
</div>
)}
{canStartTrial && (
<div className="flex items-center gap-3 rounded-xl border border-primary/30 bg-primary/5 p-4 max-w-2xl">
<Clock className="h-5 w-5 text-primary shrink-0" />
+62 -44
View File
@@ -97,6 +97,9 @@ export default async function handler(
const subscription = await stripe.subscriptions.retrieve(
session.subscription as string,
);
if (hasEnded(subscription)) {
break;
}
const serversQuantity = getSubscriptionServersQuantity(
subscription?.items?.data ?? [],
);
@@ -134,6 +137,17 @@ export default async function handler(
case "customer.subscription.created": {
const newSubscription = event.data.object as Stripe.Subscription;
const subscription = await stripe.subscriptions.retrieve(
newSubscription.id,
);
// A late event of an older subscription must not replace the current one.
if (
subscription.status !== "active" &&
subscription.status !== "trialing"
) {
break;
}
await db
.update(user)
.set({
@@ -154,19 +168,6 @@ export default async function handler(
case "customer.subscription.deleted": {
const newSubscription = event.data.object as Stripe.Subscription;
await db
.update(user)
.set({
stripeSubscriptionId: null,
serversQuantity: 0,
})
.where(
and(
eq(user.stripeCustomerId, newSubscription.customer as string),
eq(user.isEnterpriseCloud, false),
),
);
const admin = await findUserByStripeCustomerId(
newSubscription.customer as string,
);
@@ -177,6 +178,18 @@ export default async function handler(
break;
}
if (isReplacedSubscription(admin, newSubscription.id)) {
break;
}
await db
.update(user)
.set({
stripeSubscriptionId: null,
serversQuantity: 0,
})
.where(eq(user.id, admin.id));
// Paying through checkout cancels the leftover trial subscription;
// that is a conversion, not a lost trial.
const otherActive = await stripe.subscriptions
@@ -219,7 +232,10 @@ export default async function handler(
return res.status(400).send("Webhook Error: Admin not found");
}
if (admin.isEnterpriseCloud) {
if (
admin.isEnterpriseCloud ||
isReplacedSubscription(admin, newSubscription.id)
) {
break;
}
@@ -250,13 +266,8 @@ export default async function handler(
);
await db
.update(user)
.set({ serversQuantity })
.where(
and(
eq(user.stripeCustomerId, newSubscription.customer as string),
eq(user.isEnterpriseCloud, false),
),
);
.set({ serversQuantity, stripeSubscriptionId: newSubscription.id })
.where(eq(user.id, admin.id));
await updateServersBasedOnQuantity(admin.id, serversQuantity);
} else {
@@ -264,12 +275,7 @@ export default async function handler(
await db
.update(user)
.set({ serversQuantity: 0 })
.where(
and(
eq(user.stripeCustomerId, newSubscription.customer as string),
eq(user.isEnterpriseCloud, false),
),
);
.where(eq(user.id, admin.id));
}
break;
@@ -299,22 +305,22 @@ export default async function handler(
return res.status(400).send("Webhook Error: Admin not found");
}
if (
admin.isEnterpriseCloud ||
isReplacedSubscription(admin, subscription.id)
) {
break;
}
const serversQuantity = getSubscriptionServersQuantity(
subscription?.items?.data ?? [],
);
// Restores an id cleared by an old subscription's deletion.
await db
.update(user)
.set({ serversQuantity })
.where(
and(
eq(user.stripeCustomerId, subscription.customer as string),
eq(user.isEnterpriseCloud, false),
),
);
.set({ serversQuantity, stripeSubscriptionId: subscription.id })
.where(eq(user.id, admin.id));
if (admin.isEnterpriseCloud) {
break;
}
await updateServersBasedOnQuantity(admin.id, serversQuantity);
if (admin.sendInvoiceNotifications) {
@@ -341,7 +347,10 @@ export default async function handler(
return res.status(400).send("Webhook Error: Admin not found");
}
if (admin.isEnterpriseCloud) {
if (
admin.isEnterpriseCloud ||
isReplacedSubscription(admin, subscription.id)
) {
break;
}
@@ -354,12 +363,7 @@ export default async function handler(
.set({
serversQuantity: 0,
})
.where(
and(
eq(user.stripeCustomerId, newInvoice.customer as string),
eq(user.isEnterpriseCloud, false),
),
);
.where(eq(user.id, admin.id));
await disableServers(admin.id);
}
@@ -421,6 +425,20 @@ const findUserByStripeCustomerId = async (stripeCustomerId: string) => {
return userResult;
};
// Late events of an ended subscription must not make it current again.
const hasEnded = (subscription: Stripe.Subscription) =>
subscription.status === "canceled" ||
subscription.status === "incomplete_expired" ||
subscription.status === "unpaid";
// A customer can hold several subscriptions; only the one stored on the
// owner may change their plan and servers.
const isReplacedSubscription = (
admin: { stripeSubscriptionId: string | null },
subscriptionId: string,
) =>
!!admin.stripeSubscriptionId && admin.stripeSubscriptionId !== subscriptionId;
const getInvoiceSubscriptionId = (invoice: Stripe.Invoice): string | null => {
const subscription = invoice.subscription;
if (typeof subscription === "string") return subscription;
+20
View File
@@ -11,6 +11,7 @@ import { z } from "zod";
import {
getBillingStatus,
getCurrentPlan as getCurrentPlanForOrganization,
LIVE_SUBSCRIPTION_STATUSES,
startTrial,
TRIAL_DURATION_DAYS,
TRIAL_SERVER_LIMITS,
@@ -217,6 +218,25 @@ export const stripeRouter = createTRPCRouter({
}
}
if (stripeCustomerId) {
const subscriptions = await stripe.subscriptions.list({
customer: stripeCustomerId,
status: "all",
limit: 100,
});
if (
subscriptions.data.some((sub) =>
LIVE_SUBSCRIPTION_STATUSES.includes(sub.status),
)
) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
"You already have a subscription. Manage it from the billing portal.",
});
}
}
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: items,
+14
View File
@@ -78,6 +78,14 @@ export const getCurrentPlan = async (
return getCurrentPlanForUser(ownerId);
};
// Checkout reuses the owner's customer, so any of these would keep billing
// alongside the new subscription.
export const LIVE_SUBSCRIPTION_STATUSES: Stripe.Subscription.Status[] = [
"active",
"trialing",
"past_due",
];
export const TRIAL_DURATION_DAYS = 7;
export type TrialTier = "hobby" | "startup";
export const TRIAL_SERVER_LIMITS: Record<TrialTier, number> = {
@@ -92,6 +100,7 @@ export interface BillingStatus {
trialDaysRemaining: number | null;
hasUsedTrial: boolean;
hasActiveAccess: boolean;
hasPaymentIssue: boolean;
hasPaymentMethod: boolean;
isAnnual: boolean;
isEnterpriseCloud: boolean;
@@ -108,6 +117,7 @@ export const getBillingStatus = async (
trialDaysRemaining: null,
hasUsedTrial: false,
hasActiveAccess: true,
hasPaymentIssue: false,
hasPaymentMethod: true,
isAnnual: false,
isEnterpriseCloud: false,
@@ -123,6 +133,7 @@ export const getBillingStatus = async (
trialDaysRemaining: null,
hasUsedTrial: false,
hasActiveAccess: false,
hasPaymentIssue: false,
hasPaymentMethod: false,
isAnnual: false,
isEnterpriseCloud: owner?.isEnterpriseCloud ?? false,
@@ -174,6 +185,9 @@ export const getBillingStatus = async (
hasPaymentMethod,
hasUsedTrial: subscriptions.data.length > 0,
hasActiveAccess: plan !== null || !!trialingSub,
hasPaymentIssue:
plan === null &&
subscriptions.data.some((sub) => sub.status === "past_due"),
isAnnual,
isEnterpriseCloud: owner.isEnterpriseCloud,
};