feat: add webhook

This commit is contained in:
Mauricio Siu
2024-10-20 23:08:26 -06:00
parent ffe7b04bea
commit 1907e7e59c
13 changed files with 4483 additions and 827 deletions

View File

@@ -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>
);
};

View File

@@ -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"
>

View File

@@ -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>