Merge pull request #5477 from Dokploy/feat/trial-expiration-emails

fix(billing): pick a plan for the trial and warn before it expires
This commit is contained in:
Mauricio Siu
2026-09-18 03:04:07 -06:00
committed by GitHub
12 changed files with 743 additions and 427 deletions
@@ -6,28 +6,41 @@ import { api } from "@/utils/api";
export const TrialBanner = () => {
const router = useRouter();
const { data: billingStatus } = api.stripe.getBillingStatus.useQuery();
const { mutateAsync: createCustomerPortalSession, isPending } =
api.stripe.createCustomerPortalSession.useMutation();
if (!billingStatus?.isOnTrial) {
const handleAddPaymentMethod = async () => {
const session = await createCustomerPortalSession().catch(() => null);
if (session?.url) {
window.open(session.url);
return;
}
router.push("/dashboard/settings/billing");
};
if (!billingStatus?.isOnTrial || billingStatus.hasPaymentMethod) {
return null;
}
const daysRemaining = billingStatus.trialDaysRemaining ?? 0;
const daysLabel = `${daysRemaining} day${daysRemaining === 1 ? "" : "s"}`;
return (
<div className="sticky top-0 z-20 mx-4 mt-4 flex flex-wrap items-center justify-center gap-x-3 gap-y-2 rounded-lg border border-primary/20 bg-primary/10 px-4 py-2 text-sm">
<span className="flex items-center gap-2">
<Rocket className="h-4 w-4 text-primary shrink-0" />
{daysRemaining > 0
? `You have ${daysRemaining} day${daysRemaining === 1 ? "" : "s"} left in your free trial.`
: "Your free trial ends today."}
? `You have ${daysLabel} left in your free trial. Add a payment method to keep your servers.`
: "Your free trial ends today. Add a payment method to keep your servers."}
</span>
<Button
size="sm"
variant="default"
className="h-7"
onClick={() => router.push("/dashboard/settings/billing")}
isLoading={isPending}
onClick={handleAddPaymentMethod}
>
Upgrade now
Add payment method
</Button>
</div>
);
@@ -278,8 +278,9 @@ export const OnboardingWizard = ({ onClose }: Props) => {
<DialogTitle>Skip onboarding?</DialogTitle>
<DialogDescription>
If this is your first time using Dokploy, we recommend going
through these steps — it only takes a couple of minutes and gives
you a feel for how projects, servers and deployments fit together.
through these steps – it only takes a couple of minutes and gives
you a feel for how projects, servers, and deployments fit
together.
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -15,13 +15,50 @@ const stripePromise = loadStripe(
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
);
type Tier = "hobby" | "startup";
const PLANS: {
tier: Tier;
name: string;
description: string;
price: number;
features: string[];
recommended?: boolean;
}[] = [
{
tier: "hobby",
name: "Hobby",
description: "For individual developers",
price: calculatePriceHobby(1, false),
features: [
"Setup 1 server",
"Unlimited apps & databases",
"2 environments",
"Community support",
],
},
{
tier: "startup",
name: "Startup",
description: "For small to mid-size teams",
price: calculatePriceStartup(STARTUP_SERVERS_INCLUDED, false),
recommended: true,
features: [
`Setup up to ${STARTUP_SERVERS_INCLUDED} servers`,
"Unlimited users & environments",
"Basic RBAC + 2FA",
"Email & chat support",
],
},
];
interface Props {
onNext: () => void;
}
export const PlanStep = ({ onNext }: Props) => {
const [loadingTier, setLoadingTier] = useState<
"hobby" | "startup" | "trial" | null
const [loading, setLoading] = useState<
`${"trial" | "checkout"}:${Tier}` | null
>(null);
const { data } = api.stripe.getProducts.useQuery();
const { mutateAsync: createCheckoutSession } =
@@ -30,12 +67,12 @@ export const PlanStep = ({ onNext }: Props) => {
api.stripe.startFreeTrial.useMutation();
const utils = api.useUtils();
const handleCheckout = async (tier: "hobby" | "startup") => {
const handleCheckout = async (tier: Tier) => {
if (!data) return;
const productId =
tier === "hobby" ? data.hobbyProductId : data.startupProductId;
if (!productId) return;
setLoadingTier(tier);
setLoading(`checkout:${tier}`);
try {
const stripe = await stripePromise;
const session = await createCheckoutSession({
@@ -47,14 +84,14 @@ export const PlanStep = ({ onNext }: Props) => {
await stripe?.redirectToCheckout({ sessionId: session.sessionId });
} catch {
toast.error("Error starting checkout");
setLoadingTier(null);
setLoading(null);
}
};
const handleTrial = async () => {
setLoadingTier("trial");
const handleTrial = async (tier: Tier) => {
setLoading(`trial:${tier}`);
try {
await startFreeTrial();
await startFreeTrial({ tier });
await utils.project.onboardingStatus.invalidate();
toast.success("Your 7-day trial has started");
onNext();
@@ -63,7 +100,7 @@ export const PlanStep = ({ onNext }: Props) => {
error instanceof Error ? error.message : "Error starting trial",
);
} finally {
setLoadingTier(null);
setLoading(null);
}
};
@@ -79,134 +116,72 @@ export const PlanStep = ({ onNext }: Props) => {
Start free, upgrade when ready.
</h1>
<p className="text-muted-foreground text-lg max-w-md leading-relaxed">
No credit card for the trial — add one only if you decide to stay.
Try any plan free for 7 days. No credit card required — add one only
if you decide to stay.
</p>
</div>
<div className="flex flex-col rounded-2xl bg-zinc-950 dark:bg-white text-white dark:text-zinc-950 overflow-hidden">
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-6 p-7">
<div>
<span className="inline-flex items-center rounded-full bg-white text-zinc-950 dark:bg-zinc-950 dark:text-white font-mono text-[10px] font-semibold uppercase tracking-[0.15em] px-2.5 py-1">
Recommended
</span>
<p className={`${displayFont.className} text-2xl mt-3`}>
7-day free trial
</p>
<p className="text-sm text-zinc-400 dark:text-zinc-600 mt-1 max-w-xs">
No card required — cancel anytime.
</p>
<ul className="flex flex-col gap-1.5 mt-4">
{[
"Setup 1 server",
"Unlimited apps & databases",
"Community support",
].map((f) => (
<li
key={f}
className="flex items-center gap-2 text-sm text-zinc-300 dark:text-zinc-700"
>
<CheckIcon className="size-3.5 text-zinc-500 shrink-0" />
{f}
</li>
))}
</ul>
</div>
<Button
size="lg"
className="bg-white text-zinc-950 hover:bg-zinc-200 dark:bg-zinc-950 dark:text-white dark:hover:bg-zinc-800 w-fit shrink-0 px-6"
isLoading={loadingTier === "trial"}
disabled={loadingTier !== null}
onClick={handleTrial}
>
Start trial
<ArrowRightIcon className="size-4" />
</Button>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-px bg-border rounded-2xl overflow-hidden border">
<div className="flex flex-col justify-between gap-6 bg-background p-7">
<div>
<p className="font-medium">Hobby</p>
<p className="text-sm text-muted-foreground mt-1">
For individual developers
</p>
<p className="text-3xl font-semibold mt-4 tabular-nums">
${calculatePriceHobby(1, false).toFixed(2)}
<span className="text-sm font-normal text-muted-foreground">
{" "}
/mo
</span>
</p>
<ul className="flex flex-col gap-1.5 mt-4">
{[
"Setup 1 server",
"Unlimited apps & databases",
"2 environments",
"Community support",
].map((f) => (
<li
key={f}
className="flex items-center gap-2 text-sm text-muted-foreground"
{PLANS.map((plan) => {
const productId =
plan.tier === "hobby"
? data?.hobbyProductId
: data?.startupProductId;
return (
<div
key={plan.tier}
className="flex flex-col justify-between gap-6 bg-background p-7"
>
<div>
{plan.recommended && (
<span className="inline-flex items-center rounded-full bg-primary text-primary-foreground font-mono text-[10px] font-semibold uppercase tracking-[0.15em] px-2.5 py-1 mb-3">
Recommended
</span>
)}
<p className="font-medium">{plan.name}</p>
<p className="text-sm text-muted-foreground mt-1">
{plan.description}
</p>
<p className="text-3xl font-semibold mt-4 tabular-nums">
${plan.price.toFixed(2)}
<span className="text-sm font-normal text-muted-foreground">
{" "}
/mo
</span>
</p>
<ul className="flex flex-col gap-1.5 mt-4">
{plan.features.map((f) => (
<li
key={f}
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<CheckIcon className="size-3.5 shrink-0" />
{f}
</li>
))}
</ul>
</div>
<div className="flex flex-col gap-2">
<Button
isLoading={loading === `trial:${plan.tier}`}
disabled={loading !== null}
onClick={() => handleTrial(plan.tier)}
>
<CheckIcon className="size-3.5 shrink-0" />
{f}
</li>
))}
</ul>
</div>
<Button
variant="outline"
isLoading={loadingTier === "hobby"}
disabled={loadingTier !== null || !data?.hobbyProductId}
onClick={() => handleCheckout("hobby")}
>
Subscribe
</Button>
</div>
<div className="flex flex-col justify-between gap-6 bg-background p-7">
<div>
<p className="font-medium">Startup</p>
<p className="text-sm text-muted-foreground mt-1">
For small to mid-size teams
</p>
<p className="text-3xl font-semibold mt-4 tabular-nums">
$
{calculatePriceStartup(STARTUP_SERVERS_INCLUDED, false).toFixed(
2,
)}
<span className="text-sm font-normal text-muted-foreground">
{" "}
/mo
</span>
</p>
<ul className="flex flex-col gap-1.5 mt-4">
{[
`Setup up to ${STARTUP_SERVERS_INCLUDED} servers`,
"Unlimited users & environments",
"Basic RBAC + 2FA",
"Email & chat support",
].map((f) => (
<li
key={f}
className="flex items-center gap-2 text-sm text-muted-foreground"
Start 7-day free trial
<ArrowRightIcon className="size-4" />
</Button>
<Button
variant="outline"
isLoading={loading === `checkout:${plan.tier}`}
disabled={loading !== null || !productId}
onClick={() => handleCheckout(plan.tier)}
>
<CheckIcon className="size-3.5 shrink-0" />
{f}
</li>
))}
</ul>
</div>
<Button
variant="outline"
isLoading={loadingTier === "startup"}
disabled={loadingTier !== null || !data?.startupProductId}
onClick={() => handleCheckout("startup")}
>
Subscribe
</Button>
</div>
Subscribe now
</Button>
</div>
</div>
);
})}
</div>
</div>
);
@@ -65,7 +65,7 @@ export const ProjectStep = ({ onNext, plainTitle }: Props) => {
</span>
<h1 className={titleClassName}>Create your first project.</h1>
<p className="text-muted-foreground text-lg max-w-md leading-relaxed">
Projects group your apps, databases and environments together.
Projects group your apps, databases, and environments together.
</p>
</div>
@@ -1,6 +1,12 @@
import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema";
import copy from "copy-to-clipboard";
import { CheckCircle2, CopyIcon, Loader2, XCircle } from "lucide-react";
import {
CheckCircle2,
CopyIcon,
InfoIcon,
Loader2,
XCircle,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -200,9 +206,19 @@ export const ServerStep = ({ onNext, plainTitle }: Props) => {
</span>
<h1 className={titleClassName}>Connect a server.</h1>
<p className="text-muted-foreground text-lg max-w-md leading-relaxed">
Dokploy deploys to servers you own — buy one from any VPS provider
Dokploy deploys to servers you own. Buy one from any VPS provider
(Hetzner, DigitalOcean, Hostinger...) and paste its IP below.
</p>
<div className="flex items-start gap-2.5 rounded-lg border p-3 max-w-md">
<InfoIcon className="size-4 text-muted-foreground shrink-0 mt-0.5" />
<div className="flex flex-col gap-0.5">
<span className="text-sm font-medium">Requirements</span>
<span className="text-sm text-muted-foreground">
To ensure a smooth experience with Dokploy, your server should
have at least 1GB of RAM and 30GB of disk space.
</span>
</div>
</div>
</div>
{!createdServerId ? (
@@ -287,7 +303,7 @@ export const ServerStep = ({ onNext, plainTitle }: Props) => {
{isSettingUp ? (
<div className="flex items-center justify-center gap-3 py-4 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin shrink-0" />
Setting up your server — installing Docker and dependencies...
Setting up your server – installing Docker and dependencies…
</div>
) : isValidating && !validation ? (
<div className="flex items-center justify-center gap-2 py-4 text-sm text-muted-foreground">
@@ -311,7 +327,7 @@ export const ServerStep = ({ onNext, plainTitle }: Props) => {
</div>
{!isReady && !isSettingUp && (
<AlertBlock type="info">
Setup usually takes a minute after the server boots — this checks
Setup runs after the server boots and this page checks for it
automatically. You can retry setup, or use "Skip for now" above to
continue and come back to this later.
</AlertBlock>
@@ -39,8 +39,8 @@ export const WelcomeStep = ({ onNext }: Props) => {
Let's get your first app <em className="not-italic">live</em>.
</h1>
<p className="text-muted-foreground text-lg max-w-md leading-relaxed">
A few steps — pick a plan, connect a server, ship something. You'll
have a working URL by the end.
It just takes a few steps: pick a plan, connect a server, ship
something. You'll have a working URL by the end.
</p>
</div>
@@ -105,13 +105,47 @@ export const ShowBilling = () => {
api.stripe.upgradeSubscription.useMutation();
const { mutateAsync: updateInvoiceNotifications } =
api.stripe.updateInvoiceNotifications.useMutation();
const { mutateAsync: startFreeTrial, isPending: isStartingTrial } =
const { mutateAsync: startFreeTrial } =
api.stripe.startFreeTrial.useMutation();
const utils = api.useUtils();
const [trialTier, setTrialTier] = useState<"hobby" | "startup" | null>(null);
const [switchingTrial, setSwitchingTrial] = useState(false);
const handleStartTrial = async () => {
const handleSwitchTrialPlan = async (tier: "hobby" | "startup") => {
const planName = tier === "startup" ? "Startup" : "Hobby";
const switchPlan = async () => {
await upgradeSubscription({
tier,
serverQuantity: tier === "startup" ? STARTUP_SERVERS_INCLUDED : 1,
isAnnual: false,
});
await new Promise((resolve) => setTimeout(resolve, 3000));
await Promise.all([
utils.stripe.getBillingStatus.invalidate(),
utils.stripe.getProducts.invalidate(),
utils.user.get.invalidate(),
utils.server.count.invalidate(),
]);
};
setSwitchingTrial(true);
await toast
.promise(switchPlan(), {
loading: `Switching to ${planName}...`,
success: `Your trial is now on the ${planName} plan`,
error: (error) =>
error instanceof Error ? error.message : "Error switching plan",
})
.unwrap()
.catch(() => undefined);
setSwitchingTrial(false);
};
const handleStartTrial = async (tier: "hobby" | "startup") => {
setTrialTier(tier);
try {
await startFreeTrial();
await startFreeTrial({ tier });
await Promise.all([
utils.stripe.getBillingStatus.invalidate(),
utils.stripe.getProducts.invalidate(),
@@ -122,6 +156,8 @@ export const ShowBilling = () => {
toast.error(
error instanceof Error ? error.message : "Error starting trial",
);
} finally {
setTrialTier(null);
}
};
@@ -170,12 +206,23 @@ export const ShowBilling = () => {
const useNewPricing = data?.hobbyProductId && data?.startupProductId;
const products = data?.products.filter((product) => {
// @ts-ignore
// @ts-expect-error
const interval = product?.default_price?.recurring?.interval;
return isAnnual ? interval === "year" : interval === "month";
});
const isEnterpriseCloud = admin?.user.isEnterpriseCloud ?? false;
const canStartTrial =
!isEnterpriseCloud &&
!!billingStatus &&
!billingStatus.plan &&
!billingStatus.isOnTrial &&
!billingStatus.hasUsedTrial;
/** Checkout would create a second subscription alongside a running trial. */
const canSubscribe =
!isEnterpriseCloud &&
(data?.subscriptions?.length ?? 0) === 0 &&
!billingStatus?.isOnTrial;
const maxServers = admin?.user.serversQuantity ?? 1;
const percentage = ((servers ?? 0) / maxServers) * 100;
const safePercentage = Math.min(percentage, 100);
@@ -296,67 +343,72 @@ export const ShowBilling = () => {
billingStatus.trialEndsAt
? ` · ends ${new Date(billingStatus.trialEndsAt).toLocaleDateString()}`
: ""
}${
billingStatus.hasPaymentMethod
? " · billing starts automatically"
: " · add a card to keep your servers"
}`
: "You're subscribed and billed automatically."}
</span>
</div>
</div>
{billingStatus.isOnTrial &&
admin?.user.stripeCustomerId && (
{admin?.user.stripeCustomerId && (
<div className="flex flex-wrap items-center gap-2">
{billingStatus.isOnTrial &&
useNewPricing &&
billingStatus.plan && (
<Button
size="sm"
variant="outline"
isLoading={switchingTrial}
onClick={() =>
handleSwitchTrialPlan(
billingStatus.plan === "startup"
? "hobby"
: "startup",
)
}
>
{billingStatus.plan === "startup"
? "Switch to Hobby"
: "Switch to Startup"}
</Button>
)}
<Button
size="sm"
variant="outline"
variant={
billingStatus.isOnTrial &&
!billingStatus.hasPaymentMethod
? "default"
: "secondary"
}
onClick={async () => {
const session = await createCustomerPortalSession();
window.open(session.url);
}}
>
Add payment method
{billingStatus.isOnTrial &&
!billingStatus.hasPaymentMethod
? "Add payment method"
: "Manage Subscription"}
</Button>
)}
</div>
)}
{!isEnterpriseCloud &&
billingStatus &&
!billingStatus.plan &&
!billingStatus.isOnTrial &&
!billingStatus.hasUsedTrial && (
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-primary/30 bg-primary/5 p-4 max-w-2xl">
<div className="flex items-center gap-3">
<Clock className="h-5 w-5 text-primary shrink-0" />
<div className="flex flex-col gap-1.5">
<span className="text-sm font-medium">
7-day free trial
</span>
<span className="text-sm text-muted-foreground">
No credit card required — cancel anytime.
</span>
<ul className="flex flex-col gap-1 mt-1">
{[
"Setup 1 server",
"Unlimited apps & databases",
"Community support",
].map((feature) => (
<li
key={feature}
className="flex items-center gap-2 text-sm text-muted-foreground"
>
<CheckIcon className="size-3.5 shrink-0" />
{feature}
</li>
))}
</ul>
</div>
</div>
<Button
size="sm"
isLoading={isStartingTrial}
onClick={handleStartTrial}
>
Start trial
</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" />
<div className="flex flex-col">
<span className="text-sm font-medium">
7-day free trial on any plan
</span>
<span className="text-sm text-muted-foreground">
No credit card required — pick Hobby or Startup below.
</span>
</div>
</div>
)}
{(admin?.user.stripeSubscriptionId || isEnterpriseCloud) && (
<div className="space-y-2 flex flex-col">
<h3 className="text-lg font-medium">Servers Plan</h3>
@@ -933,68 +985,71 @@ export const ShowBilling = () => {
))}
</ul>
<div className="mt-6 flex flex-col gap-3">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
Servers:
</span>
<Button
disabled={hobbyServerQuantity <= 1}
variant="outline"
size="icon"
onClick={() =>
setHobbyServerQuantity((q) => Math.max(1, q - 1))
}
>
<MinusIcon className="h-4 w-4" />
</Button>
<NumberInput
value={hobbyServerQuantity}
onChange={(e) =>
setHobbyServerQuantity(
Math.max(
1,
Number(
(e.target as HTMLInputElement).value,
) || 1,
),
)
}
className="text-center"
/>
<Button
variant="outline"
size="icon"
onClick={() => setHobbyServerQuantity((q) => q + 1)}
>
<PlusIcon className="h-4 w-4" />
</Button>
</div>
<div className="flex flex-col gap-2 w-full">
{admin?.user.stripeCustomerId && (
{canSubscribe && (
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
Servers:
</span>
<Button
variant="secondary"
className="w-full"
onClick={async () => {
const session =
await createCustomerPortalSession();
window.open(session.url);
}}
disabled={hobbyServerQuantity <= 1}
variant="outline"
size="icon"
onClick={() =>
setHobbyServerQuantity((q) =>
Math.max(1, q - 1),
)
}
>
Manage Subscription
<MinusIcon className="h-4 w-4" />
</Button>
<NumberInput
value={hobbyServerQuantity}
onChange={(e) =>
setHobbyServerQuantity(
Math.max(
1,
Number(
(e.target as HTMLInputElement).value,
) || 1,
),
)
}
className="text-center"
/>
<Button
variant="outline"
size="icon"
onClick={() =>
setHobbyServerQuantity((q) => q + 1)
}
>
<PlusIcon className="h-4 w-4" />
</Button>
</div>
)}
<div className="flex flex-col gap-2 w-full">
{canStartTrial && (
<Button
className="w-full"
isLoading={trialTier === "hobby"}
disabled={trialTier !== null}
onClick={() => handleStartTrial("hobby")}
>
Start 7-day free trial
</Button>
)}
{canSubscribe && (
<Button
className="w-full"
variant={canStartTrial ? "outline" : "default"}
onClick={() =>
handleCheckout("hobby", data!.hobbyProductId!)
}
disabled={hobbyServerQuantity < 1}
>
Get Started
</Button>
)}
{!isEnterpriseCloud &&
(data?.subscriptions?.length ?? 0) === 0 && (
<Button
className="w-full"
onClick={() =>
handleCheckout("hobby", data!.hobbyProductId!)
}
disabled={hobbyServerQuantity < 1}
>
Get Started
</Button>
)}
</div>
</div>
</section>
@@ -1067,85 +1122,83 @@ export const ShowBilling = () => {
))}
</ul>
<div className="mt-6 flex flex-col gap-3">
<div className="flex flex-col gap-2">
<span className="text-sm font-medium text-foreground">
Servers (min. {STARTUP_SERVERS_INCLUDED} included)
</span>
<div className="flex items-center gap-2">
<Button
disabled={
startupServerQuantity <=
STARTUP_SERVERS_INCLUDED
}
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() =>
setStartupServerQuantity((q) =>
Math.max(STARTUP_SERVERS_INCLUDED, q - 1),
)
}
>
<MinusIcon className="h-4 w-4" />
</Button>
<NumberInput
value={startupServerQuantity}
onChange={(e) =>
setStartupServerQuantity(
Math.max(
STARTUP_SERVERS_INCLUDED,
Number(
(e.target as HTMLInputElement).value,
) || STARTUP_SERVERS_INCLUDED,
),
)
}
className="h-8 text-center"
/>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() =>
setStartupServerQuantity((q) => q + 1)
}
>
<PlusIcon className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex flex-col gap-2 w-full">
{admin?.user.stripeCustomerId && (
<Button
variant="secondary"
className="w-full"
onClick={async () => {
const session =
await createCustomerPortalSession();
window.open(session.url);
}}
>
Manage Subscription
</Button>
)}
{!isEnterpriseCloud &&
(data?.subscriptions?.length ?? 0) === 0 && (
{canSubscribe && (
<div className="flex flex-col gap-2">
<span className="text-sm font-medium text-foreground">
Servers (min. {STARTUP_SERVERS_INCLUDED} included)
</span>
<div className="flex items-center gap-2">
<Button
className="w-full"
onClick={() =>
handleCheckout(
"startup",
data!.startupProductId!,
)
}
disabled={
startupServerQuantity <
startupServerQuantity <=
STARTUP_SERVERS_INCLUDED
}
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() =>
setStartupServerQuantity((q) =>
Math.max(STARTUP_SERVERS_INCLUDED, q - 1),
)
}
>
Get Started
<MinusIcon className="h-4 w-4" />
</Button>
)}
<NumberInput
value={startupServerQuantity}
onChange={(e) =>
setStartupServerQuantity(
Math.max(
STARTUP_SERVERS_INCLUDED,
Number(
(e.target as HTMLInputElement).value,
) || STARTUP_SERVERS_INCLUDED,
),
)
}
className="h-8 text-center"
/>
<Button
variant="outline"
size="icon"
className="h-8 w-8"
onClick={() =>
setStartupServerQuantity((q) => q + 1)
}
>
<PlusIcon className="h-4 w-4" />
</Button>
</div>
</div>
)}
<div className="flex flex-col gap-2 w-full">
{canStartTrial && (
<Button
className="w-full"
isLoading={trialTier === "startup"}
disabled={trialTier !== null}
onClick={() => handleStartTrial("startup")}
>
Start 7-day free trial
</Button>
)}
{canSubscribe && (
<Button
className="w-full"
variant={canStartTrial ? "outline" : "default"}
onClick={() =>
handleCheckout(
"startup",
data!.startupProductId!,
)
}
disabled={
startupServerQuantity < STARTUP_SERVERS_INCLUDED
}
>
Get Started
</Button>
)}
</div>
</div>
</section>
@@ -1337,31 +1390,17 @@ export const ShowBilling = () => {
</Button>
</div>
<div className="flex flex-col gap-2 mt-4 w-full">
{admin?.user.stripeCustomerId && (
{canSubscribe && (
<Button
variant="secondary"
className="w-full"
onClick={async () => {
const session =
await createCustomerPortalSession();
window.open(session.url);
handleCheckout("legacy", product.id);
}}
disabled={hobbyServerQuantity < 1}
>
Manage Subscription
Subscribe
</Button>
)}
{!isEnterpriseCloud &&
(data?.subscriptions?.length ?? 0) === 0 && (
<Button
className="w-full"
onClick={async () => {
handleCheckout("legacy", product.id);
}}
disabled={hobbyServerQuantity < 1}
>
Subscribe
</Button>
)}
</div>
</div>
</section>
+39 -16
View File
@@ -9,6 +9,7 @@ import {
sendInvoiceEmail,
sendPaymentFailedEmail,
} from "@/server/utils/stripe-notifications";
import { sendTrialExpiringEmail } from "@/server/utils/trial-notifications";
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET!;
@@ -72,6 +73,7 @@ export default async function handler(
"invoice.payment_failed",
"customer.deleted",
"checkout.session.completed",
"customer.subscription.trial_will_end",
];
if (!webhooksAllowed.includes(event.type)) {
@@ -110,6 +112,12 @@ export default async function handler(
await updateServersBasedOnQuantity(admin.id, newServersQuantity);
break;
}
case "customer.subscription.trial_will_end": {
const trialingSubscription = event.data.object as Stripe.Subscription;
await sendTrialExpiringEmail(stripe, trialingSubscription, event.created);
break;
}
case "customer.subscription.created": {
const newSubscription = event.data.object as Stripe.Subscription;
@@ -176,7 +184,10 @@ export default async function handler(
break;
}
if (newSubscription.status === "active") {
if (
newSubscription.status === "active" ||
newSubscription.status === "trialing"
) {
const serversQuantity = getSubscriptionServersQuantity(
newSubscription?.items?.data ?? [],
);
@@ -209,9 +220,12 @@ export default async function handler(
case "invoice.payment_succeeded": {
const newInvoice = event.data.object as Stripe.Invoice;
const subscription = await stripe.subscriptions.retrieve(
newInvoice.subscription as string,
);
const subscriptionId = getInvoiceSubscriptionId(newInvoice);
if (!subscriptionId) {
break;
}
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
if (subscription.status !== "active") {
console.log(
@@ -220,6 +234,14 @@ export default async function handler(
break;
}
const admin = await findUserByStripeCustomerId(
subscription.customer as string,
);
if (!admin) {
return res.status(400).send("Webhook Error: Admin not found");
}
const serversQuantity = getSubscriptionServersQuantity(
subscription?.items?.data ?? [],
);
@@ -233,18 +255,10 @@ export default async function handler(
),
);
const admin = await findUserByStripeCustomerId(
subscription.customer as string,
);
if (!admin) {
return res.status(400).send("Webhook Error: Admin not found");
}
if (admin.isEnterpriseCloud) {
break;
}
const newServersQuantity = admin.serversQuantity;
await updateServersBasedOnQuantity(admin.id, newServersQuantity);
await updateServersBasedOnQuantity(admin.id, serversQuantity);
if (admin.sendInvoiceNotifications) {
await sendInvoiceEmail(newInvoice, admin);
@@ -255,9 +269,12 @@ export default async function handler(
case "invoice.payment_failed": {
const newInvoice = event.data.object as Stripe.Invoice;
const subscription = await stripe.subscriptions.retrieve(
newInvoice.subscription as string,
);
const subscriptionId = getInvoiceSubscriptionId(newInvoice);
if (!subscriptionId) {
break;
}
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
if (subscription.status !== "active") {
const admin = await findUserByStripeCustomerId(
newInvoice.customer as string,
@@ -351,6 +368,12 @@ const findUserByStripeCustomerId = async (stripeCustomerId: string) => {
return userResult;
};
const getInvoiceSubscriptionId = (invoice: Stripe.Invoice): string | null => {
const subscription = invoice.subscription;
if (typeof subscription === "string") return subscription;
return subscription?.id ?? null;
};
const activateServer = async (serverId: string) => {
await db
.update(server)
+81 -65
View File
@@ -12,7 +12,7 @@ import {
getCurrentPlan as getCurrentPlanForOrganization,
getStripeClient,
TRIAL_DURATION_DAYS,
TRIAL_SERVER_LIMIT,
TRIAL_SERVER_LIMITS,
} from "@/server/utils/billing";
import {
type BillingTier,
@@ -45,72 +45,82 @@ export const stripeRouter = createTRPCRouter({
return getBillingStatus(ctx.user.ownerId);
}),
startFreeTrial: adminProcedure.mutation(async ({ ctx }) => {
if (!IS_CLOUD) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "This feature is only available in Dokploy Cloud",
});
}
if (!HOBBY_PRICE_MONTHLY_ID) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Trials are not configured",
});
}
const owner = await findUserById(ctx.user.ownerId);
const billingStatus = await getBillingStatus(owner.id);
if (billingStatus.hasActiveAccess) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You already have an active plan or trial",
});
}
if (billingStatus.hasUsedTrial) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You have already used your free trial",
});
}
const stripe = getStripeClient();
let stripeCustomerId = owner.stripeCustomerId;
if (stripeCustomerId) {
const customer = await stripe.customers.retrieve(stripeCustomerId);
if (customer.deleted) {
stripeCustomerId = null;
startFreeTrial: adminProcedure
.input(z.object({ tier: z.enum(["hobby", "startup"]) }))
.mutation(async ({ ctx, input }) => {
if (!IS_CLOUD) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "This feature is only available in Dokploy Cloud",
});
}
}
if (!stripeCustomerId) {
const customer = await stripe.customers.create({ email: owner.email });
stripeCustomerId = customer.id;
}
const subscription = await stripe.subscriptions.create({
customer: stripeCustomerId,
items: [{ price: HOBBY_PRICE_MONTHLY_ID, quantity: 1 }],
trial_period_days: TRIAL_DURATION_DAYS,
trial_settings: { end_behavior: { missing_payment_method: "cancel" } },
metadata: { source: "onboarding_trial", adminId: owner.id },
});
const trialPriceId =
input.tier === "startup"
? STARTUP_BASE_PRICE_MONTHLY_ID
: HOBBY_PRICE_MONTHLY_ID;
if (!trialPriceId) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Trials are not configured",
});
}
await updateUser(owner.id, {
stripeCustomerId,
stripeSubscriptionId: subscription.id,
serversQuantity: TRIAL_SERVER_LIMIT,
});
const owner = await findUserById(ctx.user.ownerId);
const billingStatus = await getBillingStatus(owner.id);
return {
trialEndsAt: subscription.trial_end
? new Date(subscription.trial_end * 1000)
: null,
};
}),
if (billingStatus.hasActiveAccess) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You already have an active plan or trial",
});
}
if (billingStatus.hasUsedTrial) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "You have already used your free trial",
});
}
const stripe = getStripeClient();
let stripeCustomerId = owner.stripeCustomerId;
if (stripeCustomerId) {
const customer = await stripe.customers.retrieve(stripeCustomerId);
if (customer.deleted) {
stripeCustomerId = null;
}
}
if (!stripeCustomerId) {
const customer = await stripe.customers.create({ email: owner.email });
stripeCustomerId = customer.id;
}
const subscription = await stripe.subscriptions.create({
customer: stripeCustomerId,
items: [{ price: trialPriceId, quantity: 1 }],
trial_period_days: TRIAL_DURATION_DAYS,
trial_settings: { end_behavior: { missing_payment_method: "cancel" } },
metadata: {
source: "onboarding_trial",
adminId: owner.id,
tier: input.tier,
},
});
await updateUser(owner.id, {
stripeCustomerId,
stripeSubscriptionId: subscription.id,
serversQuantity: TRIAL_SERVER_LIMITS[input.tier],
});
return {
trialEndsAt: subscription.trial_end
? new Date(subscription.trial_end * 1000)
: null,
};
}),
getProducts: adminProcedure.query(async ({ ctx }) => {
const user = await findUserById(ctx.user.ownerId);
@@ -343,9 +353,15 @@ export const stripeRouter = createTRPCRouter({
});
}
const isTrialing = subscription.status === "trialing";
// Trials are capped at the plan's included servers; paid plans can scale.
const serverQuantity = isTrialing
? TRIAL_SERVER_LIMITS[input.tier]
: input.serverQuantity;
const newItems = getStripeItems(
input.tier as BillingTier,
input.serverQuantity,
serverQuantity,
input.isAnnual,
);
const currentItems = subscription.items.data;
@@ -371,7 +387,7 @@ export const stripeRouter = createTRPCRouter({
await stripe.subscriptions.update(owner.stripeSubscriptionId, {
items: updateItems,
proration_behavior: "create_prorations",
proration_behavior: isTrialing ? "none" : "create_prorations",
});
return { ok: true };
+17 -3
View File
@@ -16,7 +16,7 @@ export const getStripeClient = () =>
apiVersion: "2024-09-30.acacia",
});
const planFromPriceIds = (priceIds: string[]): BillingPlan | null => {
export const planFromPriceIds = (priceIds: string[]): BillingPlan | null => {
if (
priceIds.some(
(id) =>
@@ -78,7 +78,11 @@ export const getCurrentPlan = async (
};
export const TRIAL_DURATION_DAYS = 7;
export const TRIAL_SERVER_LIMIT = 1;
export type TrialTier = "hobby" | "startup";
export const TRIAL_SERVER_LIMITS: Record<TrialTier, number> = {
hobby: 1,
startup: 3,
};
export interface BillingStatus {
plan: BillingPlan | null;
@@ -87,6 +91,7 @@ export interface BillingStatus {
trialDaysRemaining: number | null;
hasUsedTrial: boolean;
hasActiveAccess: boolean;
hasPaymentMethod: boolean;
}
export const getBillingStatus = async (
@@ -100,6 +105,7 @@ export const getBillingStatus = async (
trialDaysRemaining: null,
hasUsedTrial: false,
hasActiveAccess: true,
hasPaymentMethod: true,
};
}
@@ -112,6 +118,7 @@ export const getBillingStatus = async (
trialDaysRemaining: null,
hasUsedTrial: false,
hasActiveAccess: false,
hasPaymentMethod: false,
};
}
@@ -119,7 +126,7 @@ export const getBillingStatus = async (
const subscriptions = await stripe.subscriptions.list({
customer: owner.stripeCustomerId,
status: "all",
expand: ["data.items.data.price"],
expand: ["data.items.data.price", "data.customer"],
});
const relevantSubs = subscriptions.data.filter(
@@ -133,6 +140,12 @@ export const getBillingStatus = async (
const trialingSub = subscriptions.data.find(
(sub) => sub.status === "trialing",
);
const currentSub = trialingSub ?? relevantSubs[0];
const customer = currentSub?.customer as Stripe.Customer | undefined;
const hasPaymentMethod =
!!currentSub?.default_payment_method ||
!!customer?.invoice_settings?.default_payment_method;
const trialEndsAt = trialingSub?.trial_end
? new Date(trialingSub.trial_end * 1000)
: null;
@@ -148,6 +161,7 @@ export const getBillingStatus = async (
isOnTrial: !!trialingSub,
trialEndsAt,
trialDaysRemaining,
hasPaymentMethod,
hasUsedTrial: subscriptions.data.length > 0,
hasActiveAccess: plan !== null || !!trialingSub,
};
@@ -0,0 +1,78 @@
import { db } from "@dokploy/server/db";
import TrialExpiringEmail from "@dokploy/server/emails/emails/trial-expiring";
import { sendEmail } from "@dokploy/server/verification/send-verification-email";
import { render } from "@react-email/components";
import { format } from "date-fns";
import { eq } from "drizzle-orm";
import type Stripe from "stripe";
import { user } from "@/server/db/schema";
import { planFromPriceIds } from "@/server/utils/billing";
import { WEBSITE_URL } from "@/server/utils/stripe";
const PLAN_LABELS: Record<string, string> = {
hobby: "Hobby",
startup: "Startup",
legacy: "Legacy",
};
const customerIdOf = (subscription: Stripe.Subscription) =>
typeof subscription.customer === "string"
? subscription.customer
: subscription.customer.id;
const hasPaymentMethod = async (
stripe: Stripe,
subscription: Stripe.Subscription,
) => {
if (subscription.default_payment_method) return true;
const customer = await stripe.customers.retrieve(customerIdOf(subscription));
if (customer.deleted) return true;
return !!customer.invoice_settings?.default_payment_method;
};
export const sendTrialExpiringEmail = async (
stripe: Stripe,
subscription: Stripe.Subscription,
// Stripe retries a failing webhook for days, so the countdown is measured
// from when Stripe emitted the event rather than from the current time.
notifiedAtSeconds: number,
) => {
if (!subscription.trial_end) return false;
if (await hasPaymentMethod(stripe, subscription)) return false;
const owner = await db.query.user.findFirst({
where: eq(user.stripeCustomerId, customerIdOf(subscription)),
});
if (!owner || owner.isEnterpriseCloud) return false;
const trialEndsAt = new Date(subscription.trial_end * 1000);
const daysRemaining = Math.max(
1,
Math.ceil((subscription.trial_end - notifiedAtSeconds) / (60 * 60 * 24)),
);
const plan = planFromPriceIds(
subscription.items.data.map((item) => (item.price as Stripe.Price).id),
);
const htmlContent = await render(
TrialExpiringEmail({
userName: owner.firstName || "User",
planName: plan ? (PLAN_LABELS[plan] ?? plan) : "Trial",
daysRemaining,
endsOn: format(trialEndsAt, "MMM dd, yyyy"),
billingUrl: `${WEBSITE_URL}/dashboard/settings/billing`,
}),
);
await sendEmail({
email: owner.email,
subject:
daysRemaining === 1
? "Your Dokploy trial ends tomorrow"
: `Your Dokploy trial ends in ${daysRemaining} days`,
text: htmlContent,
});
return true;
};
@@ -0,0 +1,141 @@
import {
Body,
Button,
Column,
Container,
Head,
Heading,
Hr,
Html,
Img,
Link,
Preview,
Row,
Section,
Tailwind,
Text,
} from "@react-email/components";
import { emailTailwindConfig } from "../tailwind-config";
export type TemplateProps = {
userName: string;
planName: string;
daysRemaining: number;
endsOn: string;
billingUrl: string;
};
export const TrialExpiringEmail = ({
userName = "User",
planName = "Hobby",
daysRemaining = 3,
endsOn = "2024-01-01",
billingUrl = "https://app.dokploy.com/dashboard/settings/billing",
}: TemplateProps) => {
const dayLabel = daysRemaining === 1 ? "day" : "days";
const previewText =
daysRemaining === 1
? "Your Dokploy trial ends tomorrow"
: `Your Dokploy trial ends in ${daysRemaining} ${dayLabel}`;
return (
<Html>
<Head />
<Preview>{previewText}</Preview>
<Tailwind config={emailTailwindConfig}>
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
<Container className="my-[40px] mx-auto max-w-[520px]">
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
<Img
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
width="190"
height="120"
alt="Dokploy"
className="my-0 mx-auto"
/>
</Section>
<Section className="bg-white px-[40px] py-[32px]">
<Heading className="text-[#09090b] text-[22px] font-semibold m-0 mb-[8px]">
{daysRemaining === 1
? "Your trial ends tomorrow"
: `Your trial ends in ${daysRemaining} ${dayLabel}`}
</Heading>
<Text className="text-[#71717a] text-[14px] leading-[22px] m-0 mb-[24px]">
Hello {userName}, add a payment method to keep your servers and
applications running once the trial ends.
</Text>
<Section className="border border-solid border-[#e4e4e7] rounded-lg overflow-hidden mb-[24px]">
<Row className="bg-[#fafafa]">
<Column className="px-[20px] py-[14px] w-[50%]">
<Text className="text-[#71717a] text-[12px] font-medium uppercase tracking-wider m-0">
Plan
</Text>
<Text className="text-[#09090b] text-[14px] font-semibold m-0 mt-[4px]">
{planName}
</Text>
</Column>
<Column className="px-[20px] py-[14px] w-[50%]">
<Text className="text-[#71717a] text-[12px] font-medium uppercase tracking-wider m-0">
Trial ends
</Text>
<Text className="text-[#09090b] text-[14px] font-semibold m-0 mt-[4px]">
{endsOn}
</Text>
</Column>
</Row>
</Section>
<Section className="bg-[#fefce8] border border-solid border-[#fef08a] rounded-lg px-[20px] py-[16px] mb-[24px]">
<Text className="text-[#854d0e] text-[13px] leading-[20px] m-0">
Without a payment method your subscription is cancelled when
the trial ends and your servers are deactivated.
</Text>
</Section>
<Section className="text-center mb-[24px]">
<Button
href={billingUrl}
className="bg-[#09090b] rounded-lg text-white text-[14px] font-semibold no-underline text-center px-[24px] py-[12px]"
>
Add Payment Method
</Button>
</Section>
<Hr className="border-[#e4e4e7] my-[24px]" />
<Text className="text-[#a1a1aa] text-[12px] leading-[18px] m-0">
You are billed only when the trial ends. You can cancel at any
time before then.
</Text>
</Section>
<Section className="bg-[#fafafa] rounded-b-xl px-[40px] py-[24px] text-center border-t border-solid border-[#e4e4e7]">
<Text className="text-[#a1a1aa] text-[12px] leading-[18px] m-0">
This is an automated email from{" "}
<Link
href="https://dokploy.com"
className="text-[#71717a] underline"
>
Dokploy Cloud
</Link>
. If you have any questions about your billing, please contact
our{" "}
<Link
href="https://discord.gg/2tBnJ3jDJc"
className="text-[#71717a] underline"
>
support team
</Link>
.
</Text>
</Section>
</Container>
</Body>
</Tailwind>
</Html>
);
};
export default TrialExpiringEmail;