mirror of
https://github.com/hex248/sprint.git
synced 2026-02-07 18:23:03 +00:00
fixed to use hooks
This commit is contained in:
@@ -33,8 +33,13 @@ export async function updateSeatCount(userId: number) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const stripeSubscriptionItemId = subscription.stripeSubscriptionItemId;
|
||||||
|
if (!stripeSubscriptionItemId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// update stripe
|
// update stripe
|
||||||
await stripe.subscriptionItems.update(subscription.stripeSubscriptionItemId!, {
|
await stripe.subscriptionItems.update(stripeSubscriptionItemId, {
|
||||||
quantity: newQuantity,
|
quantity: newQuantity,
|
||||||
proration_behavior: "always_invoice",
|
proration_behavior: "always_invoice",
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { BunRequest } from "bun";
|
import { type AuthedRequest, withAuth, withCors, withCSRF } from "../../auth/middleware";
|
||||||
import { withAuth, withCors, withCSRF } from "../../auth/middleware";
|
|
||||||
import { getOrganisationMembers, getOrganisationsByUserId } from "../../db/queries/organisations";
|
import { getOrganisationMembers, getOrganisationsByUserId } from "../../db/queries/organisations";
|
||||||
import { getUserById } from "../../db/queries/users";
|
import { getUserById } from "../../db/queries/users";
|
||||||
import { STRIPE_PRICE_ANNUAL, STRIPE_PRICE_MONTHLY, stripe } from "../../stripe/client";
|
import { STRIPE_PRICE_ANNUAL, STRIPE_PRICE_MONTHLY, stripe } from "../../stripe/client";
|
||||||
@@ -7,7 +6,7 @@ import { errorResponse } from "../../validation";
|
|||||||
|
|
||||||
const BASE_URL = process.env.FRONTEND_URL || "http://localhost:1420";
|
const BASE_URL = process.env.FRONTEND_URL || "http://localhost:1420";
|
||||||
|
|
||||||
async function handler(req: BunRequest) {
|
async function handler(req: AuthedRequest) {
|
||||||
if (req.method !== "POST") {
|
if (req.method !== "POST") {
|
||||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||||
}
|
}
|
||||||
@@ -20,7 +19,7 @@ async function handler(req: BunRequest) {
|
|||||||
return errorResponse("missing required fields", "VALIDATION_ERROR", 400);
|
return errorResponse("missing required fields", "VALIDATION_ERROR", 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = (req as any).userId;
|
const { userId } = req;
|
||||||
const user = await getUserById(userId);
|
const user = await getUserById(userId);
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
import type { BunRequest } from "bun";
|
import { type AuthedRequest, withAuth, withCors, withCSRF } from "../../auth/middleware";
|
||||||
import { withAuth, withCors, withCSRF } from "../../auth/middleware";
|
|
||||||
import { getSubscriptionByUserId } from "../../db/queries/subscriptions";
|
import { getSubscriptionByUserId } from "../../db/queries/subscriptions";
|
||||||
import { stripe } from "../../stripe/client";
|
import { stripe } from "../../stripe/client";
|
||||||
import { errorResponse } from "../../validation";
|
import { errorResponse } from "../../validation";
|
||||||
|
|
||||||
const BASE_URL = process.env.FRONTEND_URL || "http://localhost:1420";
|
const BASE_URL = process.env.FRONTEND_URL || "http://localhost:1420";
|
||||||
|
|
||||||
async function handler(req: BunRequest) {
|
async function handler(req: AuthedRequest) {
|
||||||
if (req.method !== "POST") {
|
if (req.method !== "POST") {
|
||||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const userId = (req as any).userId;
|
const { userId } = req;
|
||||||
const subscription = await getSubscriptionByUserId(userId);
|
const subscription = await getSubscriptionByUserId(userId);
|
||||||
if (!subscription?.stripeCustomerId) {
|
if (!subscription?.stripeCustomerId) {
|
||||||
return errorResponse("no active subscription found", "NOT_FOUND", 404);
|
return errorResponse("no active subscription found", "NOT_FOUND", 404);
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
import type { BunRequest } from "bun";
|
import { type AuthedRequest, withAuth, withCors } from "../../auth/middleware";
|
||||||
import { withAuth, withCors } from "../../auth/middleware";
|
|
||||||
import { getSubscriptionByUserId } from "../../db/queries/subscriptions";
|
import { getSubscriptionByUserId } from "../../db/queries/subscriptions";
|
||||||
import { errorResponse } from "../../validation";
|
import { errorResponse } from "../../validation";
|
||||||
|
|
||||||
async function handler(req: BunRequest) {
|
async function handler(req: AuthedRequest) {
|
||||||
if (req.method !== "GET") {
|
if (req.method !== "GET") {
|
||||||
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
return errorResponse("method not allowed", "METHOD_NOT_ALLOWED", 405);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const userId = (req as any).userId;
|
const { userId } = req;
|
||||||
const subscription = await getSubscriptionByUserId(userId);
|
const subscription = await getSubscriptionByUserId(userId);
|
||||||
|
|
||||||
return new Response(JSON.stringify({ subscription }), {
|
return new Response(JSON.stringify({ subscription }), {
|
||||||
|
|||||||
@@ -9,7 +9,15 @@ import {
|
|||||||
import { updateUser } from "../../db/queries/users";
|
import { updateUser } from "../../db/queries/users";
|
||||||
import { stripe } from "../../stripe/client";
|
import { stripe } from "../../stripe/client";
|
||||||
|
|
||||||
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || "";
|
const webhookSecret = requireEnv("STRIPE_WEBHOOK_SECRET");
|
||||||
|
|
||||||
|
function requireEnv(name: string): string {
|
||||||
|
const value = process.env[name];
|
||||||
|
if (!value) {
|
||||||
|
throw new Error(`${name} is required`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
export default async function webhook(req: BunRequest) {
|
export default async function webhook(req: BunRequest) {
|
||||||
if (req.method !== "POST") {
|
if (req.method !== "POST") {
|
||||||
@@ -61,6 +69,13 @@ export default async function webhook(req: BunRequest) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// stripe types use snake_case for these fields
|
||||||
|
const sub = stripeSubscription as unknown as {
|
||||||
|
current_period_start: number;
|
||||||
|
current_period_end: number;
|
||||||
|
trial_end: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
await createSubscription({
|
await createSubscription({
|
||||||
userId,
|
userId,
|
||||||
stripeCustomerId: session.customer as string,
|
stripeCustomerId: session.customer as string,
|
||||||
@@ -69,11 +84,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((stripeSubscription as any).current_period_start * 1000),
|
currentPeriodStart: new Date(sub.current_period_start * 1000),
|
||||||
currentPeriodEnd: new Date((stripeSubscription as any).current_period_end * 1000),
|
currentPeriodEnd: new Date(sub.current_period_end * 1000),
|
||||||
trialEnd: stripeSubscription.trial_end
|
trialEnd: sub.trial_end ? new Date(sub.trial_end * 1000) : undefined,
|
||||||
? new Date(stripeSubscription.trial_end * 1000)
|
|
||||||
: undefined,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await updateUser(userId, { plan: "pro" });
|
await updateUser(userId, { plan: "pro" });
|
||||||
@@ -99,11 +112,16 @@ export default async function webhook(req: BunRequest) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// safely convert timestamps to dates
|
// safely convert timestamps to dates
|
||||||
const currentPeriodStart = (subscription as any).current_period_start
|
// stripe types use snake_case for these fields
|
||||||
? new Date((subscription as any).current_period_start * 1000)
|
const sub = subscription as unknown as {
|
||||||
|
current_period_start: number | null;
|
||||||
|
current_period_end: number | null;
|
||||||
|
};
|
||||||
|
const currentPeriodStart = sub.current_period_start
|
||||||
|
? new Date(sub.current_period_start * 1000)
|
||||||
: undefined;
|
: undefined;
|
||||||
const currentPeriodEnd = (subscription as any).current_period_end
|
const currentPeriodEnd = sub.current_period_end
|
||||||
? new Date((subscription as any).current_period_end * 1000)
|
? new Date(sub.current_period_end * 1000)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
await updateSubscription(localSub.id, {
|
await updateSubscription(localSub.id, {
|
||||||
@@ -136,34 +154,45 @@ export default async function webhook(req: BunRequest) {
|
|||||||
case "invoice.payment_succeeded": {
|
case "invoice.payment_succeeded": {
|
||||||
const invoice = event.data.object as Stripe.Invoice;
|
const invoice = event.data.object as Stripe.Invoice;
|
||||||
|
|
||||||
if (!(invoice as any).subscription) break;
|
// stripe types use snake_case for these fields
|
||||||
|
const inv = invoice as unknown as {
|
||||||
|
subscription: string | null;
|
||||||
|
payment_intent: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
const localSub = await getSubscriptionByStripeId((invoice as any).subscription as string);
|
if (!inv.subscription) break;
|
||||||
|
|
||||||
|
const localSub = await getSubscriptionByStripeId(inv.subscription);
|
||||||
if (!localSub) break;
|
if (!localSub) break;
|
||||||
|
|
||||||
await createPayment({
|
await createPayment({
|
||||||
subscriptionId: localSub.id,
|
subscriptionId: localSub.id,
|
||||||
stripePaymentIntentId: (invoice as any).payment_intent as string,
|
stripePaymentIntentId: inv.payment_intent || "",
|
||||||
amount: invoice.amount_paid,
|
amount: invoice.amount_paid,
|
||||||
currency: invoice.currency,
|
currency: invoice.currency,
|
||||||
status: "succeeded",
|
status: "succeeded",
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`payment recorded for subscription ${(invoice as any).subscription}`);
|
console.log(`payment recorded for subscription ${inv.subscription}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "invoice.payment_failed": {
|
case "invoice.payment_failed": {
|
||||||
const invoice = event.data.object as Stripe.Invoice;
|
const invoice = event.data.object as Stripe.Invoice;
|
||||||
|
|
||||||
if (!(invoice as any).subscription) break;
|
// stripe types use snake_case for these fields
|
||||||
|
const inv = invoice as unknown as {
|
||||||
|
subscription: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
const localSub = await getSubscriptionByStripeId((invoice as any).subscription as string);
|
if (!inv.subscription) break;
|
||||||
|
|
||||||
|
const localSub = await getSubscriptionByStripeId(inv.subscription);
|
||||||
if (!localSub) break;
|
if (!localSub) break;
|
||||||
|
|
||||||
await updateSubscription(localSub.id, { status: "past_due" });
|
await updateSubscription(localSub.id, { status: "past_due" });
|
||||||
|
|
||||||
console.log(`payment failed for subscription ${(invoice as any).subscription}`);
|
console.log(`payment failed for subscription ${inv.subscription}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
import Stripe from "stripe";
|
import Stripe from "stripe";
|
||||||
|
|
||||||
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
|
const stripeSecretKey = requireEnv("STRIPE_SECRET_KEY");
|
||||||
|
|
||||||
if (!stripeSecretKey) {
|
|
||||||
throw new Error("STRIPE_SECRET_KEY is required");
|
|
||||||
}
|
|
||||||
|
|
||||||
export const stripe = new Stripe(stripeSecretKey, {
|
export const stripe = new Stripe(stripeSecretKey, {
|
||||||
apiVersion: "2024-12-18.acacia",
|
apiVersion: "2025-12-15.clover",
|
||||||
});
|
});
|
||||||
|
|
||||||
export const STRIPE_PRICE_MONTHLY = process.env.STRIPE_PRICE_MONTHLY!;
|
export const STRIPE_PRICE_MONTHLY = requireEnv("STRIPE_PRICE_MONTHLY");
|
||||||
export const STRIPE_PRICE_ANNUAL = process.env.STRIPE_PRICE_ANNUAL!;
|
export const STRIPE_PRICE_ANNUAL = requireEnv("STRIPE_PRICE_ANNUAL");
|
||||||
|
|
||||||
|
function requireEnv(name: string): string {
|
||||||
|
const value = process.env[name];
|
||||||
|
if (!value) {
|
||||||
|
throw new Error(`${name} is required`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ export * from "@/lib/query/hooks/issues";
|
|||||||
export * from "@/lib/query/hooks/organisations";
|
export * from "@/lib/query/hooks/organisations";
|
||||||
export * from "@/lib/query/hooks/projects";
|
export * from "@/lib/query/hooks/projects";
|
||||||
export * from "@/lib/query/hooks/sprints";
|
export * from "@/lib/query/hooks/sprints";
|
||||||
|
export * from "@/lib/query/hooks/subscriptions";
|
||||||
export * from "@/lib/query/hooks/timers";
|
export * from "@/lib/query/hooks/timers";
|
||||||
export * from "@/lib/query/hooks/users";
|
export * from "@/lib/query/hooks/users";
|
||||||
|
|||||||
44
packages/frontend/src/lib/query/hooks/subscriptions.ts
Normal file
44
packages/frontend/src/lib/query/hooks/subscriptions.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import type {
|
||||||
|
CreateCheckoutSessionRequest,
|
||||||
|
CreateCheckoutSessionResponse,
|
||||||
|
CreatePortalSessionResponse,
|
||||||
|
GetSubscriptionResponse,
|
||||||
|
} from "@sprint/shared";
|
||||||
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||||
|
import { queryKeys } from "@/lib/query/keys";
|
||||||
|
import { apiClient } from "@/lib/server";
|
||||||
|
|
||||||
|
export function useSubscription() {
|
||||||
|
return useQuery<GetSubscriptionResponse>({
|
||||||
|
queryKey: queryKeys.subscription.current(),
|
||||||
|
queryFn: async () => {
|
||||||
|
const { data, error } = await apiClient.subscriptionGet();
|
||||||
|
if (error) throw new Error(error);
|
||||||
|
return (data ?? { subscription: null }) as GetSubscriptionResponse;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateCheckoutSession() {
|
||||||
|
return useMutation<CreateCheckoutSessionResponse, Error, CreateCheckoutSessionRequest>({
|
||||||
|
mutationKey: ["subscription", "checkout"],
|
||||||
|
mutationFn: async (input) => {
|
||||||
|
const { data, error } = await apiClient.subscriptionCreateCheckoutSession({ body: input });
|
||||||
|
if (error) throw new Error(error);
|
||||||
|
if (!data) throw new Error("failed to create checkout session");
|
||||||
|
return data as CreateCheckoutSessionResponse;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreatePortalSession() {
|
||||||
|
return useMutation<CreatePortalSessionResponse, Error>({
|
||||||
|
mutationKey: ["subscription", "portal"],
|
||||||
|
mutationFn: async () => {
|
||||||
|
const { data, error } = await apiClient.subscriptionCreatePortalSession({ body: {} });
|
||||||
|
if (error) throw new Error(error);
|
||||||
|
if (!data) throw new Error("failed to create portal session");
|
||||||
|
return data as CreatePortalSessionResponse;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -39,4 +39,8 @@ export const queryKeys = {
|
|||||||
all: ["users"] as const,
|
all: ["users"] as const,
|
||||||
byUsername: (username: string) => [...queryKeys.users.all, "by-username", username] as const,
|
byUsername: (username: string) => [...queryKeys.users.all, "by-username", username] as const,
|
||||||
},
|
},
|
||||||
|
subscription: {
|
||||||
|
all: ["subscription"] as const,
|
||||||
|
current: () => [...queryKeys.subscription.all, "current"] as const,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
import { getServerURL } from "@/lib/utils";
|
|
||||||
|
|
||||||
interface CreateCheckoutParams {
|
|
||||||
billingPeriod: "monthly" | "annual";
|
|
||||||
csrfToken: string;
|
|
||||||
onSuccess?: (url: string) => void;
|
|
||||||
onError?: (error: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createCheckoutSession({
|
|
||||||
billingPeriod,
|
|
||||||
csrfToken,
|
|
||||||
onSuccess,
|
|
||||||
onError,
|
|
||||||
}: CreateCheckoutParams) {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${getServerURL()}/subscription/create-checkout-session`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"X-CSRF-Token": csrfToken,
|
|
||||||
},
|
|
||||||
credentials: "include",
|
|
||||||
body: JSON.stringify({ billingPeriod }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
onError?.(data.error || "Failed to create checkout session");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
onSuccess?.(data.url);
|
|
||||||
} catch (error) {
|
|
||||||
onError?.("Network error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { getServerURL } from "@/lib/utils";
|
|
||||||
|
|
||||||
interface CreatePortalParams {
|
|
||||||
csrfToken: string;
|
|
||||||
onSuccess?: (url: string) => void;
|
|
||||||
onError?: (error: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createPortalSession({ csrfToken, onSuccess, onError }: CreatePortalParams) {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${getServerURL()}/subscription/create-portal-session`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
"X-CSRF-Token": csrfToken,
|
|
||||||
},
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
onError?.(data.error || "Failed to create portal session");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
onSuccess?.(data.url);
|
|
||||||
} catch (error) {
|
|
||||||
onError?.("Network error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import type { SubscriptionRecord } from "@sprint/shared";
|
|
||||||
import { getServerURL } from "@/lib/utils";
|
|
||||||
|
|
||||||
interface GetSubscriptionParams {
|
|
||||||
onSuccess?: (subscription: SubscriptionRecord | null) => void;
|
|
||||||
onError?: (error: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getSubscription({ onSuccess, onError }: GetSubscriptionParams) {
|
|
||||||
try {
|
|
||||||
const response = await fetch(`${getServerURL()}/subscription/get`, {
|
|
||||||
method: "GET",
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
onError?.(data.error || "Failed to fetch subscription");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
onSuccess?.(data.subscription);
|
|
||||||
} catch (error) {
|
|
||||||
onError?.("Network error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { SubscriptionResponse } from "@sprint/shared";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, 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";
|
||||||
@@ -9,44 +10,37 @@ import { Switch } from "@/components/ui/switch";
|
|||||||
import { createCheckoutSession } from "@/lib/server/subscription/createCheckoutSession";
|
import { createCheckoutSession } from "@/lib/server/subscription/createCheckoutSession";
|
||||||
import { createPortalSession } from "@/lib/server/subscription/createPortalSession";
|
import { createPortalSession } from "@/lib/server/subscription/createPortalSession";
|
||||||
import { getSubscription } from "@/lib/server/subscription/getSubscription";
|
import { getSubscription } from "@/lib/server/subscription/getSubscription";
|
||||||
import { cn, getCsrfToken } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface SubscriptionData {
|
|
||||||
status: string;
|
|
||||||
currentPeriodEnd: Date | null;
|
|
||||||
quantity: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Plans() {
|
export default function Plans() {
|
||||||
const { user, isLoading } = useSession();
|
const { user, isLoading } = useSession();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [billingPeriod, setBillingPeriod] = useState<"monthly" | "annual">("annual");
|
const [billingPeriod, setBillingPeriod] = useState<"monthly" | "annual">("annual");
|
||||||
const [loginModalOpen, setLoginModalOpen] = useState(false);
|
const [loginModalOpen, setLoginModalOpen] = useState(false);
|
||||||
const [subscription, setSubscription] = useState<SubscriptionData | null>(null);
|
const [subscription, setSubscription] = useState<SubscriptionResponse | null>(null);
|
||||||
const [loadingSubscription, setLoadingSubscription] = useState(false);
|
|
||||||
const [processingTier, setProcessingTier] = useState<string | null>(null);
|
const [processingTier, setProcessingTier] = useState<string | null>(null);
|
||||||
|
|
||||||
// fetch subscription if user is logged in
|
// fetch subscription if user is logged in
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
setLoadingSubscription(true);
|
getSubscription()
|
||||||
getSubscription({
|
.then((result) => {
|
||||||
onSuccess: (data) => {
|
const data = result.data as { subscription?: SubscriptionResponse } | null;
|
||||||
setSubscription(data);
|
if (data?.subscription) {
|
||||||
setLoadingSubscription(false);
|
setSubscription(data.subscription);
|
||||||
},
|
} else {
|
||||||
onError: () => {
|
setSubscription(null);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
setSubscription(null);
|
setSubscription(null);
|
||||||
setLoadingSubscription(false);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
const hasProSubscription = subscription?.status === "active";
|
const hasProSubscription = subscription?.status === "active";
|
||||||
const csrfToken = getCsrfToken() || "";
|
|
||||||
|
|
||||||
const handleTierAction = (tierName: string) => {
|
const handleTierAction = async (tierName: string) => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
setLoginModalOpen(true);
|
setLoginModalOpen(true);
|
||||||
return;
|
return;
|
||||||
@@ -56,28 +50,23 @@ export default function Plans() {
|
|||||||
if (hasProSubscription) {
|
if (hasProSubscription) {
|
||||||
// open customer portal
|
// open customer portal
|
||||||
setProcessingTier(tierName);
|
setProcessingTier(tierName);
|
||||||
createPortalSession({
|
const result = await createPortalSession();
|
||||||
csrfToken,
|
const portalData = result.data as { url?: string } | null;
|
||||||
onSuccess: (url) => {
|
if (portalData?.url) {
|
||||||
window.location.href = url;
|
window.location.href = portalData.url;
|
||||||
},
|
} else {
|
||||||
onError: () => {
|
|
||||||
setProcessingTier(null);
|
setProcessingTier(null);
|
||||||
},
|
}
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
// start checkout
|
// start checkout
|
||||||
setProcessingTier(tierName);
|
setProcessingTier(tierName);
|
||||||
createCheckoutSession({
|
const result = await createCheckoutSession({ billingPeriod });
|
||||||
billingPeriod,
|
const checkoutData = result.data as { url?: string } | null;
|
||||||
csrfToken,
|
if (checkoutData?.url) {
|
||||||
onSuccess: (url) => {
|
window.location.href = checkoutData.url;
|
||||||
window.location.href = url;
|
} else {
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
setProcessingTier(null);
|
setProcessingTier(null);
|
||||||
},
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// starter tier - just go to issues if not already there
|
// starter tier - just go to issues if not already there
|
||||||
@@ -220,6 +209,33 @@ export default function Plans() {
|
|||||||
<p className="text-sm text-muted-foreground">30-day no-risk policy</p>
|
<p className="text-sm text-muted-foreground">30-day no-risk policy</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* FAQ */}
|
||||||
|
<div className="max-w-2xl mx-auto space-y-8 border-t pt-16">
|
||||||
|
<h2 className="text-3xl font-basteleur font-700 text-center">Frequently Asked Questions</h2>
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="font-700">Can I switch plans?</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Yes, you can upgrade or downgrade at any time. Changes take effect immediately.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="font-700">What happens when I add team members?</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Pro plan pricing scales with your team. Add or remove users anytime, and we'll adjust your
|
||||||
|
billing automatically.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<h3 className="font-700">Can I cancel my subscription?</h3>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Absolutely. Cancel anytime with no questions asked. You'll keep access until the end of your
|
||||||
|
billing period.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@@ -602,3 +602,48 @@ export const SuccessResponseSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export type SuccessResponse = z.infer<typeof SuccessResponseSchema>;
|
export type SuccessResponse = z.infer<typeof SuccessResponseSchema>;
|
||||||
|
|
||||||
|
// subscription schemas
|
||||||
|
|
||||||
|
export const CreateCheckoutSessionRequestSchema = z.object({
|
||||||
|
billingPeriod: z.enum(["monthly", "annual"]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateCheckoutSessionRequest = z.infer<typeof CreateCheckoutSessionRequestSchema>;
|
||||||
|
|
||||||
|
export const CreateCheckoutSessionResponseSchema = z.object({
|
||||||
|
url: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateCheckoutSessionResponse = z.infer<typeof CreateCheckoutSessionResponseSchema>;
|
||||||
|
|
||||||
|
export const CreatePortalSessionResponseSchema = z.object({
|
||||||
|
url: z.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreatePortalSessionResponse = z.infer<typeof CreatePortalSessionResponseSchema>;
|
||||||
|
|
||||||
|
export const SubscriptionRecordSchema = z.object({
|
||||||
|
id: z.number(),
|
||||||
|
userId: z.number(),
|
||||||
|
stripeCustomerId: z.string().nullable(),
|
||||||
|
stripeSubscriptionId: z.string().nullable(),
|
||||||
|
stripeSubscriptionItemId: z.string().nullable(),
|
||||||
|
stripePriceId: z.string().nullable(),
|
||||||
|
status: z.string(),
|
||||||
|
currentPeriodStart: z.string().nullable().optional(),
|
||||||
|
currentPeriodEnd: z.string().nullable().optional(),
|
||||||
|
cancelAtPeriodEnd: z.boolean(),
|
||||||
|
trialEnd: z.string().nullable().optional(),
|
||||||
|
quantity: z.number(),
|
||||||
|
createdAt: z.string().nullable().optional(),
|
||||||
|
updatedAt: z.string().nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type SubscriptionRecord = z.infer<typeof SubscriptionRecordSchema>;
|
||||||
|
|
||||||
|
export const GetSubscriptionResponseSchema = z.object({
|
||||||
|
subscription: SubscriptionRecordSchema.nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type GetSubscriptionResponse = z.infer<typeof GetSubscriptionResponseSchema>;
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ import { z } from "zod";
|
|||||||
import {
|
import {
|
||||||
ApiErrorSchema,
|
ApiErrorSchema,
|
||||||
AuthResponseSchema,
|
AuthResponseSchema,
|
||||||
|
CreateCheckoutSessionRequestSchema,
|
||||||
|
CreateCheckoutSessionResponseSchema,
|
||||||
|
CreatePortalSessionResponseSchema,
|
||||||
|
GetSubscriptionResponseSchema,
|
||||||
IssueByIdQuerySchema,
|
IssueByIdQuerySchema,
|
||||||
IssueCommentCreateRequestSchema,
|
IssueCommentCreateRequestSchema,
|
||||||
IssueCommentDeleteRequestSchema,
|
IssueCommentDeleteRequestSchema,
|
||||||
@@ -600,6 +604,38 @@ export const apiContract = c.router({
|
|||||||
200: z.array(timerListItemResponseSchema),
|
200: z.array(timerListItemResponseSchema),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
subscriptionCreateCheckoutSession: {
|
||||||
|
method: "POST",
|
||||||
|
path: "/subscription/create-checkout-session",
|
||||||
|
body: CreateCheckoutSessionRequestSchema,
|
||||||
|
responses: {
|
||||||
|
200: CreateCheckoutSessionResponseSchema,
|
||||||
|
400: ApiErrorSchema,
|
||||||
|
404: ApiErrorSchema,
|
||||||
|
500: ApiErrorSchema,
|
||||||
|
},
|
||||||
|
headers: csrfHeaderSchema,
|
||||||
|
},
|
||||||
|
subscriptionCreatePortalSession: {
|
||||||
|
method: "POST",
|
||||||
|
path: "/subscription/create-portal-session",
|
||||||
|
body: emptyBodySchema,
|
||||||
|
responses: {
|
||||||
|
200: CreatePortalSessionResponseSchema,
|
||||||
|
404: ApiErrorSchema,
|
||||||
|
500: ApiErrorSchema,
|
||||||
|
},
|
||||||
|
headers: csrfHeaderSchema,
|
||||||
|
},
|
||||||
|
subscriptionGet: {
|
||||||
|
method: "GET",
|
||||||
|
path: "/subscription/get",
|
||||||
|
responses: {
|
||||||
|
200: GetSubscriptionResponseSchema,
|
||||||
|
500: ApiErrorSchema,
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export type ApiContract = typeof apiContract;
|
export type ApiContract = typeof apiContract;
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
export type {
|
export type {
|
||||||
ApiError,
|
ApiError,
|
||||||
AuthResponse,
|
AuthResponse,
|
||||||
|
CreateCheckoutSessionRequest,
|
||||||
|
CreateCheckoutSessionResponse,
|
||||||
|
CreatePortalSessionResponse,
|
||||||
|
GetSubscriptionResponse,
|
||||||
IssueByIdQuery,
|
IssueByIdQuery,
|
||||||
IssueCommentCreateRequest,
|
IssueCommentCreateRequest,
|
||||||
IssueCommentDeleteRequest,
|
IssueCommentDeleteRequest,
|
||||||
@@ -46,6 +50,7 @@ export type {
|
|||||||
SprintsByProjectQuery,
|
SprintsByProjectQuery,
|
||||||
SprintUpdateRequest,
|
SprintUpdateRequest,
|
||||||
StatusCountResponse,
|
StatusCountResponse,
|
||||||
|
SubscriptionRecord as SubscriptionResponse,
|
||||||
SuccessResponse,
|
SuccessResponse,
|
||||||
TimerEndRequest,
|
TimerEndRequest,
|
||||||
TimerGetQuery,
|
TimerGetQuery,
|
||||||
@@ -62,6 +67,10 @@ export type {
|
|||||||
export {
|
export {
|
||||||
ApiErrorSchema,
|
ApiErrorSchema,
|
||||||
AuthResponseSchema,
|
AuthResponseSchema,
|
||||||
|
CreateCheckoutSessionRequestSchema,
|
||||||
|
CreateCheckoutSessionResponseSchema,
|
||||||
|
CreatePortalSessionResponseSchema,
|
||||||
|
GetSubscriptionResponseSchema,
|
||||||
IssueByIdQuerySchema,
|
IssueByIdQuerySchema,
|
||||||
IssueCommentCreateRequestSchema,
|
IssueCommentCreateRequestSchema,
|
||||||
IssueCommentDeleteRequestSchema,
|
IssueCommentDeleteRequestSchema,
|
||||||
@@ -110,6 +119,7 @@ export {
|
|||||||
SprintsByProjectQuerySchema,
|
SprintsByProjectQuerySchema,
|
||||||
SprintUpdateRequestSchema,
|
SprintUpdateRequestSchema,
|
||||||
StatusCountResponseSchema,
|
StatusCountResponseSchema,
|
||||||
|
SubscriptionRecordSchema as SubscriptionRecordApiSchema,
|
||||||
SuccessResponseSchema,
|
SuccessResponseSchema,
|
||||||
TimerEndRequestSchema,
|
TimerEndRequestSchema,
|
||||||
TimerGetQuerySchema,
|
TimerGetQuerySchema,
|
||||||
@@ -165,7 +175,7 @@ export type {
|
|||||||
SprintInsert,
|
SprintInsert,
|
||||||
SprintRecord,
|
SprintRecord,
|
||||||
SubscriptionInsert,
|
SubscriptionInsert,
|
||||||
SubscriptionRecord,
|
SubscriptionRecord as SubscriptionRecordType,
|
||||||
TimedSessionInsert,
|
TimedSessionInsert,
|
||||||
TimedSessionRecord,
|
TimedSessionRecord,
|
||||||
TimerState,
|
TimerState,
|
||||||
|
|||||||
Reference in New Issue
Block a user