feat: billing portal
This commit is contained in:
@@ -43,7 +43,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
<div className="flex w-full flex-col gap-1">
|
||||
<div className="relative flex">
|
||||
{prefix && (
|
||||
<div className="flex shrink-0 items-center rounded-l-md border border-r-0 border-light-600 px-3 text-base dark:border-dark-700 sm:text-sm/6">
|
||||
<div className="flex shrink-0 items-center rounded-l-md border border-r-0 border-light-600 px-3 text-base dark:border-dark-700 dark:text-dark-1000 sm:text-sm/6">
|
||||
{prefix}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -22,12 +22,17 @@ export default function WorkspaceMenu() {
|
||||
<Menu.Button className="mb-1 flex w-full items-center rounded-[5px] p-1.5 hover:bg-light-200 dark:hover:bg-dark-200">
|
||||
<span className="inline-flex h-6 w-6 items-center justify-center rounded-[5px] bg-indigo-700">
|
||||
<span className="text-xs font-bold leading-none text-white">
|
||||
{workspace?.name.charAt(0).toUpperCase()}
|
||||
{workspace.name.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</span>
|
||||
<span className="ml-2 text-sm font-bold text-neutral-900 dark:text-dark-1000">
|
||||
{workspace?.name}
|
||||
{workspace.name}
|
||||
</span>
|
||||
{workspace.plan === "pro" && (
|
||||
<span className="ml-2 inline-flex items-center rounded-md bg-indigo-100 px-2 py-1 text-[10px] font-medium text-indigo-700">
|
||||
Pro
|
||||
</span>
|
||||
)}
|
||||
</Menu.Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -53,14 +58,14 @@ export default function WorkspaceMenu() {
|
||||
<div>
|
||||
<span className="inline-flex h-5 w-5 items-center justify-center rounded-[5px] bg-indigo-700">
|
||||
<span className="text-xs font-medium leading-none text-white">
|
||||
{availableWorkspace?.name.charAt(0).toUpperCase()}
|
||||
{availableWorkspace.name.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
</span>
|
||||
<span className="ml-2 text-xs font-medium">
|
||||
{availableWorkspace?.name}
|
||||
{availableWorkspace.name}
|
||||
</span>
|
||||
</div>
|
||||
{workspace?.name === availableWorkspace?.name && (
|
||||
{workspace.name === availableWorkspace.name && (
|
||||
<span>
|
||||
<HiCheck className="h-4 w-4" aria-hidden="true" />
|
||||
</span>
|
||||
|
||||
73
apps/web/src/pages/api/stripe/create_billing_session.ts
Normal file
73
apps/web/src/pages/api/stripe/create_billing_session.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import { NextResponse } from "next/server";
|
||||
import { Stripe } from "stripe";
|
||||
|
||||
import * as userRepo from "@kan/db/repository/user.repo";
|
||||
import { createNextClient } from "@kan/supabase/clients";
|
||||
|
||||
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
|
||||
|
||||
if (!stripeSecretKey) {
|
||||
throw new Error("STRIPE_SECRET_KEY is not defined");
|
||||
}
|
||||
|
||||
const stripe = new Stripe(stripeSecretKey, {
|
||||
apiVersion: "2024-12-18.acacia",
|
||||
});
|
||||
|
||||
export default async function handler(req: NextRequest) {
|
||||
if (req.method !== "POST") {
|
||||
return new Response(JSON.stringify({ error: "Method not allowed" }), {
|
||||
status: 405,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const response = NextResponse.next();
|
||||
const db = createNextClient(req, response);
|
||||
const { data } = await db.auth.getUser();
|
||||
|
||||
if (!data.user) {
|
||||
return new Response(JSON.stringify({ error: "Unauthorized" }), {
|
||||
status: 403,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
const user = await userRepo.getById(db, data.user.id);
|
||||
|
||||
if (!user?.stripeCustomerId) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "No billing account found" }),
|
||||
{
|
||||
status: 404,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const session = await stripe.billingPortal.sessions.create({
|
||||
customer: user.stripeCustomerId,
|
||||
return_url: `${process.env.WEBSITE_URL}/settings`,
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify({ url: session.url }), {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Error creating portal session" }),
|
||||
{
|
||||
status: 500,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const runtime = "edge";
|
||||
export const preferredRegion = "lhr1";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -60,6 +60,7 @@ export default async function handler(req: NextRequest) {
|
||||
metaData.workspacePublicId,
|
||||
undefined,
|
||||
metaData.username,
|
||||
"pro",
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -15,12 +15,14 @@ interface Workspace {
|
||||
name: string;
|
||||
publicId: string;
|
||||
slug: string;
|
||||
plan: "free" | "pro" | "enterprise";
|
||||
}
|
||||
|
||||
const initialWorkspace: Workspace = {
|
||||
name: "",
|
||||
publicId: "",
|
||||
slug: "",
|
||||
plan: "free",
|
||||
};
|
||||
|
||||
const initialAvailableWorkspaces: Workspace[] = [];
|
||||
@@ -63,6 +65,7 @@ export const WorkspaceProvider: React.FC<{ children: ReactNode }> = ({
|
||||
publicId: workspace.publicId,
|
||||
name: workspace.name,
|
||||
slug: workspace.slug,
|
||||
plan: workspace.plan,
|
||||
};
|
||||
})
|
||||
.filter((workspace) => workspace !== null) as Workspace[];
|
||||
@@ -82,6 +85,7 @@ export const WorkspaceProvider: React.FC<{ children: ReactNode }> = ({
|
||||
publicId: selectedWorkspace.workspace.publicId,
|
||||
name: selectedWorkspace.workspace.name,
|
||||
slug: selectedWorkspace.workspace.slug,
|
||||
plan: selectedWorkspace.workspace.plan,
|
||||
});
|
||||
} else {
|
||||
const primaryWorkspace = data[0]?.workspace;
|
||||
@@ -91,6 +95,7 @@ export const WorkspaceProvider: React.FC<{ children: ReactNode }> = ({
|
||||
publicId: primaryWorkspace.publicId,
|
||||
name: primaryWorkspace.name,
|
||||
slug: primaryWorkspace.slug,
|
||||
plan: primaryWorkspace.plan,
|
||||
});
|
||||
}
|
||||
}, [data]);
|
||||
|
||||
@@ -27,9 +27,11 @@ type FormValues = z.infer<typeof schema>;
|
||||
const UpdateWorkspaceUrlForm = ({
|
||||
workspacePublicId,
|
||||
workspaceUrl,
|
||||
workspacePlan,
|
||||
}: {
|
||||
workspacePublicId: string;
|
||||
workspaceUrl: string;
|
||||
workspacePlan: "free" | "pro" | "enterprise";
|
||||
}) => {
|
||||
const utils = api.useUtils();
|
||||
const { showPopup } = usePopup();
|
||||
@@ -84,7 +86,7 @@ const UpdateWorkspaceUrlForm = ({
|
||||
const isWorkspaceSlugAvailable = checkWorkspaceSlugAvailability.data;
|
||||
|
||||
const onSubmit = (data: FormValues) => {
|
||||
if (isWorkspaceSlugAvailable?.isPremium)
|
||||
if (isWorkspaceSlugAvailable?.isPremium && workspacePlan !== "pro")
|
||||
return openModal("PREMIUM_USERNAME", data.slug);
|
||||
|
||||
updateWorkspaceSlug.mutate({
|
||||
@@ -99,7 +101,10 @@ const UpdateWorkspaceUrlForm = ({
|
||||
<Input
|
||||
{...register("slug")}
|
||||
className={`${
|
||||
isWorkspaceSlugAvailable?.isPremium ? "focus:ring-yellow-500" : ""
|
||||
isWorkspaceSlugAvailable?.isPremium ||
|
||||
(workspacePlan === "pro" && slug === workspaceUrl)
|
||||
? "focus:ring-yellow-500 dark:focus:ring-yellow-500"
|
||||
: ""
|
||||
}`}
|
||||
errorMessage={
|
||||
errors.slug?.message ||
|
||||
@@ -109,10 +114,11 @@ const UpdateWorkspaceUrlForm = ({
|
||||
}
|
||||
prefix="kan.bn/"
|
||||
iconRight={
|
||||
isWorkspaceSlugAvailable?.isPremium ? (
|
||||
isWorkspaceSlugAvailable?.isPremium ||
|
||||
(workspacePlan === "pro" && slug === workspaceUrl) ? (
|
||||
<HiMiniStar className="h-4 w-4 text-yellow-500" />
|
||||
) : isWorkspaceSlugAvailable?.isAvailable ? (
|
||||
<HiCheck className="h-4 w-4" />
|
||||
<HiCheck className="h-4 w-4 dark:text-dark-1000" />
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { HiMiniArrowTopRightOnSquare } from "react-icons/hi2";
|
||||
|
||||
import Button from "~/components/Button";
|
||||
import Modal from "~/components/modal";
|
||||
import { NewWorkspaceForm } from "~/components/NewWorkspaceForm";
|
||||
import { PageHead } from "~/components/PageHead";
|
||||
import { useModal } from "~/providers/modal";
|
||||
import { useWorkspace } from "~/providers/workspace";
|
||||
@@ -12,60 +15,101 @@ export default function SettingsPage() {
|
||||
const { modalContentType, openModal } = useModal();
|
||||
const { workspace } = useWorkspace();
|
||||
|
||||
const handleOpenBillingPortal = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/stripe/create_billing_session", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
const { url } = (await response.json()) as { url: string };
|
||||
|
||||
if (url) {
|
||||
window.location.href = url;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating billing session:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHead title={`Settings | ${workspace.name ?? "Workspace"}`} />
|
||||
<div className="px-28 py-12">
|
||||
<div className="mb-8 flex w-full justify-between">
|
||||
<h1 className="font-medium tracking-tight text-neutral-900 dark:text-dark-1000 sm:text-[1.2rem]">
|
||||
Settings
|
||||
</h1>
|
||||
<div className="flex h-full w-full flex-col overflow-hidden">
|
||||
<div className="h-full max-h-[calc(100vh-4rem)] overflow-y-auto">
|
||||
<PageHead title={`Settings | ${workspace.name ?? "Workspace"}`} />
|
||||
<div className="px-28 py-12">
|
||||
<div className="mb-8 flex w-full justify-between">
|
||||
<h1 className="font-medium tracking-tight text-neutral-900 dark:text-dark-1000 sm:text-[1.2rem]">
|
||||
Settings
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 border-t border-light-300 dark:border-dark-300">
|
||||
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Workspace name
|
||||
</h2>
|
||||
<UpdateWorkspaceNameForm
|
||||
workspacePublicId={workspace.publicId}
|
||||
workspaceName={workspace.name}
|
||||
/>
|
||||
|
||||
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Workspace username
|
||||
</h2>
|
||||
<UpdateWorkspaceUrlForm
|
||||
workspacePublicId={workspace.publicId}
|
||||
workspaceUrl={workspace.slug}
|
||||
workspacePlan={workspace.plan}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 border-t border-light-300 dark:border-dark-300">
|
||||
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Billing
|
||||
</h2>
|
||||
<p className="mb-8 text-sm text-neutral-500 dark:text-dark-900">
|
||||
View and manage your billing and subscription.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
iconRight={<HiMiniArrowTopRightOnSquare />}
|
||||
onClick={handleOpenBillingPortal}
|
||||
>
|
||||
Billing portal
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-light-300 dark:border-dark-300">
|
||||
<h2 className="mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Delete workspace
|
||||
</h2>
|
||||
<p className="mb-8 mt-2 text-sm text-neutral-500 dark:text-dark-900">
|
||||
Once you delete your workspace, there is no going back. Please
|
||||
be certain.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => openModal("DELETE_WORKSPACE")}
|
||||
>
|
||||
Delete workspace
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal>
|
||||
{modalContentType === "NEW_WORKSPACE" && <NewWorkspaceForm />}
|
||||
{modalContentType === "DELETE_WORKSPACE" && (
|
||||
<DeleteWorkspaceConfirmation />
|
||||
)}
|
||||
{modalContentType === "PREMIUM_USERNAME" && (
|
||||
<PremiumUsernameConfirmation
|
||||
workspacePublicId={workspace.publicId}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
|
||||
<div className="mb-8 border-t border-light-300 dark:border-dark-300">
|
||||
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Workspace name
|
||||
</h2>
|
||||
<UpdateWorkspaceNameForm
|
||||
workspacePublicId={workspace.publicId}
|
||||
workspaceName={workspace.name}
|
||||
/>
|
||||
|
||||
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Workspace username
|
||||
</h2>
|
||||
<UpdateWorkspaceUrlForm
|
||||
workspacePublicId={workspace.publicId}
|
||||
workspaceUrl={workspace.slug}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-light-300 dark:border-dark-300">
|
||||
<h2 className="mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
|
||||
Delete workspace
|
||||
</h2>
|
||||
<p className="mb-8 mt-2 text-sm text-neutral-500 dark:text-dark-900">
|
||||
Once you delete your workspace, there is no going back. Please be
|
||||
certain.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => openModal("DELETE_WORKSPACE")}
|
||||
>
|
||||
Delete workspace
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Modal>
|
||||
{modalContentType === "DELETE_WORKSPACE" && (
|
||||
<DeleteWorkspaceConfirmation />
|
||||
)}
|
||||
{modalContentType === "PREMIUM_USERNAME" && (
|
||||
<PremiumUsernameConfirmation
|
||||
workspacePublicId={workspace.publicId}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -126,6 +126,31 @@ export const workspaceRouter = createTRPCRouter({
|
||||
)
|
||||
.output(z.custom<Awaited<ReturnType<typeof workspaceRepo.update>>>())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.slug) {
|
||||
const workspace = await workspaceRepo.getByPublicId(
|
||||
ctx.db,
|
||||
input.workspacePublicId,
|
||||
);
|
||||
|
||||
const reservedOrPremiumWorkspaceSlug =
|
||||
await workspaceSlugRepo.getWorkspaceSlug(ctx.db, input.slug);
|
||||
|
||||
const isWorkspaceSlugAvailable =
|
||||
await workspaceRepo.isWorkspaceSlugAvailable(ctx.db, input.slug);
|
||||
|
||||
if (
|
||||
reservedOrPremiumWorkspaceSlug?.type === "reserved" ||
|
||||
(workspace?.plan !== "pro" &&
|
||||
reservedOrPremiumWorkspaceSlug?.type === "premium") ||
|
||||
!isWorkspaceSlugAvailable
|
||||
) {
|
||||
throw new TRPCError({
|
||||
message: `Workspace slug already taken`,
|
||||
code: "CONFLICT",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = await workspaceRepo.update(
|
||||
ctx.db,
|
||||
input.workspacePublicId,
|
||||
|
||||
2
packages/db/migrations/0002_bored_retro_girl.sql
Normal file
2
packages/db/migrations/0002_bored_retro_girl.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
CREATE TYPE "public"."workspace_plan" AS ENUM('free', 'pro', 'enterprise');--> statement-breakpoint
|
||||
ALTER TABLE "workspace" ADD COLUMN "plan" "workspace_plan" DEFAULT 'free' NOT NULL;
|
||||
1508
packages/db/migrations/meta/0002_snapshot.json
Normal file
1508
packages/db/migrations/meta/0002_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,13 @@
|
||||
"when": 1735821726274,
|
||||
"tag": "0001_little_red_hulk",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1735904544867,
|
||||
"tag": "0002_bored_retro_girl",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -44,10 +44,11 @@ export const update = async (
|
||||
workspacePublicId: string,
|
||||
name: string | undefined,
|
||||
slug: string | undefined,
|
||||
plan?: "free" | "pro" | "enterprise",
|
||||
) => {
|
||||
const { data } = await db
|
||||
.from("workspace")
|
||||
.update({ name, slug })
|
||||
.update({ name, slug, plan })
|
||||
.eq("publicId", workspacePublicId)
|
||||
.is("deletedAt", null);
|
||||
|
||||
@@ -60,7 +61,7 @@ export const getByPublicId = async (
|
||||
) => {
|
||||
const { data } = await db
|
||||
.from("workspace")
|
||||
.select(`id, publicId, name`)
|
||||
.select(`id, publicId, name, plan`)
|
||||
.is("deletedAt", null)
|
||||
.eq("publicId", workspacePublicId)
|
||||
.limit(1)
|
||||
@@ -112,7 +113,8 @@ export const getAllByUserId = async (
|
||||
workspace (
|
||||
publicId,
|
||||
name,
|
||||
slug
|
||||
slug,
|
||||
plan
|
||||
)
|
||||
`,
|
||||
)
|
||||
|
||||
@@ -40,6 +40,11 @@ export const activityTypeEnum = pgEnum("card_activity_type", [
|
||||
"card.archived",
|
||||
]);
|
||||
export const slugTypeEnum = pgEnum("slug_type", ["reserved", "premium"]);
|
||||
export const workspacePlanEnum = pgEnum("workspace_plan", [
|
||||
"free",
|
||||
"pro",
|
||||
"enterprise",
|
||||
]);
|
||||
|
||||
export const boards = pgTable("board", {
|
||||
id: bigserial("id", { mode: "number" }).primaryKey(),
|
||||
@@ -289,6 +294,7 @@ export const workspaces = pgTable("workspace", {
|
||||
publicId: varchar("publicId", { length: 12 }).notNull().unique(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
slug: varchar("slug", { length: 255 }).notNull().unique(),
|
||||
plan: workspacePlanEnum("plan").notNull().default("free"),
|
||||
createdBy: uuid("createdBy")
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user