mirror of
https://github.com/hex248/sprint.git
synced 2026-02-07 18:23:03 +00:00
fix: proper cancellation handling
This commit is contained in:
5
bun.lock
5
bun.lock
@@ -42,6 +42,7 @@
|
|||||||
"@iconify/react": "^6.0.2",
|
"@iconify/react": "^6.0.2",
|
||||||
"@nsmr/pixelart-react": "^2.0.0",
|
"@nsmr/pixelart-react": "^2.0.0",
|
||||||
"@phosphor-icons/react": "^2.1.10",
|
"@phosphor-icons/react": "^2.1.10",
|
||||||
|
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
"@radix-ui/react-label": "^2.1.8",
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
@@ -279,6 +280,8 @@
|
|||||||
|
|
||||||
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
||||||
|
|
||||||
|
"@radix-ui/react-alert-dialog": ["@radix-ui/react-alert-dialog@1.1.15", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-dialog": "1.1.15", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw=="],
|
||||||
|
|
||||||
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
|
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
|
||||||
|
|
||||||
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
|
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
|
||||||
@@ -837,6 +840,8 @@
|
|||||||
|
|
||||||
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
|
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
|
||||||
|
|
||||||
|
"@radix-ui/react-alert-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||||
|
|
||||||
"@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
"@radix-ui/react-collection/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||||
|
|
||||||
"@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
"@radix-ui/react-dialog/@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
|
||||||
|
|||||||
@@ -108,6 +108,7 @@ const main = async () => {
|
|||||||
"/subscription/create-portal-session": withGlobalAuthed(
|
"/subscription/create-portal-session": withGlobalAuthed(
|
||||||
withAuth(withCSRF(routes.subscriptionCreatePortalSession)),
|
withAuth(withCSRF(routes.subscriptionCreatePortalSession)),
|
||||||
),
|
),
|
||||||
|
"/subscription/cancel": withGlobalAuthed(withAuth(withCSRF(routes.subscriptionCancel))),
|
||||||
"/subscription/get": withGlobalAuthed(withAuth(routes.subscriptionGet)),
|
"/subscription/get": withGlobalAuthed(withAuth(routes.subscriptionGet)),
|
||||||
"/subscription/webhook": withGlobal(routes.subscriptionWebhook),
|
"/subscription/webhook": withGlobal(routes.subscriptionWebhook),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ import sprintCreate from "./sprint/create";
|
|||||||
import sprintDelete from "./sprint/delete";
|
import sprintDelete from "./sprint/delete";
|
||||||
import sprintUpdate from "./sprint/update";
|
import sprintUpdate from "./sprint/update";
|
||||||
import sprintsByProject from "./sprints/by-project";
|
import sprintsByProject from "./sprints/by-project";
|
||||||
|
import subscriptionCancel from "./subscription/cancel";
|
||||||
import subscriptionCreateCheckoutSession from "./subscription/create-checkout-session";
|
import subscriptionCreateCheckoutSession from "./subscription/create-checkout-session";
|
||||||
import subscriptionCreatePortalSession from "./subscription/create-portal-session";
|
import subscriptionCreatePortalSession from "./subscription/create-portal-session";
|
||||||
import subscriptionGet from "./subscription/get";
|
import subscriptionGet from "./subscription/get";
|
||||||
@@ -113,6 +114,7 @@ export const routes = {
|
|||||||
|
|
||||||
subscriptionCreateCheckoutSession,
|
subscriptionCreateCheckoutSession,
|
||||||
subscriptionCreatePortalSession,
|
subscriptionCreatePortalSession,
|
||||||
|
subscriptionCancel,
|
||||||
subscriptionGet,
|
subscriptionGet,
|
||||||
subscriptionWebhook,
|
subscriptionWebhook,
|
||||||
};
|
};
|
||||||
|
|||||||
68
packages/backend/src/routes/subscription/cancel.ts
Normal file
68
packages/backend/src/routes/subscription/cancel.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import { type AuthedRequest, withAuth, withCors, withCSRF } from "../../auth/middleware";
|
||||||
|
import { getSubscriptionByUserId, updateSubscription } from "../../db/queries/subscriptions";
|
||||||
|
import { stripe } from "../../stripe/client";
|
||||||
|
import { errorResponse } from "../../validation";
|
||||||
|
|
||||||
|
async function handler(req: AuthedRequest) {
|
||||||
|
if (req.method !== "POST") {
|
||||||
|
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { userId } = req;
|
||||||
|
const subscription = await getSubscriptionByUserId(userId);
|
||||||
|
if (!subscription?.stripeSubscriptionId) {
|
||||||
|
return errorResponse("no active subscription found", "NOT_FOUND", 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const stripeCurrent = (await stripe.subscriptions.retrieve(
|
||||||
|
subscription.stripeSubscriptionId,
|
||||||
|
)) as unknown as {
|
||||||
|
status: string;
|
||||||
|
cancel_at_period_end: boolean | null;
|
||||||
|
current_period_end: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const currentPeriodEnd = stripeCurrent.current_period_end
|
||||||
|
? new Date(stripeCurrent.current_period_end * 1000)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (stripeCurrent.status === "canceled" || stripeCurrent.cancel_at_period_end) {
|
||||||
|
const updated = await updateSubscription(subscription.id, {
|
||||||
|
status: stripeCurrent.status,
|
||||||
|
cancelAtPeriodEnd: stripeCurrent.cancel_at_period_end ?? subscription.cancelAtPeriodEnd,
|
||||||
|
...(currentPeriodEnd && { currentPeriodEnd }),
|
||||||
|
});
|
||||||
|
return new Response(JSON.stringify({ subscription: updated }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const stripeSubscription = (await stripe.subscriptions.update(subscription.stripeSubscriptionId, {
|
||||||
|
cancel_at_period_end: true,
|
||||||
|
})) as unknown as {
|
||||||
|
status: string;
|
||||||
|
cancel_at_period_end: boolean | null;
|
||||||
|
current_period_end: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updated = await updateSubscription(subscription.id, {
|
||||||
|
status: stripeSubscription.status,
|
||||||
|
cancelAtPeriodEnd: stripeSubscription.cancel_at_period_end ?? true,
|
||||||
|
currentPeriodEnd: stripeSubscription.current_period_end
|
||||||
|
? new Date(stripeSubscription.current_period_end * 1000)
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ subscription: updated }), {
|
||||||
|
status: 200,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("subscription cancel error:", error);
|
||||||
|
return errorResponse("failed to cancel subscription", "CANCEL_ERROR", 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default withCors(withAuth(withCSRF(handler)));
|
||||||
@@ -11,6 +11,15 @@ import { stripe } from "../../stripe/client";
|
|||||||
|
|
||||||
const webhookSecret = requireEnv("STRIPE_WEBHOOK_SECRET");
|
const webhookSecret = requireEnv("STRIPE_WEBHOOK_SECRET");
|
||||||
|
|
||||||
|
function toStripeDate(seconds: number | null | undefined, field: string) {
|
||||||
|
if (seconds === null || seconds === undefined) return undefined;
|
||||||
|
if (!Number.isFinite(seconds)) {
|
||||||
|
console.warn(`invalid ${field} timestamp:`, seconds);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return new Date(seconds * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
function requireEnv(name: string): string {
|
function requireEnv(name: string): string {
|
||||||
const value = process.env[name];
|
const value = process.env[name];
|
||||||
if (!value) {
|
if (!value) {
|
||||||
@@ -71,8 +80,8 @@ export default async function webhook(req: BunRequest) {
|
|||||||
|
|
||||||
// stripe types use snake_case for these fields
|
// stripe types use snake_case for these fields
|
||||||
const sub = stripeSubscription as unknown as {
|
const sub = stripeSubscription as unknown as {
|
||||||
current_period_start: number;
|
current_period_start: number | null;
|
||||||
current_period_end: number;
|
current_period_end: number | null;
|
||||||
trial_end: number | null;
|
trial_end: number | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -84,9 +93,9 @@ export default async function webhook(req: BunRequest) {
|
|||||||
stripePriceId: session.metadata?.priceId || "",
|
stripePriceId: session.metadata?.priceId || "",
|
||||||
status: stripeSubscription.status,
|
status: stripeSubscription.status,
|
||||||
quantity: parseInt(session.metadata?.quantity || "1", 10),
|
quantity: parseInt(session.metadata?.quantity || "1", 10),
|
||||||
currentPeriodStart: new Date(sub.current_period_start * 1000),
|
currentPeriodStart: toStripeDate(sub.current_period_start, "current_period_start"),
|
||||||
currentPeriodEnd: new Date(sub.current_period_end * 1000),
|
currentPeriodEnd: toStripeDate(sub.current_period_end, "current_period_end"),
|
||||||
trialEnd: sub.trial_end ? new Date(sub.trial_end * 1000) : undefined,
|
trialEnd: toStripeDate(sub.trial_end, "trial_end"),
|
||||||
});
|
});
|
||||||
|
|
||||||
await updateUser(userId, { plan: "pro" });
|
await updateUser(userId, { plan: "pro" });
|
||||||
@@ -117,12 +126,8 @@ export default async function webhook(req: BunRequest) {
|
|||||||
current_period_start: number | null;
|
current_period_start: number | null;
|
||||||
current_period_end: number | null;
|
current_period_end: number | null;
|
||||||
};
|
};
|
||||||
const currentPeriodStart = sub.current_period_start
|
const currentPeriodStart = toStripeDate(sub.current_period_start, "current_period_start");
|
||||||
? new Date(sub.current_period_start * 1000)
|
const currentPeriodEnd = toStripeDate(sub.current_period_end, "current_period_end");
|
||||||
: undefined;
|
|
||||||
const currentPeriodEnd = sub.current_period_end
|
|
||||||
? new Date(sub.current_period_end * 1000)
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
await updateSubscription(localSub.id, {
|
await updateSubscription(localSub.id, {
|
||||||
status: subscription.status,
|
status: subscription.status,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"@ts-rest/core": "^3.52.1",
|
"@ts-rest/core": "^3.52.1",
|
||||||
"@nsmr/pixelart-react": "^2.0.0",
|
"@nsmr/pixelart-react": "^2.0.0",
|
||||||
"@phosphor-icons/react": "^2.1.10",
|
"@phosphor-icons/react": "^2.1.10",
|
||||||
|
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dialog": "^1.1.15",
|
"@radix-ui/react-dialog": "^1.1.15",
|
||||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||||
"@radix-ui/react-label": "^2.1.8",
|
"@radix-ui/react-label": "^2.1.8",
|
||||||
|
|||||||
131
packages/frontend/src/components/ui/alert-dialog.tsx
Normal file
131
packages/frontend/src/components/ui/alert-dialog.tsx
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||||
|
import type * as React from "react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||||
|
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||||
|
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||||
|
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogOverlay({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Overlay
|
||||||
|
data-slot="alert-dialog-overlay"
|
||||||
|
className={cn("fixed inset-0 z-50 bg-black/50", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogContent({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPortal>
|
||||||
|
<AlertDialogOverlay />
|
||||||
|
<AlertDialogPrimitive.Content
|
||||||
|
data-slot="alert-dialog-content"
|
||||||
|
className={cn(
|
||||||
|
"bg-background data-[state=closed]:zoom-out-95",
|
||||||
|
"data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%]",
|
||||||
|
"z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%]",
|
||||||
|
"gap-4 border p-4 shadow-lg duration-200 outline-none w-sm",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</AlertDialogPortal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-footer"
|
||||||
|
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Title
|
||||||
|
data-slot="alert-dialog-title"
|
||||||
|
className={cn("text-lg leading-none font-semibold", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Description
|
||||||
|
data-slot="alert-dialog-description"
|
||||||
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type AlertDialogActionProps = React.ComponentProps<typeof AlertDialogPrimitive.Action> &
|
||||||
|
Omit<React.ComponentProps<typeof Button>, "asChild">;
|
||||||
|
|
||||||
|
function AlertDialogAction({ className, ...props }: AlertDialogActionProps) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Action asChild>
|
||||||
|
<Button className={className} {...props} />
|
||||||
|
</AlertDialogPrimitive.Action>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type AlertDialogCancelProps = React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
|
||||||
|
Omit<React.ComponentProps<typeof Button>, "asChild">;
|
||||||
|
|
||||||
|
function AlertDialogCancel({ className, ...props }: AlertDialogCancelProps) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Cancel asChild>
|
||||||
|
<Button variant="outline" className={className} {...props} />
|
||||||
|
</AlertDialogPrimitive.Cancel>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogOverlay,
|
||||||
|
AlertDialogPortal,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
};
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import type {
|
import type {
|
||||||
|
CancelSubscriptionResponse,
|
||||||
CreateCheckoutSessionRequest,
|
CreateCheckoutSessionRequest,
|
||||||
CreateCheckoutSessionResponse,
|
CreateCheckoutSessionResponse,
|
||||||
CreatePortalSessionResponse,
|
CreatePortalSessionResponse,
|
||||||
GetSubscriptionResponse,
|
GetSubscriptionResponse,
|
||||||
} from "@sprint/shared";
|
} from "@sprint/shared";
|
||||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { queryKeys } from "@/lib/query/keys";
|
import { queryKeys } from "@/lib/query/keys";
|
||||||
import { apiClient } from "@/lib/server";
|
import { apiClient } from "@/lib/server";
|
||||||
|
|
||||||
@@ -42,3 +43,20 @@ export function useCreatePortalSession() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function useCancelSubscription() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
return useMutation<CancelSubscriptionResponse, Error>({
|
||||||
|
mutationKey: ["subscription", "cancel"],
|
||||||
|
mutationFn: async () => {
|
||||||
|
const { data, error } = await apiClient.subscriptionCancel({ body: {} });
|
||||||
|
if (error) throw new Error(error);
|
||||||
|
if (!data) throw new Error("failed to cancel subscription");
|
||||||
|
return data as CancelSubscriptionResponse;
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: queryKeys.subscription.current() });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,12 +1,29 @@
|
|||||||
import { useState } from "react";
|
import { format } from "date-fns";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
import { Link, useNavigate } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import { LoginModal } from "@/components/login-modal";
|
import { LoginModal } from "@/components/login-modal";
|
||||||
import { PricingCard, pricingTiers } from "@/components/pricing-card";
|
import { PricingCard, pricingTiers } from "@/components/pricing-card";
|
||||||
import { useSession } from "@/components/session-provider";
|
import { useSession } from "@/components/session-provider";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import Icon from "@/components/ui/icon";
|
import Icon from "@/components/ui/icon";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { useCreateCheckoutSession, useCreatePortalSession, useSubscription } from "@/lib/query/hooks";
|
import {
|
||||||
|
useCancelSubscription,
|
||||||
|
useCreateCheckoutSession,
|
||||||
|
useCreatePortalSession,
|
||||||
|
useSubscription,
|
||||||
|
} from "@/lib/query/hooks";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
export default function Plans() {
|
export default function Plans() {
|
||||||
@@ -19,9 +36,21 @@ export default function Plans() {
|
|||||||
const { data: subscriptionData } = useSubscription();
|
const { data: subscriptionData } = useSubscription();
|
||||||
const createCheckoutSession = useCreateCheckoutSession();
|
const createCheckoutSession = useCreateCheckoutSession();
|
||||||
const createPortalSession = useCreatePortalSession();
|
const createPortalSession = useCreatePortalSession();
|
||||||
|
const cancelSubscription = useCancelSubscription();
|
||||||
|
|
||||||
const subscription = subscriptionData?.subscription ?? null;
|
const subscription = subscriptionData?.subscription ?? null;
|
||||||
const hasProSubscription = subscription?.status === "active";
|
const isProUser =
|
||||||
|
user?.plan === "pro" || subscription?.status === "active" || subscription?.status === "trialing";
|
||||||
|
const isCancellationScheduled = Boolean(subscription?.cancelAtPeriodEnd);
|
||||||
|
const isCanceled = subscription?.status === "canceled";
|
||||||
|
const cancellationEndDate = useMemo(() => {
|
||||||
|
if (!subscription?.currentPeriodEnd) return null;
|
||||||
|
const date = new Date(subscription.currentPeriodEnd);
|
||||||
|
if (Number.isNaN(date.getTime())) return null;
|
||||||
|
return format(date, "d MMM yyyy");
|
||||||
|
}, [subscription?.currentPeriodEnd]);
|
||||||
|
const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
|
||||||
|
const [cancelError, setCancelError] = useState<string | null>(null);
|
||||||
|
|
||||||
const handleTierAction = async (tierName: string) => {
|
const handleTierAction = async (tierName: string) => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
@@ -30,7 +59,7 @@ export default function Plans() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (tierName === "Pro") {
|
if (tierName === "Pro") {
|
||||||
if (hasProSubscription) {
|
if (isProUser) {
|
||||||
// open customer portal
|
// open customer portal
|
||||||
setProcessingTier(tierName);
|
setProcessingTier(tierName);
|
||||||
try {
|
try {
|
||||||
@@ -64,14 +93,25 @@ export default function Plans() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleCancelSubscription = async () => {
|
||||||
|
setCancelError(null);
|
||||||
|
try {
|
||||||
|
await cancelSubscription.mutateAsync();
|
||||||
|
setCancelDialogOpen(false);
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "failed to cancel subscription";
|
||||||
|
setCancelError(message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// modify pricing tiers based on user's current plan
|
// modify pricing tiers based on user's current plan
|
||||||
const modifiedTiers = pricingTiers.map((tier) => {
|
const modifiedTiers = pricingTiers.map((tier) => {
|
||||||
const isCurrentPlan = tier.name === "Pro" && hasProSubscription;
|
const isCurrentPlan = tier.name === "Pro" && isProUser;
|
||||||
const isStarterCurrent = tier.name === "Starter" && !hasProSubscription;
|
const isStarterCurrent = tier.name === "Starter" && !!user && !isProUser;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...tier,
|
...tier,
|
||||||
highlighted: isCurrentPlan || (!hasProSubscription && tier.name === "Pro"),
|
highlighted: isCurrentPlan || (!isProUser && tier.name === "Pro"),
|
||||||
cta: isCurrentPlan
|
cta: isCurrentPlan
|
||||||
? "Manage subscription"
|
? "Manage subscription"
|
||||||
: isStarterCurrent
|
: isStarterCurrent
|
||||||
@@ -120,7 +160,7 @@ export default function Plans() {
|
|||||||
</h1>
|
</h1>
|
||||||
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
|
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
|
||||||
{user
|
{user
|
||||||
? hasProSubscription
|
? isProUser
|
||||||
? "You are currently on the Pro plan. Manage your subscription or switch plans below."
|
? "You are currently on the Pro plan. Manage your subscription or switch plans below."
|
||||||
: "You are currently on the Starter plan. Upgrade to Pro for unlimited access."
|
: "You are currently on the Starter plan. Upgrade to Pro for unlimited access."
|
||||||
: "Choose the plan that fits your team. Scale as you grow."}
|
: "Choose the plan that fits your team. Scale as you grow."}
|
||||||
@@ -175,6 +215,54 @@ export default function Plans() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{user && isProUser && (
|
||||||
|
<div className="w-full max-w-4xl mx-auto border rounded-md p-6">
|
||||||
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="font-700">Cancel subscription</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{isCancellationScheduled || isCanceled
|
||||||
|
? `Cancelled, benefits end on ${cancellationEndDate ?? "your billing end date"}.`
|
||||||
|
: "Canceling will keep access until the end of your billing period."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<AlertDialog
|
||||||
|
open={cancelDialogOpen}
|
||||||
|
onOpenChange={(open: boolean) => {
|
||||||
|
setCancelDialogOpen(open);
|
||||||
|
if (!open) setCancelError(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={cancelSubscription.isPending || isCancellationScheduled || isCanceled}
|
||||||
|
>
|
||||||
|
{isCancellationScheduled || isCanceled
|
||||||
|
? "Cancellation scheduled"
|
||||||
|
: "Cancel subscription"}
|
||||||
|
</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Cancel subscription?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
You will keep Pro access until the end of your current billing period.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Keep subscription</AlertDialogCancel>
|
||||||
|
<AlertDialogAction variant="destructive" onClick={handleCancelSubscription}>
|
||||||
|
{cancelSubscription.isPending ? "Canceling..." : "Confirm cancel"}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
{cancelError && <p className="text-sm text-destructive">{cancelError}</p>}
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* trust signals */}
|
{/* trust signals */}
|
||||||
<div className="grid md:grid-cols-3 gap-8 w-full border-t pt-16 pb-8 max-w-4xl mx-auto">
|
<div className="grid md:grid-cols-3 gap-8 w-full border-t pt-16 pb-8 max-w-4xl mx-auto">
|
||||||
<div className="flex flex-col items-center text-center gap-2">
|
<div className="flex flex-col items-center text-center gap-2">
|
||||||
|
|||||||
@@ -647,3 +647,9 @@ export const GetSubscriptionResponseSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export type GetSubscriptionResponse = z.infer<typeof GetSubscriptionResponseSchema>;
|
export type GetSubscriptionResponse = z.infer<typeof GetSubscriptionResponseSchema>;
|
||||||
|
|
||||||
|
export const CancelSubscriptionResponseSchema = z.object({
|
||||||
|
subscription: SubscriptionRecordSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CancelSubscriptionResponse = z.infer<typeof CancelSubscriptionResponseSchema>;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|||||||
import {
|
import {
|
||||||
ApiErrorSchema,
|
ApiErrorSchema,
|
||||||
AuthResponseSchema,
|
AuthResponseSchema,
|
||||||
|
CancelSubscriptionResponseSchema,
|
||||||
CreateCheckoutSessionRequestSchema,
|
CreateCheckoutSessionRequestSchema,
|
||||||
CreateCheckoutSessionResponseSchema,
|
CreateCheckoutSessionResponseSchema,
|
||||||
CreatePortalSessionResponseSchema,
|
CreatePortalSessionResponseSchema,
|
||||||
@@ -628,6 +629,17 @@ export const apiContract = c.router({
|
|||||||
},
|
},
|
||||||
headers: csrfHeaderSchema,
|
headers: csrfHeaderSchema,
|
||||||
},
|
},
|
||||||
|
subscriptionCancel: {
|
||||||
|
method: "POST",
|
||||||
|
path: "/subscription/cancel",
|
||||||
|
body: emptyBodySchema,
|
||||||
|
responses: {
|
||||||
|
200: CancelSubscriptionResponseSchema,
|
||||||
|
404: ApiErrorSchema,
|
||||||
|
500: ApiErrorSchema,
|
||||||
|
},
|
||||||
|
headers: csrfHeaderSchema,
|
||||||
|
},
|
||||||
subscriptionGet: {
|
subscriptionGet: {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
path: "/subscription/get",
|
path: "/subscription/get",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
export type {
|
export type {
|
||||||
ApiError,
|
ApiError,
|
||||||
AuthResponse,
|
AuthResponse,
|
||||||
|
CancelSubscriptionResponse,
|
||||||
CreateCheckoutSessionRequest,
|
CreateCheckoutSessionRequest,
|
||||||
CreateCheckoutSessionResponse,
|
CreateCheckoutSessionResponse,
|
||||||
CreatePortalSessionResponse,
|
CreatePortalSessionResponse,
|
||||||
@@ -67,6 +68,7 @@ export type {
|
|||||||
export {
|
export {
|
||||||
ApiErrorSchema,
|
ApiErrorSchema,
|
||||||
AuthResponseSchema,
|
AuthResponseSchema,
|
||||||
|
CancelSubscriptionResponseSchema,
|
||||||
CreateCheckoutSessionRequestSchema,
|
CreateCheckoutSessionRequestSchema,
|
||||||
CreateCheckoutSessionResponseSchema,
|
CreateCheckoutSessionResponseSchema,
|
||||||
CreatePortalSessionResponseSchema,
|
CreatePortalSessionResponseSchema,
|
||||||
|
|||||||
Reference in New Issue
Block a user