feat: premium workspace usernames

This commit is contained in:
Henry
2025-01-02 20:40:29 +00:00
parent b5dc9433db
commit 67e714b8b0
41 changed files with 1767 additions and 9088 deletions

View File

@@ -5,8 +5,10 @@ import { twMerge } from "tailwind-merge";
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
contentEditable?: boolean;
prefix?: string;
iconRight?: React.ReactNode;
value?: string;
errorMessage?: string;
className?: string;
onChange?: (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
) => void;
@@ -14,7 +16,16 @@ interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
const Input = forwardRef<HTMLInputElement, InputProps>(
(
{ contentEditable, errorMessage, prefix, value, onChange, ...props },
{
contentEditable,
errorMessage,
prefix,
value,
onChange,
iconRight,
className,
...props
},
ref,
) => {
if (contentEditable) {
@@ -30,7 +41,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
return (
<div className="flex w-full flex-col gap-1">
<div className="flex">
<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">
{prefix}
@@ -42,9 +53,15 @@ const Input = forwardRef<HTMLInputElement, InputProps>(
className={twMerge(
"block w-full rounded-md border-0 bg-dark-300 bg-white/5 py-1.5 shadow-sm ring-1 ring-inset ring-light-600 placeholder:text-dark-800 focus:ring-2 focus:ring-inset focus:ring-light-700 dark:text-dark-1000 dark:ring-dark-700 dark:focus:ring-dark-700 sm:text-sm sm:leading-6",
prefix && "rounded-l-none",
className && className,
)}
{...props}
/>
{iconRight && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
{iconRight}
</div>
)}
</div>
{errorMessage && (
<div className="text-xs text-red-500">{errorMessage}</div>

View File

@@ -15,6 +15,7 @@ export const env = createEnv({
*/
server: {
POSTGRES_URL: z.string().url(),
STRIPE_SECRET_KEY: z.string().optional(),
},
/**

View File

@@ -0,0 +1,23 @@
import { useEffect, useState } from "react";
/**
* A hook that delays updating a value until a specified delay has passed
* @param value The value to debounce
* @param delay The delay in milliseconds
* @returns The debounced value
*/
export function useDebounce<T>(value: T, delay: number): [T] {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timeoutId);
};
}, [value, delay]);
return [debouncedValue];
}

View File

@@ -1,11 +1,22 @@
import type { EmailOtpType } from "@supabase/supabase-js";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { Stripe } from "stripe";
import * as memberRepo from "@kan/db/repository/member.repo";
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 !== "GET") {
return new NextResponse(null, {
@@ -54,9 +65,17 @@ export default async function handler(req: NextRequest) {
const existingUser = await userRepo.getById(db, user.id);
if (!existingUser) {
const stripeCustomer = await stripe.customers.create({
email: user.email,
metadata: {
userId: user.id,
},
});
await userRepo.create(db, {
id: user.id,
email: user.email,
stripeCustomerId: stripeCustomer.id,
});
}
}

View File

@@ -0,0 +1,135 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { Stripe } from "stripe";
import { z } from "zod";
import * as userRepo from "@kan/db/repository/user.repo";
import * as workspaceRepo from "@kan/db/repository/workspace.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",
});
const usernameSchema = z
.string()
.min(3)
.max(24)
.regex(/^(?![-]+$)[a-zA-Z0-9-]+$/);
interface CheckoutSessionRequest {
successUrl: string;
cancelUrl: string;
username: string;
workspacePublicId: string;
stripeCustomerId: string;
}
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) {
return new Response(JSON.stringify({ error: "User not found" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
const body = (await req.json()) as CheckoutSessionRequest;
const { successUrl, cancelUrl, username, workspacePublicId } = body;
if (!successUrl || !cancelUrl || !username || !workspacePublicId) {
return new Response(
JSON.stringify({ error: "Missing required fields" }),
{
status: 400,
headers: { "Content-Type": "application/json" },
},
);
}
const usernameResult = usernameSchema.safeParse(username);
if (!usernameResult.success) {
return new Response(JSON.stringify({ error: "Invalid username" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
const workspace = await workspaceRepo.getAllByUserId(db, user.id);
const isMemberOfWorkspace = workspace.some(
({ workspace }) => workspace?.publicId === body.workspacePublicId,
);
if (!isMemberOfWorkspace) {
return new Response(JSON.stringify({ error: "Unauthorized" }), {
status: 403,
headers: { "Content-Type": "application/json" },
});
}
const session = await stripe.checkout.sessions.create({
mode: "subscription",
line_items: [
{
price: "price_1QcpmyDlDJBL8JHbeqhe1Ruq",
quantity: 1,
},
],
success_url: `${process.env.WEBSITE_URL}${successUrl}`,
cancel_url: `${process.env.WEBSITE_URL}${cancelUrl}`,
customer: user.stripeCustomerId ?? undefined,
metadata: {
username,
workspacePublicId,
},
});
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 checkout session" }),
{
status: 500,
headers: { "Content-Type": "application/json" },
},
);
}
}
export const runtime = "edge";
export const preferredRegion = "lhr1";
export const dynamic = "force-dynamic";

View File

@@ -0,0 +1,82 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { Stripe } from "stripe";
import * as workspaceRepo from "@kan/db/repository/workspace.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");
}
export const webCrypto = Stripe.createSubtleCryptoProvider();
const stripe: Stripe = new Stripe(stripeSecretKey, {
apiVersion: "2024-12-18.acacia",
httpClient: Stripe.createFetchHttpClient(),
});
export default async function handler(req: NextRequest) {
if (req.method !== "POST") {
return new Response(JSON.stringify({ message: "Method not allowed" }), {
status: 405,
});
}
const sig = req.headers.get("stripe-signature");
if (!sig) {
return new Response(JSON.stringify({ message: "No signature found" }), {
status: 400,
});
}
try {
const body = await req.text();
const event = await stripe.webhooks.constructEventAsync(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET!,
undefined,
webCrypto,
);
const response = NextResponse.next();
const db = createNextClient(req, response);
switch (event.type) {
case "checkout.session.completed": {
const checkoutSession = event.data.object;
const metaData = checkoutSession.metadata;
if (metaData?.workspacePublicId && metaData.username) {
await workspaceRepo.update(
db,
metaData.workspacePublicId,
undefined,
metaData.username,
);
}
break;
}
default:
console.log(`Unhandled event type: ${event.type}`);
}
return new Response(JSON.stringify({ received: true }), { status: 200 });
} catch (err) {
console.error("Webhook error:", err);
return new Response(JSON.stringify({ message: "Webhook handler failed" }), {
status: 400,
});
}
}
export const runtime = "edge";
export const preferredRegion = "lhr1";
export const dynamic = "force-dynamic";

View File

@@ -1,19 +1,16 @@
import { HiOutlinePlusSmall, HiEllipsisHorizontal } from "react-icons/hi2";
import { HiEllipsisHorizontal, HiOutlinePlusSmall } from "react-icons/hi2";
import { twMerge } from "tailwind-merge";
import Dropdown from "~/components/Dropdown";
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";
import { PageHead } from "~/components/PageHead";
import Modal from "~/components/modal";
import { NewWorkspaceForm } from "~/components/NewWorkspaceForm";
import { InviteMemberForm } from "./components/InviteMemberForm";
import { DeleteMemberConfirmation } from "./components/DeleteMemberConfirmation";
import Dropdown from "~/components/Dropdown";
import { api } from "~/utils/api";
import { getInitialsFromName, inferInitialsFromEmail } from "~/utils/helpers";
import { DeleteMemberConfirmation } from "./components/DeleteMemberConfirmation";
import { InviteMemberForm } from "./components/InviteMemberForm";
export default function MembersPage() {
const { modalContentType, openModal } = useModal();
@@ -24,6 +21,25 @@ export default function MembersPage() {
// { enabled: workspace?.publicId ? true : false },
);
const handleUpgrade = async () => {
try {
const response = await fetch("/api/stripe/create_checkout_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 checkout session:", error);
}
};
const TableRow = ({
memberPublicId,
memberName,
@@ -139,7 +155,7 @@ export default function MembersPage() {
return (
<>
<PageHead title={`Members | ${workspace?.name ?? "Workspace"}`} />
<PageHead title={`Members | ${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]">
@@ -149,7 +165,7 @@ export default function MembersPage() {
<button
type="button"
className="flex items-center gap-x-1.5 rounded-md bg-light-1000 px-3 py-2 text-sm font-semibold text-light-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 dark:bg-dark-1000 dark:text-dark-50"
onClick={() => openModal("INVITE_MEMBER")}
onClick={() => handleUpgrade()}
>
<div className="h-5 w-5 items-center">
<HiOutlinePlusSmall
@@ -189,8 +205,8 @@ export default function MembersPage() {
<TableRow
key={member.publicId}
memberPublicId={member.publicId}
memberName={member?.user?.name}
memberEmail={member?.user?.email}
memberName={member.user?.name}
memberEmail={member.user?.email}
memberRole={member.role}
memberStatus={member.status}
isLastRow={index === data.members.length - 1}

View File

@@ -0,0 +1,56 @@
import Button from "~/components/Button";
import { useModal } from "~/providers/modal";
export function PremiumUsernameConfirmation({
workspacePublicId,
}: {
workspacePublicId: string;
}) {
const { closeModal, entityId } = useModal();
const handleUpgrade = async () => {
try {
const response = await fetch("/api/stripe/create_checkout_session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: entityId,
workspacePublicId: workspacePublicId,
cancelUrl: "/settings",
successUrl: "/settings",
}),
});
const { url } = (await response.json()) as { url: string };
if (url) {
window.location.href = url;
}
} catch (error) {
console.error("Error creating checkout session:", error);
}
};
return (
<div className="p-5">
<div className="flex w-full flex-col justify-between pb-4">
<h2 className="text-md pb-4 font-medium text-neutral-900 dark:text-dark-1000">
{`Confirm username change`}
</h2>
<p className="text-sm font-medium text-light-900 dark:text-dark-900">
{
"As you are changing from a standard to a premium username, you will be taken to the checkout to upgrade."
}
</p>
</div>
<div className="mt-5 flex justify-end space-x-2 sm:mt-6">
<Button onClick={() => closeModal()} variant="secondary">
Cancel
</Button>
<Button onClick={handleUpgrade}>Upgrade</Button>
</div>
</div>
);
}

View File

@@ -1,17 +1,25 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { HiCheck, HiMiniStar } from "react-icons/hi2";
import { z } from "zod";
import Button from "~/components/Button";
import Input from "~/components/Input";
import { useDebounce } from "~/hooks/useDebounce";
import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api";
const schema = z.object({
slug: z
.string()
.min(3, { message: "Workspace URL must be at least 3 characters long" })
.max(24, { message: "Workspace URL cannot exceed 24 characters" }),
.min(3, {
message: "Username must be at least 3 characters long",
})
.max(24, { message: "Username cannot exceed 24 characters" })
.regex(/^(?![-]+$)[a-zA-Z0-9-]+$/, {
message: "Username can only contain letters, numbers, and hyphens",
}),
});
type FormValues = z.infer<typeof schema>;
@@ -25,17 +33,22 @@ const UpdateWorkspaceUrlForm = ({
}) => {
const utils = api.useUtils();
const { showPopup } = usePopup();
const { openModal } = useModal();
const {
register,
handleSubmit,
formState: { isDirty, errors },
watch,
} = useForm<FormValues>({
resolver: zodResolver(schema),
values: {
slug: workspaceUrl,
},
mode: "onChange",
});
const slug = watch("slug");
const updateWorkspaceSlug = api.workspace.update.useMutation({
onSuccess: async () => {
try {
@@ -47,13 +60,33 @@ const UpdateWorkspaceUrlForm = ({
},
onError: () => {
showPopup({
header: "Error updating workspace URL",
header: "Error updating workspace username",
message: "Please try again later, or contact customer support.",
});
},
});
const [debouncedSlug] = useDebounce(slug, 500);
const isTyping = slug !== debouncedSlug;
const checkWorkspaceSlugAvailability =
api.workspace.checkSlugAvailability.useQuery(
{
workspaceSlug: debouncedSlug,
},
{
enabled:
!!debouncedSlug && debouncedSlug !== workspaceUrl && !errors.slug,
},
);
const isWorkspaceSlugAvailable = checkWorkspaceSlugAvailability.data;
const onSubmit = (data: FormValues) => {
if (isWorkspaceSlugAvailable?.isPremium)
return openModal("PREMIUM_USERNAME", data.slug);
updateWorkspaceSlug.mutate({
workspacePublicId,
slug: data.slug,
@@ -65,14 +98,35 @@ const UpdateWorkspaceUrlForm = ({
<div className="mb-4 flex max-w-[350px] items-center gap-2">
<Input
{...register("slug")}
errorMessage={errors.slug?.message}
prefix="kanbn.com/"
className={`${
isWorkspaceSlugAvailable?.isPremium ? "focus:ring-yellow-500" : ""
}`}
errorMessage={
errors.slug?.message ||
(isWorkspaceSlugAvailable?.isAvailable === false
? "This workspace username has already been taken"
: undefined)
}
prefix="kan.bn/"
iconRight={
isWorkspaceSlugAvailable?.isPremium ? (
<HiMiniStar className="h-4 w-4 text-yellow-500" />
) : isWorkspaceSlugAvailable?.isAvailable ? (
<HiCheck className="h-4 w-4" />
) : null
}
/>
</div>
<Button
onClick={handleSubmit(onSubmit)}
variant="primary"
disabled={!isDirty || updateWorkspaceSlug.isPending}
disabled={
!isDirty ||
updateWorkspaceSlug.isPending ||
checkWorkspaceSlugAvailability.isPending ||
isWorkspaceSlugAvailable?.isAvailable === false ||
isTyping
}
isLoading={updateWorkspaceSlug.isPending}
>
Update

View File

@@ -4,6 +4,7 @@ import { PageHead } from "~/components/PageHead";
import { useModal } from "~/providers/modal";
import { useWorkspace } from "~/providers/workspace";
import { DeleteWorkspaceConfirmation } from "./components/DeleteWorkspaceConfirmation";
import { PremiumUsernameConfirmation } from "./components/PremiumUsernameConfirmation";
import UpdateWorkspaceNameForm from "./components/UpdateWorkspaceNameForm";
import UpdateWorkspaceUrlForm from "./components/UpdateWorkspaceUrlForm";
@@ -31,7 +32,7 @@ export default function SettingsPage() {
/>
<h2 className="mb-4 mt-8 text-[14px] text-neutral-900 dark:text-dark-1000">
Workspace URL
Workspace username
</h2>
<UpdateWorkspaceUrlForm
workspacePublicId={workspace.publicId}
@@ -59,6 +60,11 @@ export default function SettingsPage() {
{modalContentType === "DELETE_WORKSPACE" && (
<DeleteWorkspaceConfirmation />
)}
{modalContentType === "PREMIUM_USERNAME" && (
<PremiumUsernameConfirmation
workspacePublicId={workspace.publicId}
/>
)}
</Modal>
</div>
</>