mirror of
https://github.com/Dokploy/dokploy
synced 2025-06-26 18:27:59 +00:00
feat: add webhook
This commit is contained in:
parent
ffe7b04bea
commit
1907e7e59c
@ -1,16 +1,13 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NumberInput } from "@/components/ui/input";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { api } from "@/utils/api";
|
||||
import { loadStripe } from "@stripe/stripe-js";
|
||||
import clsx from "clsx";
|
||||
import { CheckIcon, MinusIcon, PlusIcon } from "lucide-react";
|
||||
import { useRouter } from "next/router";
|
||||
import { AlertTriangle, CheckIcon, MinusIcon, PlusIcon } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { ReviewPayment } from "./review-payment";
|
||||
|
||||
const stripePromise = loadStripe(
|
||||
"pk_test_51QAm7bF3cxQuHeOz0xg04o9teeyTbbNHQPJ5Tr98MlTEan9MzewT3gwh0jSWBNvrRWZ5vASoBgxUSF4gPWsJwATk00Ir2JZ0S1",
|
||||
@ -18,29 +15,17 @@ const stripePromise = loadStripe(
|
||||
|
||||
export const calculatePrice = (count: number, isAnnual = false) => {
|
||||
if (isAnnual) {
|
||||
if (count === 1) return 40.8;
|
||||
if (count <= 3) return 81.5;
|
||||
return 81.5 + (count - 3) * 35.7;
|
||||
if (count <= 1) return 45.9;
|
||||
return 35.7 * count;
|
||||
}
|
||||
if (count === 1) return 4.0;
|
||||
if (count <= 3) return 7.99;
|
||||
return 7.99 + (count - 3) * 3.5;
|
||||
if (count <= 1) return 4.5;
|
||||
return count * 3.5;
|
||||
};
|
||||
|
||||
export const calculateYearlyCost = (serverQuantity: number) => {
|
||||
const count = serverQuantity;
|
||||
if (count === 1) return 4.0 * 12;
|
||||
if (count <= 3) return 7.99 * 12;
|
||||
return (7.99 + (count - 3) * 3.5) * 12;
|
||||
};
|
||||
|
||||
// 178.156.147.118
|
||||
export const ShowBilling = () => {
|
||||
const router = useRouter();
|
||||
const { data: billingSubscription } =
|
||||
api.stripe.getBillingSubscription.useQuery(undefined);
|
||||
const { data: servers } = api.server.all.useQuery(undefined);
|
||||
const { data: admin } = api.admin.one.useQuery();
|
||||
const { data, refetch } = api.stripe.getProducts.useQuery();
|
||||
const { data } = api.stripe.getProducts.useQuery();
|
||||
const { mutateAsync: createCheckoutSession } =
|
||||
api.stripe.createCheckoutSession.useMutation();
|
||||
|
||||
@ -48,68 +33,11 @@ export const ShowBilling = () => {
|
||||
api.stripe.createCustomerPortalSession.useMutation();
|
||||
|
||||
const [serverQuantity, setServerQuantity] = useState(3);
|
||||
|
||||
const { mutateAsync: upgradeSubscriptionMonthly } =
|
||||
api.stripe.upgradeSubscriptionMonthly.useMutation();
|
||||
|
||||
const { mutateAsync: upgradeSubscriptionAnnual } =
|
||||
api.stripe.upgradeSubscriptionAnnual.useMutation();
|
||||
const [isAnnual, setIsAnnual] = useState(false);
|
||||
|
||||
// useEffect(() => {
|
||||
// if (billingSubscription) {
|
||||
// setIsAnnual(
|
||||
// (prevIsAnnual) =>
|
||||
// billingSubscription.billingInterval === "year" &&
|
||||
// prevIsAnnual !== true,
|
||||
// );
|
||||
// }
|
||||
// }, [billingSubscription]);
|
||||
|
||||
const handleCheckout = async (productId: string) => {
|
||||
const stripe = await stripePromise;
|
||||
|
||||
if (data && admin?.stripeSubscriptionId && data.subscriptions.length > 0) {
|
||||
if (isAnnual) {
|
||||
upgradeSubscriptionAnnual({
|
||||
subscriptionId: admin?.stripeSubscriptionId,
|
||||
serverQuantity,
|
||||
})
|
||||
.then(async (subscription) => {
|
||||
if (subscription.type === "new") {
|
||||
await stripe?.redirectToCheckout({
|
||||
sessionId: subscription.sessionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
toast.success("Subscription upgraded successfully");
|
||||
await refetch();
|
||||
})
|
||||
.catch((error) => {
|
||||
toast.error("Error to upgrade the subscription");
|
||||
console.error(error);
|
||||
});
|
||||
} else {
|
||||
upgradeSubscriptionMonthly({
|
||||
subscriptionId: admin?.stripeSubscriptionId,
|
||||
serverQuantity,
|
||||
})
|
||||
.then(async (subscription) => {
|
||||
if (subscription.type === "new") {
|
||||
await stripe?.redirectToCheckout({
|
||||
sessionId: subscription.sessionId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
toast.success("Subscription upgraded successfully");
|
||||
await refetch();
|
||||
})
|
||||
.catch((error) => {
|
||||
toast.error("Error to upgrade the subscription");
|
||||
console.error(error);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (data && data.subscriptions.length === 0) {
|
||||
createCheckoutSession({
|
||||
productId,
|
||||
serverQuantity: serverQuantity,
|
||||
@ -126,9 +54,12 @@ export const ShowBilling = () => {
|
||||
return isAnnual ? interval === "year" : interval === "month";
|
||||
});
|
||||
|
||||
const maxServers = admin?.serversQuantity ?? 1;
|
||||
const percentage = ((servers?.length ?? 0) / maxServers) * 100;
|
||||
const safePercentage = Math.min(percentage, 100);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 w-full justify-center">
|
||||
<Badge>{admin?.stripeSubscriptionStatus}</Badge>
|
||||
<Tabs
|
||||
defaultValue="monthly"
|
||||
value={isAnnual ? "annual" : "monthly"}
|
||||
@ -140,11 +71,33 @@ export const ShowBilling = () => {
|
||||
<TabsTrigger value="annual">Annual</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
{products?.map((product) => {
|
||||
// const suscripcion = data?.subscriptions.find((subscription) =>
|
||||
// subscription.items.data.find((item) => item.pr === product.id),
|
||||
// );
|
||||
{admin?.stripeSubscriptionId && (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-medium">Servers Plan</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You have {servers?.length} server on your plan of{" "}
|
||||
{admin?.serversQuantity} servers
|
||||
</p>
|
||||
<div className="pb-5">
|
||||
<Progress value={safePercentage} className="max-w-lg" />
|
||||
</div>
|
||||
{admin && (
|
||||
<>
|
||||
{admin.serversQuantity! <= servers?.length! && (
|
||||
<div className="flex flex-row gap-4 p-2 bg-yellow-50 dark:bg-yellow-950 rounded-lg items-center">
|
||||
<AlertTriangle className="text-yellow-600 dark:text-yellow-400" />
|
||||
<span className="text-sm text-yellow-600 dark:text-yellow-400">
|
||||
You have reached the maximum number of servers you can
|
||||
create, please upgrade your plan to add more servers.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{products?.map((product) => {
|
||||
const featured = true;
|
||||
return (
|
||||
<div key={product.id}>
|
||||
@ -221,10 +174,6 @@ export const ShowBilling = () => {
|
||||
onClick={() => {
|
||||
if (serverQuantity <= 1) return;
|
||||
|
||||
if (serverQuantity === 3) {
|
||||
setServerQuantity(serverQuantity - 2);
|
||||
return;
|
||||
}
|
||||
setServerQuantity(serverQuantity - 1);
|
||||
}}
|
||||
>
|
||||
@ -233,10 +182,6 @@ export const ShowBilling = () => {
|
||||
<NumberInput
|
||||
value={serverQuantity}
|
||||
onChange={(e) => {
|
||||
if (Number(e.target.value) === 2) {
|
||||
setServerQuantity(3);
|
||||
return;
|
||||
}
|
||||
setServerQuantity(e.target.value);
|
||||
}}
|
||||
/>
|
||||
@ -244,11 +189,6 @@ export const ShowBilling = () => {
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (serverQuantity === 1) {
|
||||
setServerQuantity(3);
|
||||
return;
|
||||
}
|
||||
|
||||
setServerQuantity(serverQuantity + 1);
|
||||
}}
|
||||
>
|
||||
@ -263,58 +203,39 @@ export const ShowBilling = () => {
|
||||
"flex flex-row items-center gap-2 mt-4",
|
||||
)}
|
||||
>
|
||||
{data &&
|
||||
data?.subscriptions?.length > 0 &&
|
||||
billingSubscription?.billingInterval === "year" &&
|
||||
isAnnual && (
|
||||
<ReviewPayment
|
||||
isAnnual={true}
|
||||
serverQuantity={serverQuantity}
|
||||
/>
|
||||
)}
|
||||
{data &&
|
||||
data?.subscriptions?.length > 0 &&
|
||||
billingSubscription?.billingInterval === "month" &&
|
||||
!isAnnual && (
|
||||
<ReviewPayment
|
||||
isAnnual={false}
|
||||
serverQuantity={serverQuantity}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="justify-end w-full">
|
||||
{admin?.stripeCustomerId && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="w-full"
|
||||
onClick={async () => {
|
||||
handleCheckout(product.id);
|
||||
const session = await createCustomerPortalSession();
|
||||
|
||||
window.open(session.url);
|
||||
}}
|
||||
disabled={serverQuantity < 1}
|
||||
>
|
||||
Subscribe
|
||||
Manage Subscription
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data?.subscriptions?.length === 0 && (
|
||||
<div className="justify-end w-full">
|
||||
<Button
|
||||
className="w-full"
|
||||
onClick={async () => {
|
||||
handleCheckout(product.id);
|
||||
}}
|
||||
disabled={serverQuantity < 1}
|
||||
>
|
||||
Subscribe
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={async () => {
|
||||
// Crear una sesión del portal del cliente
|
||||
const session = await createCustomerPortalSession();
|
||||
|
||||
// router.push(session.url,"",{});
|
||||
window.open(session.url);
|
||||
|
||||
// Redirigir al portal del cliente en Stripe
|
||||
// window.location.href = session.url;
|
||||
}}
|
||||
>
|
||||
Manage Subscription
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@ -31,6 +31,7 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { api } from "@/utils/api";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
@ -57,6 +58,9 @@ type Schema = z.infer<typeof Schema>;
|
||||
export const AddServer = () => {
|
||||
const utils = api.useUtils();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const { data: canCreateMoreServers, refetch } =
|
||||
api.stripe.canCreateMoreServers.useQuery();
|
||||
|
||||
const { data: sshKeys } = api.sshKey.all.useQuery();
|
||||
const { mutateAsync, error, isError } = api.server.create.useMutation();
|
||||
const form = useForm<Schema>({
|
||||
@ -82,6 +86,10 @@ export const AddServer = () => {
|
||||
});
|
||||
}, [form, form.reset, form.formState.isSubmitSuccessful]);
|
||||
|
||||
useEffect(() => {
|
||||
refetch();
|
||||
}, [isOpen]);
|
||||
|
||||
const onSubmit = async (data: Schema) => {
|
||||
await mutateAsync({
|
||||
name: data.name,
|
||||
@ -116,6 +124,14 @@ export const AddServer = () => {
|
||||
Add a server to deploy your applications remotely.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{!canCreateMoreServers && (
|
||||
<AlertBlock type="warning">
|
||||
You cannot create more servers,{" "}
|
||||
<Link href="/dashboard/settings/billing" className="text-primary">
|
||||
Please upgrade your plan
|
||||
</Link>
|
||||
</AlertBlock>
|
||||
)}
|
||||
{isError && <AlertBlock type="error">{error?.message}</AlertBlock>}
|
||||
<Form {...form}>
|
||||
<form
|
||||
@ -254,6 +270,7 @@ export const AddServer = () => {
|
||||
<DialogFooter>
|
||||
<Button
|
||||
isLoading={form.formState.isSubmitting}
|
||||
disabled={!canCreateMoreServers}
|
||||
form="hook-form-add-server"
|
||||
type="submit"
|
||||
>
|
||||
|
@ -36,6 +36,9 @@ export const ShowServers = () => {
|
||||
const { data, refetch } = api.server.all.useQuery();
|
||||
const { mutateAsync } = api.server.remove.useMutation();
|
||||
const { data: sshKeys } = api.sshKey.all.useQuery();
|
||||
const { data: isCloud } = api.settings.isCloud.useQuery();
|
||||
const { data: canCreateMoreServers } =
|
||||
api.stripe.canCreateMoreServers.useQuery();
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@ -74,8 +77,22 @@ export const ShowServers = () => {
|
||||
<div className="flex flex-col items-center gap-3 min-h-[25vh] justify-center">
|
||||
<ServerIcon className="size-8" />
|
||||
<span className="text-base text-muted-foreground">
|
||||
No Servers found. Add a server to deploy your applications
|
||||
remotely.
|
||||
{!canCreateMoreServers ? (
|
||||
<div>
|
||||
You cannot create more servers,{" "}
|
||||
<Link
|
||||
href="/dashboard/settings/billing"
|
||||
className="text-primary"
|
||||
>
|
||||
Please upgrade your plan
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<span>
|
||||
No Servers found. Add a server to deploy your applications
|
||||
remotely.
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
@ -87,6 +104,9 @@ export const ShowServers = () => {
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[100px]">Name</TableHead>
|
||||
{isCloud && (
|
||||
<TableHead className="text-center">Status</TableHead>
|
||||
)}
|
||||
<TableHead className="text-center">IP Address</TableHead>
|
||||
<TableHead className="text-center">Port</TableHead>
|
||||
<TableHead className="text-center">Username</TableHead>
|
||||
@ -101,6 +121,19 @@ export const ShowServers = () => {
|
||||
return (
|
||||
<TableRow key={server.serverId}>
|
||||
<TableCell className="w-[100px]">{server.name}</TableCell>
|
||||
{isCloud && (
|
||||
<TableHead className="text-center">
|
||||
<Badge
|
||||
variant={
|
||||
server.serverStatus === "active"
|
||||
? "default"
|
||||
: "secondary"
|
||||
}
|
||||
>
|
||||
{server.serverStatus}
|
||||
</Badge>
|
||||
</TableHead>
|
||||
)}
|
||||
<TableCell className="text-center">
|
||||
<Badge>{server.ipAddress}</Badge>
|
||||
</TableCell>
|
||||
|
9
apps/dokploy/drizzle/0043_legal_power_pack.sql
Normal file
9
apps/dokploy/drizzle/0043_legal_power_pack.sql
Normal file
@ -0,0 +1,9 @@
|
||||
DO $$ BEGIN
|
||||
CREATE TYPE "public"."serverStatus" AS ENUM('active', 'inactive');
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "admin" RENAME COLUMN "totalServers" TO "serversQuantity";--> statement-breakpoint
|
||||
ALTER TABLE "server" ADD COLUMN "serverStatus" "serverStatus" DEFAULT 'active' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "admin" DROP COLUMN IF EXISTS "stripeSubscriptionStatus";
|
3944
apps/dokploy/drizzle/meta/0043_snapshot.json
Normal file
3944
apps/dokploy/drizzle/meta/0043_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -302,6 +302,13 @@
|
||||
"when": 1729455812207,
|
||||
"tag": "0042_smooth_swordsman",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 43,
|
||||
"version": "6",
|
||||
"when": 1729472842572,
|
||||
"tag": "0043_legal_power_pack",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
@ -1,20 +1,21 @@
|
||||
import { db } from "@/server/db";
|
||||
import { admins, github } from "@/server/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { buffer } from "node:stream/consumers";
|
||||
import { db } from "@/server/db";
|
||||
import { admins, server } from "@/server/db/schema";
|
||||
import { findAdminById } from "@dokploy/server";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import Stripe from "stripe";
|
||||
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
maxNetworkRetries: 3,
|
||||
});
|
||||
|
||||
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET || "";
|
||||
|
||||
export const config = {
|
||||
api: {
|
||||
bodyParser: false, // Deshabilitar el body parser de Next.js
|
||||
bodyParser: false,
|
||||
},
|
||||
};
|
||||
|
||||
@ -22,108 +23,334 @@ export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
) {
|
||||
const buf = await buffer(req); // Leer el raw body como un Buffer
|
||||
if (!endpointSecret) {
|
||||
return res.status(400).send("Webhook Error: Missing Stripe Secret Key");
|
||||
}
|
||||
const buf = await buffer(req);
|
||||
const sig = req.headers["stripe-signature"] as string;
|
||||
|
||||
let event: Stripe.Event;
|
||||
|
||||
try {
|
||||
// Verificar el evento usando el raw body (buf)
|
||||
event = stripe.webhooks.constructEvent(buf, sig, endpointSecret);
|
||||
const newSubscription = event.data.object as Stripe.Subscription;
|
||||
console.log(event.type);
|
||||
switch (event.type) {
|
||||
case "customer.subscription.created":
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionId: newSubscription.id,
|
||||
stripeSubscriptionStatus: newSubscription.status,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
|
||||
break;
|
||||
|
||||
case "customer.subscription.deleted":
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionStatus: "canceled",
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
break;
|
||||
case "customer.subscription.updated":
|
||||
console.log(newSubscription.status);
|
||||
// Suscripción actualizada (upgrade, downgrade, cambios)
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionStatus: newSubscription.status,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
break;
|
||||
case "invoice.payment_succeeded":
|
||||
console.log(newSubscription.customer);
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionStatus: "active",
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
break;
|
||||
case "invoice.payment_failed":
|
||||
// Pago fallido
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionStatus: "payment_failed",
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
console.log(`Unhandled event type: ${event.type}`);
|
||||
}
|
||||
|
||||
res.status(200).json({ received: true });
|
||||
} catch (err) {
|
||||
console.error("Webhook signature verification failed.", err.message);
|
||||
return res.status(400).send("Webhook Error: ");
|
||||
}
|
||||
|
||||
const webhooksAllowed = [
|
||||
"customer.subscription.created",
|
||||
"customer.subscription.deleted",
|
||||
"customer.subscription.updated",
|
||||
"invoice.payment_succeeded",
|
||||
"invoice.payment_failed",
|
||||
"customer.deleted",
|
||||
"checkout.session.completed",
|
||||
];
|
||||
|
||||
if (!webhooksAllowed.includes(event.type)) {
|
||||
return res.status(400).send("Webhook Error: Invalid Event Type");
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed": {
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
const adminId = session?.metadata?.adminId as string;
|
||||
|
||||
const subscription = await stripe.subscriptions.retrieve(
|
||||
session.subscription as string,
|
||||
);
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeCustomerId: session.customer as string,
|
||||
stripeSubscriptionId: session.subscription as string,
|
||||
serversQuantity: subscription?.items?.data?.[0]?.quantity ?? 0,
|
||||
})
|
||||
.where(eq(admins.adminId, adminId))
|
||||
.returning();
|
||||
|
||||
const admin = await findAdminById(adminId);
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
const newServersQuantity = admin.serversQuantity;
|
||||
const servers = await findServersByAdminIdSorted(admin.adminId);
|
||||
|
||||
if (servers.length > newServersQuantity) {
|
||||
for (const [index, server] of servers.entries()) {
|
||||
if (index < newServersQuantity) {
|
||||
await activateServer(server.serverId);
|
||||
} else {
|
||||
await deactivateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const server of servers) {
|
||||
await activateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "customer.subscription.created": {
|
||||
const newSubscription = event.data.object as Stripe.Subscription;
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionId: newSubscription.id,
|
||||
serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0,
|
||||
stripeCustomerId: newSubscription.customer as string,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
|
||||
const newServersQuantity = admin.serversQuantity;
|
||||
const servers = await findServersByAdminIdSorted(admin.adminId);
|
||||
|
||||
// 4 > 3
|
||||
if (servers.length > newServersQuantity) {
|
||||
for (const [index, server] of servers.entries()) {
|
||||
// 0 < 3 = true
|
||||
// 1 < 3 = true
|
||||
// 2 < 3 = true
|
||||
// 3 < 3 = false
|
||||
if (index < newServersQuantity) {
|
||||
await activateServer(server.serverId);
|
||||
} else {
|
||||
await deactivateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const server of servers) {
|
||||
await activateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.subscription.deleted": {
|
||||
const newSubscription = event.data.object as Stripe.Subscription;
|
||||
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeSubscriptionId: null,
|
||||
serversQuantity: 0,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
|
||||
await disableServers(admin.adminId);
|
||||
break;
|
||||
}
|
||||
case "customer.subscription.updated": {
|
||||
const newSubscription = event.data.object as Stripe.Subscription;
|
||||
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
),
|
||||
);
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(
|
||||
typeof newSubscription.customer === "string"
|
||||
? newSubscription.customer
|
||||
: "",
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
|
||||
const newServersQuantity = admin.serversQuantity;
|
||||
const servers = await findServersByAdminIdSorted(admin.adminId);
|
||||
|
||||
if (servers.length > newServersQuantity) {
|
||||
for (const [index, server] of servers.entries()) {
|
||||
if (index < newServersQuantity) {
|
||||
await activateServer(server.serverId);
|
||||
} else {
|
||||
await deactivateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const server of servers) {
|
||||
await activateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case "invoice.payment_succeeded": {
|
||||
const newInvoice = event.data.object as Stripe.Invoice;
|
||||
|
||||
const suscription = await stripe.subscriptions.retrieve(
|
||||
newInvoice.subscription as string,
|
||||
);
|
||||
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
serversQuantity: suscription?.items?.data?.[0]?.quantity ?? 0,
|
||||
})
|
||||
.where(eq(admins.stripeCustomerId, suscription.customer as string));
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(
|
||||
suscription.customer as string,
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
const newServersQuantity = admin.serversQuantity;
|
||||
const servers = await findServersByAdminIdSorted(admin.adminId);
|
||||
if (servers.length > newServersQuantity) {
|
||||
for (const [index, server] of servers.entries()) {
|
||||
if (index < newServersQuantity) {
|
||||
await activateServer(server.serverId);
|
||||
} else {
|
||||
await deactivateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const server of servers) {
|
||||
await activateServer(server.serverId);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case "invoice.payment_failed": {
|
||||
const newInvoice = event.data.object as Stripe.Invoice;
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
serversQuantity: 0,
|
||||
})
|
||||
.where(
|
||||
eq(
|
||||
admins.stripeCustomerId,
|
||||
typeof newInvoice.customer === "string" ? newInvoice.customer : "",
|
||||
),
|
||||
);
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(
|
||||
typeof newInvoice.customer === "string" ? newInvoice.customer : "",
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
|
||||
await disableServers(admin.adminId);
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.deleted": {
|
||||
const customer = event.data.object as Stripe.Customer;
|
||||
|
||||
const admin = await findAdminByStripeCustomerId(customer.id);
|
||||
if (!admin) {
|
||||
return res.status(400).send("Webhook Error: Admin not found");
|
||||
}
|
||||
|
||||
await disableServers(admin.adminId);
|
||||
await db
|
||||
.update(admins)
|
||||
.set({
|
||||
stripeCustomerId: null,
|
||||
stripeSubscriptionId: null,
|
||||
serversQuantity: 0,
|
||||
})
|
||||
.where(eq(admins.stripeCustomerId, customer.id));
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
console.log(`Unhandled event type: ${event.type}`);
|
||||
}
|
||||
|
||||
return res.status(200).json({ received: true });
|
||||
}
|
||||
|
||||
const disableServers = async (adminId: string) => {
|
||||
await db
|
||||
.update(server)
|
||||
.set({
|
||||
serverStatus: "inactive",
|
||||
})
|
||||
.where(eq(server.adminId, adminId));
|
||||
};
|
||||
|
||||
const findAdminByStripeCustomerId = async (stripeCustomerId: string) => {
|
||||
const admin = db.query.admins.findFirst({
|
||||
where: eq(admins.stripeCustomerId, stripeCustomerId),
|
||||
});
|
||||
return admin;
|
||||
};
|
||||
|
||||
const activateServer = async (serverId: string) => {
|
||||
await db
|
||||
.update(server)
|
||||
.set({ serverStatus: "active" })
|
||||
.where(eq(server.serverId, serverId));
|
||||
};
|
||||
|
||||
const deactivateServer = async (serverId: string) => {
|
||||
await db
|
||||
.update(server)
|
||||
.set({ serverStatus: "inactive" })
|
||||
.where(eq(server.serverId, serverId));
|
||||
};
|
||||
|
||||
export const findServersByAdminIdSorted = async (adminId: string) => {
|
||||
const servers = await db.query.server.findMany({
|
||||
where: eq(server.adminId, adminId),
|
||||
orderBy: asc(server.createdAt),
|
||||
});
|
||||
|
||||
return servers;
|
||||
};
|
||||
|
@ -635,7 +635,7 @@ export const settingsRouter = createTRPCRouter({
|
||||
|
||||
return true;
|
||||
}),
|
||||
isCloud: adminProcedure.query(async () => {
|
||||
isCloud: protectedProcedure.query(async () => {
|
||||
return IS_CLOUD;
|
||||
}),
|
||||
health: publicProcedure.query(async () => {
|
||||
|
@ -1,18 +1,11 @@
|
||||
import { admins } from "@/server/db/schema";
|
||||
import { getStripeItems } from "@/server/utils/stripe";
|
||||
import {
|
||||
ADDITIONAL_PRICE_YEARLY_ID,
|
||||
BASE_PRICE_MONTHLY_ID,
|
||||
BASE_PRICE_YEARLY_ID,
|
||||
GROWTH_PRICE_MONTHLY_ID,
|
||||
GROWTH_PRICE_YEARLY_ID,
|
||||
SERVER_ADDITIONAL_PRICE_MONTHLY_ID,
|
||||
getStripeItems,
|
||||
getStripePrices,
|
||||
getStripeSubscriptionItems,
|
||||
getStripeSubscriptionItemsCalculate,
|
||||
updateBasePlan,
|
||||
} from "@/server/utils/stripe";
|
||||
import { findAdminById } from "@dokploy/server";
|
||||
IS_CLOUD,
|
||||
findAdminById,
|
||||
findServersByAdminId,
|
||||
updateAdmin,
|
||||
} from "@dokploy/server";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import Stripe from "stripe";
|
||||
@ -63,260 +56,30 @@ export const stripeRouter = createTRPCRouter({
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
// await updateAdmin(ctx.user.a, {
|
||||
// stripeCustomerId: null,
|
||||
// stripeSubscriptionId: null,
|
||||
// serversQuantity: 0,
|
||||
// });
|
||||
const items = getStripeItems(input.serverQuantity, input.isAnnual);
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
const stripeCustomerId = admin.stripeCustomerId;
|
||||
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
// payment_method_types: ["card"],
|
||||
mode: "subscription",
|
||||
line_items: items,
|
||||
// subscription_data: {
|
||||
// trial_period_days: 0,
|
||||
// },
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
serverQuantity: input.serverQuantity,
|
||||
},
|
||||
...(stripeCustomerId && {
|
||||
customer: stripeCustomerId,
|
||||
}),
|
||||
metadata: {
|
||||
adminId: admin.adminId,
|
||||
},
|
||||
success_url:
|
||||
"http://localhost:3000/api/stripe.success?sessionId={CHECKOUT_SESSION_ID}",
|
||||
success_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
cancel_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
});
|
||||
|
||||
return { sessionId: session.id };
|
||||
}),
|
||||
|
||||
upgradeSubscriptionMonthly: adminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
subscriptionId: z.string(),
|
||||
serverQuantity: z.number().min(1),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
const { subscriptionId, serverQuantity } = input;
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
const suscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const currentItems = suscription.items.data;
|
||||
// If have a monthly plan, we need to create a new subscription
|
||||
const haveMonthlyPlan = currentItems.find(
|
||||
(item) =>
|
||||
item.price.id === BASE_PRICE_YEARLY_ID ||
|
||||
item.price.id === GROWTH_PRICE_YEARLY_ID ||
|
||||
item.price.id === ADDITIONAL_PRICE_YEARLY_ID,
|
||||
);
|
||||
|
||||
if (haveMonthlyPlan) {
|
||||
const items = getStripeItems(serverQuantity, false);
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
line_items: items,
|
||||
mode: "subscription",
|
||||
...(admin.stripeCustomerId && {
|
||||
customer: admin.stripeCustomerId,
|
||||
}),
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
serverQuantity: input.serverQuantity,
|
||||
},
|
||||
},
|
||||
success_url:
|
||||
"http://localhost:3000/api/stripe.success?sessionId={CHECKOUT_SESSION_ID}",
|
||||
cancel_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
});
|
||||
|
||||
return {
|
||||
type: "new",
|
||||
success: true,
|
||||
sessionId: session.id,
|
||||
};
|
||||
}
|
||||
|
||||
const basePriceId = BASE_PRICE_MONTHLY_ID;
|
||||
const growthPriceId = GROWTH_PRICE_MONTHLY_ID;
|
||||
const additionalPriceId = SERVER_ADDITIONAL_PRICE_MONTHLY_ID;
|
||||
|
||||
// Obtener suscripción actual
|
||||
const { baseItem, additionalItem } = await getStripeSubscriptionItems(
|
||||
subscriptionId,
|
||||
false,
|
||||
);
|
||||
|
||||
const deleteAdditionalItem = async () => {
|
||||
if (additionalItem) {
|
||||
await stripe.subscriptionItems.del(additionalItem.id);
|
||||
}
|
||||
};
|
||||
|
||||
const updateOrCreateAdditionalItem = async (
|
||||
additionalServers: number,
|
||||
) => {
|
||||
if (additionalItem) {
|
||||
await stripe.subscriptionItems.update(additionalItem.id, {
|
||||
quantity: additionalServers,
|
||||
});
|
||||
} else {
|
||||
await stripe.subscriptions.update(subscriptionId, {
|
||||
items: [
|
||||
{
|
||||
price: additionalPriceId,
|
||||
quantity: additionalServers,
|
||||
},
|
||||
],
|
||||
proration_behavior: "always_invoice",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (serverQuantity === 1) {
|
||||
await deleteAdditionalItem();
|
||||
if (baseItem?.price.id !== basePriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, basePriceId);
|
||||
}
|
||||
} else if (serverQuantity >= 2 && serverQuantity <= 3) {
|
||||
await deleteAdditionalItem();
|
||||
if (baseItem?.price.id !== growthPriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, growthPriceId);
|
||||
}
|
||||
} else if (serverQuantity > 3) {
|
||||
if (baseItem?.price.id !== growthPriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, growthPriceId);
|
||||
}
|
||||
const additionalServers = serverQuantity - 3;
|
||||
await updateOrCreateAdditionalItem(additionalServers);
|
||||
}
|
||||
|
||||
await stripe.subscriptions.update(subscriptionId, {
|
||||
metadata: {
|
||||
serverQuantity: serverQuantity.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
upgradeSubscriptionAnnual: adminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
subscriptionId: z.string(),
|
||||
serverQuantity: z.number().min(1),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
const { subscriptionId, serverQuantity } = input;
|
||||
|
||||
const currentSubscription =
|
||||
await stripe.subscriptions.retrieve(subscriptionId);
|
||||
|
||||
if (!currentSubscription) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Subscription not found",
|
||||
});
|
||||
}
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
const currentItems = currentSubscription.items.data;
|
||||
// If have a monthly plan, we need to create a new subscription
|
||||
const haveMonthlyPlan = currentItems.find(
|
||||
(item) =>
|
||||
item.price.id === BASE_PRICE_MONTHLY_ID ||
|
||||
item.price.id === GROWTH_PRICE_MONTHLY_ID ||
|
||||
item.price.id === SERVER_ADDITIONAL_PRICE_MONTHLY_ID,
|
||||
);
|
||||
|
||||
if (haveMonthlyPlan) {
|
||||
const items = getStripeItems(serverQuantity, true);
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
line_items: items,
|
||||
mode: "subscription",
|
||||
...(admin.stripeCustomerId && {
|
||||
customer: admin.stripeCustomerId,
|
||||
}),
|
||||
subscription_data: {
|
||||
metadata: {
|
||||
serverQuantity: input.serverQuantity,
|
||||
},
|
||||
},
|
||||
success_url:
|
||||
"http://localhost:3000/api/stripe.success?sessionId={CHECKOUT_SESSION_ID}",
|
||||
cancel_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
});
|
||||
|
||||
return {
|
||||
type: "new",
|
||||
success: true,
|
||||
sessionId: session.id,
|
||||
};
|
||||
}
|
||||
|
||||
const basePriceId = BASE_PRICE_YEARLY_ID;
|
||||
const growthPriceId = GROWTH_PRICE_YEARLY_ID;
|
||||
const additionalPriceId = ADDITIONAL_PRICE_YEARLY_ID;
|
||||
|
||||
// Obtener suscripción actual
|
||||
const { baseItem, additionalItem } = await getStripeSubscriptionItems(
|
||||
subscriptionId,
|
||||
true,
|
||||
);
|
||||
|
||||
const deleteAdditionalItem = async () => {
|
||||
if (additionalItem) {
|
||||
await stripe.subscriptionItems.del(additionalItem.id);
|
||||
}
|
||||
};
|
||||
|
||||
const updateOrCreateAdditionalItem = async (
|
||||
additionalServers: number,
|
||||
) => {
|
||||
if (additionalItem) {
|
||||
await stripe.subscriptionItems.update(additionalItem.id, {
|
||||
quantity: additionalServers,
|
||||
});
|
||||
} else {
|
||||
await stripe.subscriptions.update(subscriptionId, {
|
||||
items: [
|
||||
{
|
||||
price: additionalPriceId,
|
||||
quantity: additionalServers,
|
||||
},
|
||||
],
|
||||
proration_behavior: "always_invoice",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (serverQuantity === 1) {
|
||||
await deleteAdditionalItem();
|
||||
if (baseItem?.price.id !== basePriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, basePriceId);
|
||||
}
|
||||
} else if (serverQuantity >= 2 && serverQuantity <= 3) {
|
||||
await deleteAdditionalItem();
|
||||
if (baseItem?.price.id !== growthPriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, growthPriceId);
|
||||
}
|
||||
} else if (serverQuantity > 3) {
|
||||
if (baseItem?.price.id !== growthPriceId && baseItem?.price.id) {
|
||||
await updateBasePlan(subscriptionId, baseItem?.id, growthPriceId);
|
||||
}
|
||||
const additionalServers = serverQuantity - 3;
|
||||
await updateOrCreateAdditionalItem(additionalServers);
|
||||
}
|
||||
|
||||
await stripe.subscriptions.update(subscriptionId, {
|
||||
metadata: {
|
||||
serverQuantity: serverQuantity.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
createCustomerPortalSession: adminProcedure.mutation(
|
||||
async ({ ctx, input }) => {
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
@ -333,12 +96,18 @@ export const stripeRouter = createTRPCRouter({
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: stripeCustomerId,
|
||||
return_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
});
|
||||
try {
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: stripeCustomerId,
|
||||
return_url: "http://localhost:3000/dashboard/settings/billing",
|
||||
});
|
||||
|
||||
return { url: session.url };
|
||||
return { url: session.url };
|
||||
} catch (error) {
|
||||
return {
|
||||
url: "",
|
||||
};
|
||||
}
|
||||
},
|
||||
),
|
||||
success: adminProcedure.query(async ({ ctx }) => {
|
||||
@ -348,153 +117,56 @@ export const stripeRouter = createTRPCRouter({
|
||||
throw new Error("No session_id provided");
|
||||
}
|
||||
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
// const session = await stripe.checkout.sessions.retrieve(sessionId);
|
||||
|
||||
const session = await stripe.checkout.sessions.retrieve(sessionId);
|
||||
// if (session.payment_status === "paid") {
|
||||
// const admin = await findAdminById(ctx.user.adminId);
|
||||
|
||||
if (session.payment_status === "paid") {
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
// // if (admin.stripeSubscriptionId) {
|
||||
// // const subscription = await stripe.subscriptions.retrieve(
|
||||
// // admin.stripeSubscriptionId,
|
||||
// // );
|
||||
// // if (subscription.status === "active") {
|
||||
// // await stripe.subscriptions.update(admin.stripeSubscriptionId, {
|
||||
// // cancel_at_period_end: true,
|
||||
// // });
|
||||
// // }
|
||||
// // }
|
||||
// console.log("Payment successful!");
|
||||
|
||||
if (admin.stripeSubscriptionId) {
|
||||
const subscription = await stripe.subscriptions.retrieve(
|
||||
admin.stripeSubscriptionId,
|
||||
);
|
||||
if (subscription.status === "active") {
|
||||
await stripe.subscriptions.update(admin.stripeSubscriptionId, {
|
||||
cancel_at_period_end: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
console.log("Payment successful!");
|
||||
// const stripeCustomerId = session.customer as string;
|
||||
// console.log("Stripe Customer ID:", stripeCustomerId);
|
||||
|
||||
const stripeCustomerId = session.customer as string;
|
||||
console.log("Stripe Customer ID:", stripeCustomerId);
|
||||
// const stripeSubscriptionId = session.subscription as string;
|
||||
// const suscription =
|
||||
// await stripe.subscriptions.retrieve(stripeSubscriptionId);
|
||||
// console.log("Stripe Subscription ID:", stripeSubscriptionId);
|
||||
|
||||
const stripeSubscriptionId = session.subscription as string;
|
||||
console.log("Stripe Subscription ID:", stripeSubscriptionId);
|
||||
|
||||
await db
|
||||
?.update(admins)
|
||||
.set({
|
||||
stripeCustomerId,
|
||||
stripeSubscriptionId,
|
||||
})
|
||||
.where(eq(admins.adminId, ctx.user.adminId))
|
||||
.returning();
|
||||
} else {
|
||||
console.log("Payment not completed or failed.");
|
||||
}
|
||||
// await db
|
||||
// ?.update(admins)
|
||||
// .set({
|
||||
// stripeCustomerId,
|
||||
// stripeSubscriptionId,
|
||||
// serversQuantity: suscription?.items?.data?.[0]?.quantity ?? 0,
|
||||
// })
|
||||
// .where(eq(admins.adminId, ctx.user.adminId))
|
||||
// .returning();
|
||||
// } else {
|
||||
// console.log("Payment not completed or failed.");
|
||||
// }
|
||||
|
||||
ctx.res.redirect("/dashboard/settings/billing");
|
||||
|
||||
return true;
|
||||
}),
|
||||
|
||||
getBillingSubscription: adminProcedure.query(async ({ ctx }) => {
|
||||
canCreateMoreServers: adminProcedure.query(async ({ ctx }) => {
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
const servers = await findServersByAdminId(admin.adminId);
|
||||
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
const stripeSubscriptionId = admin.stripeSubscriptionId;
|
||||
const subscription =
|
||||
await stripe.subscriptions.retrieve(stripeSubscriptionId);
|
||||
|
||||
let billingInterval: Stripe.Price.Recurring.Interval | undefined;
|
||||
|
||||
const totalServers = subscription.metadata.serverQuantity;
|
||||
let totalAmount = 0;
|
||||
|
||||
for (const item of subscription.items.data) {
|
||||
const quantity = item.quantity || 1;
|
||||
const amountPerUnit = item.price.unit_amount / 100;
|
||||
|
||||
totalAmount += quantity * amountPerUnit;
|
||||
billingInterval = item.price.recurring?.interval;
|
||||
if (!IS_CLOUD) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
nextPaymentDate: new Date(subscription.current_period_end * 1000),
|
||||
monthlyAmount: totalAmount.toFixed(2),
|
||||
totalServers,
|
||||
billingInterval,
|
||||
};
|
||||
return servers.length < admin.serversQuantity;
|
||||
}),
|
||||
|
||||
calculateUpgradeCost: adminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
serverQuantity: z.number().min(1),
|
||||
isAnnual: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input, ctx }) => {
|
||||
const admin = await findAdminById(ctx.user.adminId);
|
||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||
apiVersion: "2024-09-30.acacia",
|
||||
});
|
||||
|
||||
if (!admin.stripeSubscriptionId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Subscription not found",
|
||||
});
|
||||
}
|
||||
|
||||
const subscriptionId = admin.stripeSubscriptionId;
|
||||
if (!subscriptionId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Subscription not found",
|
||||
});
|
||||
}
|
||||
|
||||
const items = await getStripeSubscriptionItemsCalculate(
|
||||
subscriptionId,
|
||||
input.serverQuantity,
|
||||
input.isAnnual,
|
||||
);
|
||||
|
||||
const upcomingInvoice = await stripe.invoices.retrieveUpcoming({
|
||||
subscription: subscriptionId,
|
||||
subscription_items: items,
|
||||
subscription_proration_behavior: "always_invoice",
|
||||
});
|
||||
|
||||
const totalAmount = upcomingInvoice.total / 100;
|
||||
return totalAmount;
|
||||
}),
|
||||
calculateNewMonthlyCost: adminProcedure
|
||||
.input(
|
||||
z.object({
|
||||
serverQuantity: z.number().min(1),
|
||||
isAnnual: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input, ctx }) => {
|
||||
const serverCount = input.serverQuantity;
|
||||
|
||||
const prices = await getStripePrices(input.isAnnual);
|
||||
let monthlyCost = 0;
|
||||
if (serverCount === 1) {
|
||||
monthlyCost = prices?.basePrice?.unit_amount / 100;
|
||||
} else if (serverCount >= 2 && serverCount <= 3) {
|
||||
monthlyCost = prices?.growthPrice?.unit_amount / 100;
|
||||
} else if (serverCount > 3) {
|
||||
monthlyCost =
|
||||
prices?.growthPrice?.unit_amount / 100 +
|
||||
(serverCount - 3) * (prices?.additionalPrice?.unit_amount / 100);
|
||||
}
|
||||
|
||||
return monthlyCost.toFixed(2);
|
||||
}),
|
||||
});
|
||||
// {
|
||||
// "Parallelism": 1,
|
||||
// "Delay": 10000000000,
|
||||
// "FailureAction": "rollback",
|
||||
// "Order": "start-first"
|
||||
// }
|
||||
|
@ -22,194 +22,17 @@ export const getStripeItems = (serverQuantity: number, isAnnual: boolean) => {
|
||||
const items = [];
|
||||
|
||||
if (isAnnual) {
|
||||
if (serverQuantity === 1) {
|
||||
items.push({
|
||||
price: BASE_PRICE_YEARLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
} else if (serverQuantity <= 3) {
|
||||
items.push({
|
||||
price: GROWTH_PRICE_YEARLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
price: GROWTH_PRICE_YEARLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
items.push({
|
||||
price: ADDITIONAL_PRICE_YEARLY_ID,
|
||||
quantity: serverQuantity - 3,
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
price: "price_1QC7XwF3cxQuHeOz68CpnIUZ",
|
||||
quantity: serverQuantity,
|
||||
});
|
||||
|
||||
return items;
|
||||
}
|
||||
if (serverQuantity === 1) {
|
||||
items.push({
|
||||
price: BASE_PRICE_MONTHLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
} else if (serverQuantity <= 3) {
|
||||
items.push({
|
||||
price: GROWTH_PRICE_MONTHLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
price: GROWTH_PRICE_MONTHLY_ID,
|
||||
quantity: 1,
|
||||
});
|
||||
items.push({
|
||||
price: SERVER_ADDITIONAL_PRICE_MONTHLY_ID,
|
||||
quantity: serverQuantity - 3,
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
price: "price_1QC7X5F3cxQuHeOz1859ljDP",
|
||||
quantity: serverQuantity,
|
||||
});
|
||||
|
||||
return items;
|
||||
};
|
||||
|
||||
export const getStripeSubscriptionItemsCalculate = async (
|
||||
subscriptionId: string,
|
||||
serverQuantity: number,
|
||||
isAnnual: boolean,
|
||||
) => {
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const currentItems = subscription.items.data;
|
||||
const items = [];
|
||||
|
||||
const basePriceId = isAnnual ? BASE_PRICE_YEARLY_ID : BASE_PRICE_MONTHLY_ID;
|
||||
const growthPriceId = isAnnual
|
||||
? GROWTH_PRICE_YEARLY_ID
|
||||
: GROWTH_PRICE_MONTHLY_ID;
|
||||
const additionalPriceId = isAnnual
|
||||
? ADDITIONAL_PRICE_YEARLY_ID
|
||||
: SERVER_ADDITIONAL_PRICE_MONTHLY_ID;
|
||||
|
||||
const baseItem = currentItems.find(
|
||||
(item) => item.price.id === basePriceId || item.price.id === growthPriceId,
|
||||
);
|
||||
const additionalItem = currentItems.find(
|
||||
(item) => item.price.id === additionalPriceId,
|
||||
);
|
||||
|
||||
if (serverQuantity === 1) {
|
||||
if (baseItem) {
|
||||
items.push({
|
||||
id: baseItem.id,
|
||||
price: basePriceId,
|
||||
quantity: 1,
|
||||
});
|
||||
}
|
||||
} else if (serverQuantity <= 3) {
|
||||
if (baseItem) {
|
||||
items.push({
|
||||
id: baseItem.id,
|
||||
price: growthPriceId,
|
||||
quantity: 1,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (baseItem) {
|
||||
items.push({
|
||||
id: baseItem.id,
|
||||
price: growthPriceId,
|
||||
quantity: 1,
|
||||
});
|
||||
}
|
||||
|
||||
if (additionalItem) {
|
||||
items.push({
|
||||
id: additionalItem.id,
|
||||
price: additionalPriceId,
|
||||
quantity: serverQuantity - 3,
|
||||
});
|
||||
} else {
|
||||
items.push({
|
||||
price: additionalPriceId,
|
||||
quantity: serverQuantity - 3,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
};
|
||||
|
||||
export const updateBasePlan = async (
|
||||
subscriptionId: string,
|
||||
subscriptionItemId: string,
|
||||
newPriceId: string,
|
||||
) => {
|
||||
await stripe.subscriptions.update(subscriptionId, {
|
||||
items: [
|
||||
{
|
||||
id: subscriptionItemId,
|
||||
price: newPriceId,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
proration_behavior: "always_invoice",
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteAdditionalItem = async (subscriptionItemId: string) => {
|
||||
await stripe.subscriptionItems.del(subscriptionItemId);
|
||||
};
|
||||
|
||||
export const getStripeSubscriptionItems = async (
|
||||
subscriptionId: string,
|
||||
isAnual: boolean,
|
||||
) => {
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
|
||||
expand: ["items.data.price"],
|
||||
});
|
||||
|
||||
if (isAnual) {
|
||||
const baseItem = subscription.items.data.find(
|
||||
(item) =>
|
||||
item.price.id === BASE_PRICE_YEARLY_ID ||
|
||||
item.price.id === GROWTH_PRICE_YEARLY_ID,
|
||||
);
|
||||
const additionalItem = subscription.items.data.find(
|
||||
(item) => item.price.id === ADDITIONAL_PRICE_YEARLY_ID,
|
||||
);
|
||||
|
||||
return {
|
||||
baseItem,
|
||||
additionalItem,
|
||||
};
|
||||
}
|
||||
const baseItem = subscription.items.data.find(
|
||||
(item) =>
|
||||
item.price.id === BASE_PRICE_MONTHLY_ID ||
|
||||
item.price.id === GROWTH_PRICE_MONTHLY_ID,
|
||||
);
|
||||
const additionalItem = subscription.items.data.find(
|
||||
(item) => item.price.id === SERVER_ADDITIONAL_PRICE_MONTHLY_ID,
|
||||
);
|
||||
|
||||
return {
|
||||
baseItem,
|
||||
additionalItem,
|
||||
};
|
||||
};
|
||||
|
||||
export const getStripePrices = async (isAnual: boolean) => {
|
||||
const basePrice = isAnual
|
||||
? await stripe.prices.retrieve(BASE_PRICE_YEARLY_ID)
|
||||
: await stripe.prices.retrieve(BASE_PRICE_MONTHLY_ID);
|
||||
|
||||
const growthPrice = isAnual
|
||||
? await stripe.prices.retrieve(GROWTH_PRICE_YEARLY_ID)
|
||||
: await stripe.prices.retrieve(GROWTH_PRICE_MONTHLY_ID);
|
||||
|
||||
const additionalPrice = isAnual
|
||||
? await stripe.prices.retrieve(ADDITIONAL_PRICE_YEARLY_ID)
|
||||
: await stripe.prices.retrieve(SERVER_ADDITIONAL_PRICE_MONTHLY_ID);
|
||||
|
||||
return {
|
||||
basePrice,
|
||||
growthPrice,
|
||||
additionalPrice,
|
||||
};
|
||||
};
|
||||
|
@ -30,8 +30,7 @@ export const admins = pgTable("admin", {
|
||||
.$defaultFn(() => new Date().toISOString()),
|
||||
stripeCustomerId: text("stripeCustomerId"),
|
||||
stripeSubscriptionId: text("stripeSubscriptionId"),
|
||||
stripeSubscriptionStatus: text("stripeSubscriptionStatus"),
|
||||
totalServers: integer("totalServers").notNull().default(0),
|
||||
serversQuantity: integer("serversQuantity").notNull().default(0),
|
||||
});
|
||||
|
||||
export const adminsRelations = relations(admins, ({ one, many }) => ({
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { boolean, integer, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { boolean, integer, pgEnum, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { createInsertSchema } from "drizzle-zod";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
@ -17,6 +17,8 @@ import { redis } from "./redis";
|
||||
import { sshKeys } from "./ssh-key";
|
||||
import { generateAppName } from "./utils";
|
||||
|
||||
export const serverStatus = pgEnum("serverStatus", ["active", "inactive"]);
|
||||
|
||||
export const server = pgTable("server", {
|
||||
serverId: text("serverId")
|
||||
.notNull()
|
||||
@ -37,6 +39,8 @@ export const server = pgTable("server", {
|
||||
adminId: text("adminId")
|
||||
.notNull()
|
||||
.references(() => admins.adminId, { onDelete: "cascade" }),
|
||||
serverStatus: serverStatus("serverStatus").notNull().default("active"),
|
||||
|
||||
sshKeyId: text("sshKeyId").references(() => sshKeys.sshKeyId, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
|
@ -13036,7 +13036,7 @@ snapshots:
|
||||
eslint: 8.45.0
|
||||
eslint-import-resolver-node: 0.3.9
|
||||
eslint-import-resolver-typescript: 3.6.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1(eslint@8.45.0))(eslint@8.45.0)
|
||||
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1)(eslint@8.45.0)
|
||||
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1(eslint@8.45.0))(eslint@8.45.0))(eslint@8.45.0)
|
||||
eslint-plugin-jsx-a11y: 6.9.0(eslint@8.45.0)
|
||||
eslint-plugin-react: 7.35.0(eslint@8.45.0)
|
||||
eslint-plugin-react-hooks: 5.0.0-canary-7118f5dd7-20230705(eslint@8.45.0)
|
||||
@ -13060,7 +13060,7 @@ snapshots:
|
||||
enhanced-resolve: 5.17.1
|
||||
eslint: 8.45.0
|
||||
eslint-module-utils: 2.8.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1(eslint@8.45.0))(eslint@8.45.0))(eslint@8.45.0)
|
||||
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1)(eslint@8.45.0)
|
||||
eslint-plugin-import: 2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1(eslint@8.45.0))(eslint@8.45.0))(eslint@8.45.0)
|
||||
fast-glob: 3.3.2
|
||||
get-tsconfig: 4.7.5
|
||||
is-core-module: 2.15.0
|
||||
@ -13082,7 +13082,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-plugin-import@2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1)(eslint@8.45.0):
|
||||
eslint-plugin-import@2.29.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@6.21.0(eslint@8.45.0)(typescript@5.1.6))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1(eslint@8.45.0))(eslint@8.45.0))(eslint@8.45.0):
|
||||
dependencies:
|
||||
array-includes: 3.1.8
|
||||
array.prototype.findlastindex: 1.2.5
|
||||
|
Loading…
Reference in New Issue
Block a user