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 { Button } from "@/components/ui/button";
|
||||||
import { NumberInput } from "@/components/ui/input";
|
import { NumberInput } from "@/components/ui/input";
|
||||||
|
import { Progress } from "@/components/ui/progress";
|
||||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import { loadStripe } from "@stripe/stripe-js";
|
import { loadStripe } from "@stripe/stripe-js";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import { CheckIcon, MinusIcon, PlusIcon } from "lucide-react";
|
import { AlertTriangle, CheckIcon, MinusIcon, PlusIcon } from "lucide-react";
|
||||||
import { useRouter } from "next/router";
|
|
||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { toast } from "sonner";
|
|
||||||
import { ReviewPayment } from "./review-payment";
|
|
||||||
|
|
||||||
const stripePromise = loadStripe(
|
const stripePromise = loadStripe(
|
||||||
"pk_test_51QAm7bF3cxQuHeOz0xg04o9teeyTbbNHQPJ5Tr98MlTEan9MzewT3gwh0jSWBNvrRWZ5vASoBgxUSF4gPWsJwATk00Ir2JZ0S1",
|
"pk_test_51QAm7bF3cxQuHeOz0xg04o9teeyTbbNHQPJ5Tr98MlTEan9MzewT3gwh0jSWBNvrRWZ5vASoBgxUSF4gPWsJwATk00Ir2JZ0S1",
|
||||||
@ -18,29 +15,17 @@ const stripePromise = loadStripe(
|
|||||||
|
|
||||||
export const calculatePrice = (count: number, isAnnual = false) => {
|
export const calculatePrice = (count: number, isAnnual = false) => {
|
||||||
if (isAnnual) {
|
if (isAnnual) {
|
||||||
if (count === 1) return 40.8;
|
if (count <= 1) return 45.9;
|
||||||
if (count <= 3) return 81.5;
|
return 35.7 * count;
|
||||||
return 81.5 + (count - 3) * 35.7;
|
|
||||||
}
|
}
|
||||||
if (count === 1) return 4.0;
|
if (count <= 1) return 4.5;
|
||||||
if (count <= 3) return 7.99;
|
return count * 3.5;
|
||||||
return 7.99 + (count - 3) * 3.5;
|
|
||||||
};
|
};
|
||||||
|
// 178.156.147.118
|
||||||
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;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ShowBilling = () => {
|
export const ShowBilling = () => {
|
||||||
const router = useRouter();
|
|
||||||
const { data: billingSubscription } =
|
|
||||||
api.stripe.getBillingSubscription.useQuery(undefined);
|
|
||||||
const { data: servers } = api.server.all.useQuery(undefined);
|
const { data: servers } = api.server.all.useQuery(undefined);
|
||||||
const { data: admin } = api.admin.one.useQuery();
|
const { data: admin } = api.admin.one.useQuery();
|
||||||
const { data, refetch } = api.stripe.getProducts.useQuery();
|
const { data } = api.stripe.getProducts.useQuery();
|
||||||
const { mutateAsync: createCheckoutSession } =
|
const { mutateAsync: createCheckoutSession } =
|
||||||
api.stripe.createCheckoutSession.useMutation();
|
api.stripe.createCheckoutSession.useMutation();
|
||||||
|
|
||||||
@ -48,68 +33,11 @@ export const ShowBilling = () => {
|
|||||||
api.stripe.createCustomerPortalSession.useMutation();
|
api.stripe.createCustomerPortalSession.useMutation();
|
||||||
|
|
||||||
const [serverQuantity, setServerQuantity] = useState(3);
|
const [serverQuantity, setServerQuantity] = useState(3);
|
||||||
|
|
||||||
const { mutateAsync: upgradeSubscriptionMonthly } =
|
|
||||||
api.stripe.upgradeSubscriptionMonthly.useMutation();
|
|
||||||
|
|
||||||
const { mutateAsync: upgradeSubscriptionAnnual } =
|
|
||||||
api.stripe.upgradeSubscriptionAnnual.useMutation();
|
|
||||||
const [isAnnual, setIsAnnual] = useState(false);
|
const [isAnnual, setIsAnnual] = useState(false);
|
||||||
|
|
||||||
// useEffect(() => {
|
|
||||||
// if (billingSubscription) {
|
|
||||||
// setIsAnnual(
|
|
||||||
// (prevIsAnnual) =>
|
|
||||||
// billingSubscription.billingInterval === "year" &&
|
|
||||||
// prevIsAnnual !== true,
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
// }, [billingSubscription]);
|
|
||||||
|
|
||||||
const handleCheckout = async (productId: string) => {
|
const handleCheckout = async (productId: string) => {
|
||||||
const stripe = await stripePromise;
|
const stripe = await stripePromise;
|
||||||
|
if (data && data.subscriptions.length === 0) {
|
||||||
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 {
|
|
||||||
createCheckoutSession({
|
createCheckoutSession({
|
||||||
productId,
|
productId,
|
||||||
serverQuantity: serverQuantity,
|
serverQuantity: serverQuantity,
|
||||||
@ -126,9 +54,12 @@ export const ShowBilling = () => {
|
|||||||
return isAnnual ? interval === "year" : interval === "month";
|
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 (
|
return (
|
||||||
<div className="flex flex-col gap-4 w-full justify-center">
|
<div className="flex flex-col gap-4 w-full justify-center">
|
||||||
<Badge>{admin?.stripeSubscriptionStatus}</Badge>
|
|
||||||
<Tabs
|
<Tabs
|
||||||
defaultValue="monthly"
|
defaultValue="monthly"
|
||||||
value={isAnnual ? "annual" : "monthly"}
|
value={isAnnual ? "annual" : "monthly"}
|
||||||
@ -140,11 +71,33 @@ export const ShowBilling = () => {
|
|||||||
<TabsTrigger value="annual">Annual</TabsTrigger>
|
<TabsTrigger value="annual">Annual</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
{products?.map((product) => {
|
{admin?.stripeSubscriptionId && (
|
||||||
// const suscripcion = data?.subscriptions.find((subscription) =>
|
<div className="space-y-2">
|
||||||
// subscription.items.data.find((item) => item.pr === product.id),
|
<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;
|
const featured = true;
|
||||||
return (
|
return (
|
||||||
<div key={product.id}>
|
<div key={product.id}>
|
||||||
@ -221,10 +174,6 @@ export const ShowBilling = () => {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (serverQuantity <= 1) return;
|
if (serverQuantity <= 1) return;
|
||||||
|
|
||||||
if (serverQuantity === 3) {
|
|
||||||
setServerQuantity(serverQuantity - 2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setServerQuantity(serverQuantity - 1);
|
setServerQuantity(serverQuantity - 1);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@ -233,10 +182,6 @@ export const ShowBilling = () => {
|
|||||||
<NumberInput
|
<NumberInput
|
||||||
value={serverQuantity}
|
value={serverQuantity}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
if (Number(e.target.value) === 2) {
|
|
||||||
setServerQuantity(3);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setServerQuantity(e.target.value);
|
setServerQuantity(e.target.value);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@ -244,11 +189,6 @@ export const ShowBilling = () => {
|
|||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (serverQuantity === 1) {
|
|
||||||
setServerQuantity(3);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setServerQuantity(serverQuantity + 1);
|
setServerQuantity(serverQuantity + 1);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@ -263,25 +203,21 @@ export const ShowBilling = () => {
|
|||||||
"flex flex-row items-center gap-2 mt-4",
|
"flex flex-row items-center gap-2 mt-4",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{data &&
|
{admin?.stripeCustomerId && (
|
||||||
data?.subscriptions?.length > 0 &&
|
<Button
|
||||||
billingSubscription?.billingInterval === "year" &&
|
variant="secondary"
|
||||||
isAnnual && (
|
className="w-full"
|
||||||
<ReviewPayment
|
onClick={async () => {
|
||||||
isAnnual={true}
|
const session = await createCustomerPortalSession();
|
||||||
serverQuantity={serverQuantity}
|
|
||||||
/>
|
window.open(session.url);
|
||||||
)}
|
}}
|
||||||
{data &&
|
>
|
||||||
data?.subscriptions?.length > 0 &&
|
Manage Subscription
|
||||||
billingSubscription?.billingInterval === "month" &&
|
</Button>
|
||||||
!isAnnual && (
|
|
||||||
<ReviewPayment
|
|
||||||
isAnnual={false}
|
|
||||||
serverQuantity={serverQuantity}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{data?.subscriptions?.length === 0 && (
|
||||||
<div className="justify-end w-full">
|
<div className="justify-end w-full">
|
||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
@ -293,28 +229,13 @@ export const ShowBilling = () => {
|
|||||||
Subscribe
|
Subscribe
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -31,6 +31,7 @@ import { Textarea } from "@/components/ui/textarea";
|
|||||||
import { api } from "@/utils/api";
|
import { api } from "@/utils/api";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { PlusIcon } from "lucide-react";
|
import { PlusIcon } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
import { useRouter } from "next/router";
|
import { useRouter } from "next/router";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
@ -57,6 +58,9 @@ type Schema = z.infer<typeof Schema>;
|
|||||||
export const AddServer = () => {
|
export const AddServer = () => {
|
||||||
const utils = api.useUtils();
|
const utils = api.useUtils();
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const { data: canCreateMoreServers, refetch } =
|
||||||
|
api.stripe.canCreateMoreServers.useQuery();
|
||||||
|
|
||||||
const { data: sshKeys } = api.sshKey.all.useQuery();
|
const { data: sshKeys } = api.sshKey.all.useQuery();
|
||||||
const { mutateAsync, error, isError } = api.server.create.useMutation();
|
const { mutateAsync, error, isError } = api.server.create.useMutation();
|
||||||
const form = useForm<Schema>({
|
const form = useForm<Schema>({
|
||||||
@ -82,6 +86,10 @@ export const AddServer = () => {
|
|||||||
});
|
});
|
||||||
}, [form, form.reset, form.formState.isSubmitSuccessful]);
|
}, [form, form.reset, form.formState.isSubmitSuccessful]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
refetch();
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
const onSubmit = async (data: Schema) => {
|
const onSubmit = async (data: Schema) => {
|
||||||
await mutateAsync({
|
await mutateAsync({
|
||||||
name: data.name,
|
name: data.name,
|
||||||
@ -116,6 +124,14 @@ export const AddServer = () => {
|
|||||||
Add a server to deploy your applications remotely.
|
Add a server to deploy your applications remotely.
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</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>}
|
{isError && <AlertBlock type="error">{error?.message}</AlertBlock>}
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form
|
<form
|
||||||
@ -254,6 +270,7 @@ export const AddServer = () => {
|
|||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
isLoading={form.formState.isSubmitting}
|
isLoading={form.formState.isSubmitting}
|
||||||
|
disabled={!canCreateMoreServers}
|
||||||
form="hook-form-add-server"
|
form="hook-form-add-server"
|
||||||
type="submit"
|
type="submit"
|
||||||
>
|
>
|
||||||
|
@ -36,6 +36,9 @@ export const ShowServers = () => {
|
|||||||
const { data, refetch } = api.server.all.useQuery();
|
const { data, refetch } = api.server.all.useQuery();
|
||||||
const { mutateAsync } = api.server.remove.useMutation();
|
const { mutateAsync } = api.server.remove.useMutation();
|
||||||
const { data: sshKeys } = api.sshKey.all.useQuery();
|
const { data: sshKeys } = api.sshKey.all.useQuery();
|
||||||
|
const { data: isCloud } = api.settings.isCloud.useQuery();
|
||||||
|
const { data: canCreateMoreServers } =
|
||||||
|
api.stripe.canCreateMoreServers.useQuery();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 space-y-6">
|
<div className="p-6 space-y-6">
|
||||||
@ -74,9 +77,23 @@ export const ShowServers = () => {
|
|||||||
<div className="flex flex-col items-center gap-3 min-h-[25vh] justify-center">
|
<div className="flex flex-col items-center gap-3 min-h-[25vh] justify-center">
|
||||||
<ServerIcon className="size-8" />
|
<ServerIcon className="size-8" />
|
||||||
<span className="text-base text-muted-foreground">
|
<span className="text-base text-muted-foreground">
|
||||||
|
{!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
|
No Servers found. Add a server to deploy your applications
|
||||||
remotely.
|
remotely.
|
||||||
</span>
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
@ -87,6 +104,9 @@ export const ShowServers = () => {
|
|||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableHead className="w-[100px]">Name</TableHead>
|
<TableHead className="w-[100px]">Name</TableHead>
|
||||||
|
{isCloud && (
|
||||||
|
<TableHead className="text-center">Status</TableHead>
|
||||||
|
)}
|
||||||
<TableHead className="text-center">IP Address</TableHead>
|
<TableHead className="text-center">IP Address</TableHead>
|
||||||
<TableHead className="text-center">Port</TableHead>
|
<TableHead className="text-center">Port</TableHead>
|
||||||
<TableHead className="text-center">Username</TableHead>
|
<TableHead className="text-center">Username</TableHead>
|
||||||
@ -101,6 +121,19 @@ export const ShowServers = () => {
|
|||||||
return (
|
return (
|
||||||
<TableRow key={server.serverId}>
|
<TableRow key={server.serverId}>
|
||||||
<TableCell className="w-[100px]">{server.name}</TableCell>
|
<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">
|
<TableCell className="text-center">
|
||||||
<Badge>{server.ipAddress}</Badge>
|
<Badge>{server.ipAddress}</Badge>
|
||||||
</TableCell>
|
</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,
|
"when": 1729455812207,
|
||||||
"tag": "0042_smooth_swordsman",
|
"tag": "0042_smooth_swordsman",
|
||||||
"breakpoints": true
|
"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 { 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 type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
|
|
||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||||
apiVersion: "2024-09-30.acacia",
|
apiVersion: "2024-09-30.acacia",
|
||||||
|
maxNetworkRetries: 3,
|
||||||
});
|
});
|
||||||
|
|
||||||
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET || "";
|
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET || "";
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
api: {
|
api: {
|
||||||
bodyParser: false, // Deshabilitar el body parser de Next.js
|
bodyParser: false,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -22,23 +23,83 @@ export default async function handler(
|
|||||||
req: NextApiRequest,
|
req: NextApiRequest,
|
||||||
res: NextApiResponse,
|
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;
|
const sig = req.headers["stripe-signature"] as string;
|
||||||
|
|
||||||
let event: Stripe.Event;
|
let event: Stripe.Event;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Verificar el evento usando el raw body (buf)
|
|
||||||
event = stripe.webhooks.constructEvent(buf, sig, endpointSecret);
|
event = stripe.webhooks.constructEvent(buf, sig, endpointSecret);
|
||||||
const newSubscription = event.data.object as Stripe.Subscription;
|
} catch (err) {
|
||||||
console.log(event.type);
|
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) {
|
switch (event.type) {
|
||||||
case "customer.subscription.created":
|
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
|
await db
|
||||||
.update(admins)
|
.update(admins)
|
||||||
.set({
|
.set({
|
||||||
stripeSubscriptionId: newSubscription.id,
|
stripeSubscriptionId: newSubscription.id,
|
||||||
stripeSubscriptionStatus: newSubscription.status,
|
serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0,
|
||||||
|
stripeCustomerId: newSubscription.customer as string,
|
||||||
})
|
})
|
||||||
.where(
|
.where(
|
||||||
eq(
|
eq(
|
||||||
@ -50,13 +111,49 @@ export default async function handler(
|
|||||||
)
|
)
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
break;
|
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;
|
||||||
|
|
||||||
case "customer.subscription.deleted":
|
|
||||||
await db
|
await db
|
||||||
.update(admins)
|
.update(admins)
|
||||||
.set({
|
.set({
|
||||||
stripeSubscriptionStatus: "canceled",
|
stripeSubscriptionId: null,
|
||||||
|
serversQuantity: 0,
|
||||||
})
|
})
|
||||||
.where(
|
.where(
|
||||||
eq(
|
eq(
|
||||||
@ -66,14 +163,27 @@ export default async function handler(
|
|||||||
: "",
|
: "",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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;
|
break;
|
||||||
case "customer.subscription.updated":
|
}
|
||||||
console.log(newSubscription.status);
|
case "customer.subscription.updated": {
|
||||||
// Suscripción actualizada (upgrade, downgrade, cambios)
|
const newSubscription = event.data.object as Stripe.Subscription;
|
||||||
|
|
||||||
await db
|
await db
|
||||||
.update(admins)
|
.update(admins)
|
||||||
.set({
|
.set({
|
||||||
stripeSubscriptionStatus: newSubscription.status,
|
serversQuantity: newSubscription?.items?.data?.[0]?.quantity ?? 0,
|
||||||
})
|
})
|
||||||
.where(
|
.where(
|
||||||
eq(
|
eq(
|
||||||
@ -83,47 +193,164 @@ export default async function handler(
|
|||||||
: "",
|
: "",
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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;
|
break;
|
||||||
case "invoice.payment_succeeded":
|
}
|
||||||
console.log(newSubscription.customer);
|
case "invoice.payment_succeeded": {
|
||||||
|
const newInvoice = event.data.object as Stripe.Invoice;
|
||||||
|
|
||||||
|
const suscription = await stripe.subscriptions.retrieve(
|
||||||
|
newInvoice.subscription as string,
|
||||||
|
);
|
||||||
|
|
||||||
await db
|
await db
|
||||||
.update(admins)
|
.update(admins)
|
||||||
.set({
|
.set({
|
||||||
stripeSubscriptionStatus: "active",
|
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(
|
.where(
|
||||||
eq(
|
eq(
|
||||||
admins.stripeCustomerId,
|
admins.stripeCustomerId,
|
||||||
typeof newSubscription.customer === "string"
|
typeof newInvoice.customer === "string" ? newInvoice.customer : "",
|
||||||
? newSubscription.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;
|
break;
|
||||||
case "invoice.payment_failed":
|
}
|
||||||
// Pago fallido
|
|
||||||
|
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
|
await db
|
||||||
.update(admins)
|
.update(admins)
|
||||||
.set({
|
.set({
|
||||||
stripeSubscriptionStatus: "payment_failed",
|
stripeCustomerId: null,
|
||||||
|
stripeSubscriptionId: null,
|
||||||
|
serversQuantity: 0,
|
||||||
})
|
})
|
||||||
.where(
|
.where(eq(admins.stripeCustomerId, customer.id));
|
||||||
eq(
|
|
||||||
admins.stripeCustomerId,
|
|
||||||
typeof newSubscription.customer === "string"
|
|
||||||
? newSubscription.customer
|
|
||||||
: "",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
console.log(`Unhandled event type: ${event.type}`);
|
console.log(`Unhandled event type: ${event.type}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json({ received: true });
|
return res.status(200).json({ received: true });
|
||||||
} catch (err) {
|
|
||||||
console.error("Webhook signature verification failed.", err.message);
|
|
||||||
return res.status(400).send("Webhook Error: ");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
return true;
|
||||||
}),
|
}),
|
||||||
isCloud: adminProcedure.query(async () => {
|
isCloud: protectedProcedure.query(async () => {
|
||||||
return IS_CLOUD;
|
return IS_CLOUD;
|
||||||
}),
|
}),
|
||||||
health: publicProcedure.query(async () => {
|
health: publicProcedure.query(async () => {
|
||||||
|
@ -1,18 +1,11 @@
|
|||||||
import { admins } from "@/server/db/schema";
|
import { admins } from "@/server/db/schema";
|
||||||
|
import { getStripeItems } from "@/server/utils/stripe";
|
||||||
import {
|
import {
|
||||||
ADDITIONAL_PRICE_YEARLY_ID,
|
IS_CLOUD,
|
||||||
BASE_PRICE_MONTHLY_ID,
|
findAdminById,
|
||||||
BASE_PRICE_YEARLY_ID,
|
findServersByAdminId,
|
||||||
GROWTH_PRICE_MONTHLY_ID,
|
updateAdmin,
|
||||||
GROWTH_PRICE_YEARLY_ID,
|
} from "@dokploy/server";
|
||||||
SERVER_ADDITIONAL_PRICE_MONTHLY_ID,
|
|
||||||
getStripeItems,
|
|
||||||
getStripePrices,
|
|
||||||
getStripeSubscriptionItems,
|
|
||||||
getStripeSubscriptionItemsCalculate,
|
|
||||||
updateBasePlan,
|
|
||||||
} from "@/server/utils/stripe";
|
|
||||||
import { findAdminById } from "@dokploy/server";
|
|
||||||
import { TRPCError } from "@trpc/server";
|
import { TRPCError } from "@trpc/server";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
@ -63,260 +56,30 @@ export const stripeRouter = createTRPCRouter({
|
|||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
||||||
apiVersion: "2024-09-30.acacia",
|
apiVersion: "2024-09-30.acacia",
|
||||||
});
|
});
|
||||||
|
// await updateAdmin(ctx.user.a, {
|
||||||
|
// stripeCustomerId: null,
|
||||||
|
// stripeSubscriptionId: null,
|
||||||
|
// serversQuantity: 0,
|
||||||
|
// });
|
||||||
const items = getStripeItems(input.serverQuantity, input.isAnnual);
|
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({
|
const session = await stripe.checkout.sessions.create({
|
||||||
// payment_method_types: ["card"],
|
|
||||||
mode: "subscription",
|
mode: "subscription",
|
||||||
line_items: items,
|
line_items: items,
|
||||||
// subscription_data: {
|
...(stripeCustomerId && {
|
||||||
// trial_period_days: 0,
|
customer: stripeCustomerId,
|
||||||
// },
|
}),
|
||||||
subscription_data: {
|
|
||||||
metadata: {
|
metadata: {
|
||||||
serverQuantity: input.serverQuantity,
|
adminId: admin.adminId,
|
||||||
},
|
},
|
||||||
},
|
success_url: "http://localhost:3000/dashboard/settings/billing",
|
||||||
success_url:
|
|
||||||
"http://localhost:3000/api/stripe.success?sessionId={CHECKOUT_SESSION_ID}",
|
|
||||||
cancel_url: "http://localhost:3000/dashboard/settings/billing",
|
cancel_url: "http://localhost:3000/dashboard/settings/billing",
|
||||||
});
|
});
|
||||||
|
|
||||||
return { sessionId: session.id };
|
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(
|
createCustomerPortalSession: adminProcedure.mutation(
|
||||||
async ({ ctx, input }) => {
|
async ({ ctx, input }) => {
|
||||||
const admin = await findAdminById(ctx.user.adminId);
|
const admin = await findAdminById(ctx.user.adminId);
|
||||||
@ -333,12 +96,18 @@ export const stripeRouter = createTRPCRouter({
|
|||||||
apiVersion: "2024-09-30.acacia",
|
apiVersion: "2024-09-30.acacia",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
const session = await stripe.billingPortal.sessions.create({
|
const session = await stripe.billingPortal.sessions.create({
|
||||||
customer: stripeCustomerId,
|
customer: stripeCustomerId,
|
||||||
return_url: "http://localhost:3000/dashboard/settings/billing",
|
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 }) => {
|
success: adminProcedure.query(async ({ ctx }) => {
|
||||||
@ -348,153 +117,56 @@ export const stripeRouter = createTRPCRouter({
|
|||||||
throw new Error("No session_id provided");
|
throw new Error("No session_id provided");
|
||||||
}
|
}
|
||||||
|
|
||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
// const session = await stripe.checkout.sessions.retrieve(sessionId);
|
||||||
apiVersion: "2024-09-30.acacia",
|
|
||||||
});
|
|
||||||
|
|
||||||
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") {
|
// // if (admin.stripeSubscriptionId) {
|
||||||
const admin = await findAdminById(ctx.user.adminId);
|
// // 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 stripeCustomerId = session.customer as string;
|
||||||
const subscription = await stripe.subscriptions.retrieve(
|
// console.log("Stripe Customer ID:", stripeCustomerId);
|
||||||
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;
|
// const stripeSubscriptionId = session.subscription as string;
|
||||||
console.log("Stripe Customer ID:", stripeCustomerId);
|
// const suscription =
|
||||||
|
// await stripe.subscriptions.retrieve(stripeSubscriptionId);
|
||||||
|
// console.log("Stripe Subscription ID:", stripeSubscriptionId);
|
||||||
|
|
||||||
const stripeSubscriptionId = session.subscription as string;
|
// await db
|
||||||
console.log("Stripe Subscription ID:", stripeSubscriptionId);
|
// ?.update(admins)
|
||||||
|
// .set({
|
||||||
await db
|
// stripeCustomerId,
|
||||||
?.update(admins)
|
// stripeSubscriptionId,
|
||||||
.set({
|
// serversQuantity: suscription?.items?.data?.[0]?.quantity ?? 0,
|
||||||
stripeCustomerId,
|
// })
|
||||||
stripeSubscriptionId,
|
// .where(eq(admins.adminId, ctx.user.adminId))
|
||||||
})
|
// .returning();
|
||||||
.where(eq(admins.adminId, ctx.user.adminId))
|
// } else {
|
||||||
.returning();
|
// console.log("Payment not completed or failed.");
|
||||||
} else {
|
// }
|
||||||
console.log("Payment not completed or failed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.res.redirect("/dashboard/settings/billing");
|
ctx.res.redirect("/dashboard/settings/billing");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}),
|
}),
|
||||||
|
canCreateMoreServers: adminProcedure.query(async ({ ctx }) => {
|
||||||
getBillingSubscription: adminProcedure.query(async ({ ctx }) => {
|
|
||||||
const admin = await findAdminById(ctx.user.adminId);
|
const admin = await findAdminById(ctx.user.adminId);
|
||||||
|
const servers = await findServersByAdminId(admin.adminId);
|
||||||
|
|
||||||
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
|
if (!IS_CLOUD) {
|
||||||
apiVersion: "2024-09-30.acacia",
|
return true;
|
||||||
});
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return servers.length < admin.serversQuantity;
|
||||||
nextPaymentDate: new Date(subscription.current_period_end * 1000),
|
|
||||||
monthlyAmount: totalAmount.toFixed(2),
|
|
||||||
totalServers,
|
|
||||||
billingInterval,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
|
|
||||||
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 = [];
|
const items = [];
|
||||||
|
|
||||||
if (isAnnual) {
|
if (isAnnual) {
|
||||||
if (serverQuantity === 1) {
|
|
||||||
items.push({
|
items.push({
|
||||||
price: BASE_PRICE_YEARLY_ID,
|
price: "price_1QC7XwF3cxQuHeOz68CpnIUZ",
|
||||||
quantity: 1,
|
quantity: serverQuantity,
|
||||||
});
|
});
|
||||||
} 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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
if (serverQuantity === 1) {
|
|
||||||
items.push({
|
items.push({
|
||||||
price: BASE_PRICE_MONTHLY_ID,
|
price: "price_1QC7X5F3cxQuHeOz1859ljDP",
|
||||||
quantity: 1,
|
quantity: serverQuantity,
|
||||||
});
|
});
|
||||||
} 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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return items;
|
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()),
|
.$defaultFn(() => new Date().toISOString()),
|
||||||
stripeCustomerId: text("stripeCustomerId"),
|
stripeCustomerId: text("stripeCustomerId"),
|
||||||
stripeSubscriptionId: text("stripeSubscriptionId"),
|
stripeSubscriptionId: text("stripeSubscriptionId"),
|
||||||
stripeSubscriptionStatus: text("stripeSubscriptionStatus"),
|
serversQuantity: integer("serversQuantity").notNull().default(0),
|
||||||
totalServers: integer("totalServers").notNull().default(0),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const adminsRelations = relations(admins, ({ one, many }) => ({
|
export const adminsRelations = relations(admins, ({ one, many }) => ({
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import { relations } from "drizzle-orm";
|
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 { createInsertSchema } from "drizzle-zod";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
@ -17,6 +17,8 @@ import { redis } from "./redis";
|
|||||||
import { sshKeys } from "./ssh-key";
|
import { sshKeys } from "./ssh-key";
|
||||||
import { generateAppName } from "./utils";
|
import { generateAppName } from "./utils";
|
||||||
|
|
||||||
|
export const serverStatus = pgEnum("serverStatus", ["active", "inactive"]);
|
||||||
|
|
||||||
export const server = pgTable("server", {
|
export const server = pgTable("server", {
|
||||||
serverId: text("serverId")
|
serverId: text("serverId")
|
||||||
.notNull()
|
.notNull()
|
||||||
@ -37,6 +39,8 @@ export const server = pgTable("server", {
|
|||||||
adminId: text("adminId")
|
adminId: text("adminId")
|
||||||
.notNull()
|
.notNull()
|
||||||
.references(() => admins.adminId, { onDelete: "cascade" }),
|
.references(() => admins.adminId, { onDelete: "cascade" }),
|
||||||
|
serverStatus: serverStatus("serverStatus").notNull().default("active"),
|
||||||
|
|
||||||
sshKeyId: text("sshKeyId").references(() => sshKeys.sshKeyId, {
|
sshKeyId: text("sshKeyId").references(() => sshKeys.sshKeyId, {
|
||||||
onDelete: "set null",
|
onDelete: "set null",
|
||||||
}),
|
}),
|
||||||
|
@ -13036,7 +13036,7 @@ snapshots:
|
|||||||
eslint: 8.45.0
|
eslint: 8.45.0
|
||||||
eslint-import-resolver-node: 0.3.9
|
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-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-jsx-a11y: 6.9.0(eslint@8.45.0)
|
||||||
eslint-plugin-react: 7.35.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)
|
eslint-plugin-react-hooks: 5.0.0-canary-7118f5dd7-20230705(eslint@8.45.0)
|
||||||
@ -13060,7 +13060,7 @@ snapshots:
|
|||||||
enhanced-resolve: 5.17.1
|
enhanced-resolve: 5.17.1
|
||||||
eslint: 8.45.0
|
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-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
|
fast-glob: 3.3.2
|
||||||
get-tsconfig: 4.7.5
|
get-tsconfig: 4.7.5
|
||||||
is-core-module: 2.15.0
|
is-core-module: 2.15.0
|
||||||
@ -13082,7 +13082,7 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- 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:
|
dependencies:
|
||||||
array-includes: 3.1.8
|
array-includes: 3.1.8
|
||||||
array.prototype.findlastindex: 1.2.5
|
array.prototype.findlastindex: 1.2.5
|
||||||
|
Loading…
Reference in New Issue
Block a user