Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

web: new onboarding (#1188)

Ameer Al Ashhab7c12ca726547
diff --git a/apps/web/actions/organization/upload-organization-icon.ts b/apps/web/actions/organization/upload-organization-icon.ts
index 3ab598900..72fec848e 100644
--- a/apps/web/actions/organization/upload-organization-icon.ts
+++ b/apps/web/actions/organization/upload-organization-icon.ts
@@ -6,10 +6,8 @@ import { organizations } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import { S3Buckets } from "@cap/web-backend";
import type { Organisation } from "@cap/web-domain";
-import DOMPurify from "dompurify";
import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
-import { JSDOM } from "jsdom";
import { revalidatePath } from "next/cache";
import { sanitizeFile } from "@/lib/sanitizeFile";
import { runPromise } from "@/lib/server";
@@ -37,7 +35,7 @@ export async function uploadOrganizationIcon(
throw new Error("Only the owner can update organization icon");
}
- const file = formData.get("file") as File;
+ const file = formData.get("icon") as File | null;
if (!file) {
throw new Error("No file provided");
@@ -64,11 +62,12 @@ export async function uploadOrganizationIcon(
await Effect.gen(function* () {
const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
- yield* bucket.putObject(
- fileKey,
- yield* Effect.promise(() => sanitizedFile.bytes()),
- { contentType: file.type },
- );
+ const bodyBytes = yield* Effect.promise(async () => {
+ const buf = await sanitizedFile.arrayBuffer();
+ return new Uint8Array(buf);
+ });
+
+ yield* bucket.putObject(fileKey, bodyBytes, { contentType: file.type });
// Construct the icon URL
if (serverEnv().CAP_AWS_BUCKET_URL) {
// If a custom bucket URL is defined, use it
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
index 6c2aca433..f0eaffb8f 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
@@ -49,7 +49,6 @@ interface Props {
const AdminNavItems = ({ toggleMobileNav }: Props) => {
const pathname = usePathname();
const [open, setOpen] = useState(false);
- const [hoveredItem, setHoveredItem] = useState<string | null>(null);
const { user, sidebarCollapsed, userCapsCount } = useDashboardContext();
const manageNavigation = [
@@ -221,7 +220,7 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
? "pointer-events-none"
: "text-gray-10 hover:text-gray-12 hover:bg-gray-6",
)}
- key={`${organization.organization.name}-organization`}
+ key={`${organization.organization.name}-organization-${organization.organization.id}`}
onSelect={async () => {
await updateActiveOrganization(
organization.organization.id,
@@ -323,23 +322,6 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
/>
)}
- {hoveredItem === item.name && !isPathActive(item.href) && (
- <motion.div
- layoutId="hoverIndicator"
- className={clsx(
- "absolute bg-transparent rounded-xl",
- sidebarCollapsed ? "inset-0 mx-auto w-9 h-9" : "inset-0",
- )}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{
- type: "spring",
- bounce: 0.2,
- duration: 0.2,
- }}
- />
- )}
<NavItem
name={item.name}
href={item.href}
diff --git a/apps/web/app/(org)/dashboard/caps/page.tsx b/apps/web/app/(org)/dashboard/caps/page.tsx
index f78bb69d8..f86da3da9 100644
--- a/apps/web/app/(org)/dashboard/caps/page.tsx
+++ b/apps/web/app/(org)/dashboard/caps/page.tsx
@@ -123,16 +123,6 @@ export default async function CapsPage(props: PageProps<"/dashboard/caps">) {
const totalCount = totalCountResult[0]?.count || 0;
- // Get custom domain and verification status for the user's organization
- const organizationData = await db()
- .select({
- customDomain: organizations.customDomain,
- domainVerified: organizations.domainVerified,
- })
- .from(organizations)
- .where(eq(organizations.id, user.activeOrganizationId))
- .limit(1);
-
const videoData = await db()
.select({
id: videos.id,
diff --git a/apps/web/app/(org)/dashboard/layout.tsx b/apps/web/app/(org)/dashboard/layout.tsx
index 80a53df94..74d611c36 100644
--- a/apps/web/app/(org)/dashboard/layout.tsx
+++ b/apps/web/app/(org)/dashboard/layout.tsx
@@ -29,7 +29,7 @@ export default async function DashboardLayout({
}
if (!user.name || user.name.length === 0) {
- redirect("/onboarding");
+ redirect("/onboarding/welcome");
}
let organizationSelect: Organization[] = [];
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
index 9a9e85aad..dc046d28d 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/OrganizationIcon.tsx
@@ -1,7 +1,7 @@
"use client";
import { CardDescription, Label } from "@cap/ui";
-import { useState } from "react";
+import { useId, useState } from "react";
import { toast } from "sonner";
import { removeOrganizationIcon } from "@/actions/organization/remove-icon";
import { uploadOrganizationIcon } from "@/actions/organization/upload-organization-icon";
@@ -9,6 +9,7 @@ import { FileInput } from "@/components/FileInput";
import { useDashboardContext } from "../../../Contexts";
export const OrganizationIcon = () => {
+ const iconInputId = useId();
const { activeOrganization } = useDashboardContext();
const organizationId = activeOrganization?.organization.id;
const existingIconUrl = activeOrganization?.organization.iconUrl;
@@ -22,10 +23,9 @@ export const OrganizationIcon = () => {
// Upload the file to the server immediately
try {
setIsUploading(true);
- const formData = new FormData();
- formData.append("file", file);
-
- const result = await uploadOrganizationIcon(formData, organizationId);
+ const fd = new FormData();
+ fd.append("icon", file);
+ const result = await uploadOrganizationIcon(fd, organizationId);
if (result.success) {
toast.success("Organization icon updated successfully");
@@ -68,7 +68,7 @@ export const OrganizationIcon = () => {
<FileInput
height={44}
previewIconSize={20}
- id="icon"
+ id={iconInputId}
name="icon"
onChange={handleFileChange}
disabled={isUploading}
diff --git a/apps/web/app/(org)/onboarding/Onboarding.tsx b/apps/web/app/(org)/onboarding/Onboarding.tsx
deleted file mode 100644
index cdffc88ed..000000000
--- a/apps/web/app/(org)/onboarding/Onboarding.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-"use client";
-
-import { Button, Input } from "@cap/ui";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
-import { toast } from "sonner";
-import { UpgradeModal } from "@/components/UpgradeModal";
-
-export const Onboarding = () => {
- const [loading, setLoading] = useState(false);
- const [firstName, setFirstName] = useState("");
- const [lastName, setLastName] = useState("");
- const [showUpgradeModal, setShowUpgradeModal] = useState(false);
- const router = useRouter();
- const [isRedirecting, setIsRedirecting] = useState(false);
-
- const onboardingRequest = async () => {
- const response = await fetch("/api/settings/onboarding", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ firstName, lastName }),
- });
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- return response.json();
- };
-
- const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault();
- try {
- setLoading(true);
- const response = await onboardingRequest();
-
- if (!response.isMemberOfOrganization) {
- setShowUpgradeModal(true);
- } else {
- router.refresh();
- setIsRedirecting(true);
- }
- } catch {
- toast.error("Failed to complete onboarding");
- } finally {
- setLoading(false);
- }
- };
-
- return (
- <>
- <form
- className="relative w-[calc(100%-2%)] p-[28px] max-w-[472px] bg-gray-2 border border-gray-4 rounded-2xl"
- onSubmit={handleSubmit}
- >
- <div className="space-y-3">
- <div className="flex flex-col space-y-1">
- <Input
- type="text"
- id="firstName"
- placeholder="First name"
- name="firstName"
- required
- value={firstName}
- disabled={loading || isRedirecting}
- onChange={(e) => setFirstName(e.target.value)}
- />
- </div>
- <div className="flex flex-col space-y-1">
- <Input
- type="text"
- id="lastName"
- name="lastName"
- placeholder="Last name"
- value={lastName}
- disabled={loading || isRedirecting}
- onChange={(e) => setLastName(e.target.value)}
- />
- </div>
- </div>
- <Button
- disabled={!firstName || loading || isRedirecting}
- className="mx-auto mt-6 w-full"
- type="submit"
- spinner={loading || isRedirecting}
- >
- {isRedirecting
- ? "Redirecting..."
- : loading
- ? "Submitting..."
- : "Submit"}
- </Button>
- </form>
-
- <UpgradeModal
- open={showUpgradeModal}
- onOpenChange={(open) => {
- setShowUpgradeModal(open);
- if (!open) {
- router.refresh();
- setIsRedirecting(true);
- }
- }}
- />
- </>
- );
-};
diff --git a/apps/web/app/(org)/onboarding/[...steps]/layout.tsx b/apps/web/app/(org)/onboarding/[...steps]/layout.tsx
new file mode 100644
index 000000000..19007be20
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/[...steps]/layout.tsx
@@ -0,0 +1,45 @@
+import { getCurrentUser } from "@cap/database/auth/session";
+import { redirect } from "next/navigation";
+
+export default async function OnboardingStepLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ steps: string[] }>;
+}) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ redirect("/login");
+ }
+
+ const steps = user.onboardingSteps || {};
+ const currentStep = (await params).steps?.[0] ?? "welcome";
+
+ const ordered = [
+ "welcome",
+ "organization-setup",
+ "custom-domain",
+ "invite-team",
+ "download",
+ ] as const;
+ const isComplete = (s: (typeof ordered)[number]) =>
+ s === "welcome"
+ ? Boolean(steps.welcome && user.name)
+ : s === "organization-setup"
+ ? Boolean(steps.organizationSetup)
+ : s === "custom-domain"
+ ? Boolean(steps.customDomain)
+ : s === "invite-team"
+ ? Boolean(steps.inviteTeam)
+ : Boolean(steps.download);
+
+ const firstIncomplete = ordered.find((s) => !isComplete(s)) ?? "download";
+
+ if (currentStep !== firstIncomplete) {
+ redirect(`/onboarding/${firstIncomplete}`);
+ }
+
+ return children;
+}
diff --git a/apps/web/app/(org)/onboarding/[...steps]/page.tsx b/apps/web/app/(org)/onboarding/[...steps]/page.tsx
new file mode 100644
index 000000000..949f15357
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/[...steps]/page.tsx
@@ -0,0 +1,33 @@
+import { getCurrentUser } from "@cap/database/auth/session";
+import { CustomDomainPage } from "../components/CustomDomainPage";
+import { DownloadPage } from "../components/DownloadPage";
+import { InviteTeamPage } from "../components/InviteTeamPage";
+import { OrganizationSetupPage } from "../components/OrganizationSetupPage";
+import { WelcomePage } from "../components/WelcomePage";
+
+export default async function OnboardingStepPage({
+ params,
+}: {
+ params: Promise<{
+ steps: "welcome" | "organization-setup" | "custom-domain" | "invite-team";
+ }>;
+}) {
+ const step = (await params).steps[0];
+
+ switch (step) {
+ case "welcome":
+ return <WelcomePage />;
+ case "organization-setup": {
+ const user = await getCurrentUser();
+ return <OrganizationSetupPage firstName={user?.name} />;
+ }
+ case "custom-domain":
+ return <CustomDomainPage />;
+ case "invite-team":
+ return <InviteTeamPage />;
+ case "download":
+ return <DownloadPage />;
+ default:
+ return null;
+ }
+}
diff --git a/apps/web/app/(org)/onboarding/components/Base.tsx b/apps/web/app/(org)/onboarding/components/Base.tsx
new file mode 100644
index 000000000..af52bf933
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/Base.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import { LogoBadge } from "@cap/ui";
+import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import clsx from "clsx";
+import { useRouter } from "next/navigation";
+
+export const Base = ({
+ children,
+ title,
+ description,
+ descriptionClassName,
+ hideBackButton = true,
+}: {
+ children: React.ReactNode;
+ title: string;
+ description: string | React.ReactNode;
+ descriptionClassName?: string;
+ hideBackButton?: boolean;
+}) => {
+ const router = useRouter();
+ return (
+ <div className="relative w-[calc(100%-2%)] space-y-7 p-7 max-w-[472px] bg-gray-2 border border-gray-4 rounded-2xl">
+ {!hideBackButton && (
+ <div
+ onClick={() => router.back()}
+ className="absolute overflow-hidden flex top-5 rounded-full left-5 z-20 hover:bg-gray-1 gap-2 items-center py-1.5 px-3 text-gray-12 bg-transparent border border-gray-4 transition-colors duration-300 cursor-pointer"
+ >
+ <FontAwesomeIcon className="w-2" icon={faArrowLeft} />
+ <p className="text-xs text-inherit">Back</p>
+ </div>
+ )}
+ <a href="/">
+ <LogoBadge className="mx-auto w-auto h-12" />
+ </a>
+ <div className="flex flex-col justify-center items-center space-y-1 text-center">
+ <h2 className="text-2xl font-semibold text-gray-12">{title}</h2>
+ {typeof description === "string" ? (
+ <p
+ className={clsx(
+ "w-full text-base max-w-[260px] text-gray-10",
+ descriptionClassName,
+ )}
+ >
+ {description}
+ </p>
+ ) : (
+ description
+ )}
+ </div>
+ {children}
+ </div>
+ );
+};
diff --git a/apps/web/app/(org)/onboarding/components/Bottom.tsx b/apps/web/app/(org)/onboarding/components/Bottom.tsx
new file mode 100644
index 000000000..68ddb87ad
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/Bottom.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import { Button } from "@cap/ui";
+import { useRouter } from "next/navigation";
+import { signOut } from "next-auth/react";
+import { startTransition } from "react";
+import { toast } from "sonner";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+
+export const Bottom = () => {
+ const router = useRouter();
+
+ const skipToDashboard = useEffectMutation({
+ mutationFn: () =>
+ withRpc((r) =>
+ r.UserCompleteOnboardingStep({
+ step: "skipToDashboard",
+ data: undefined,
+ }),
+ ),
+ onSuccess: () => {
+ startTransition(() => {
+ router.push("/dashboard/caps");
+ router.refresh();
+ });
+ },
+ onError: () => {
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ return (
+ <div className="flex right-0 bottom-0 left-0 justify-between items-center p-0 mt-5 w-full lg:absolute lg:mt-0 lg:p-16">
+ <Button
+ className="w-fit"
+ variant="outline"
+ size="sm"
+ onClick={() => signOut()}
+ >
+ Sign out
+ </Button>
+ <Button
+ className="px-0 w-fit"
+ variant="transparent"
+ spinner={skipToDashboard.isPending}
+ disabled={skipToDashboard.isPending || skipToDashboard.isSuccess}
+ size="sm"
+ onClick={() => skipToDashboard.mutate()}
+ >
+ {skipToDashboard.isPending ? "Skipping..." : "Skip to dashboard"}
+ </Button>
+ </div>
+ );
+};
+
+export default Bottom;
diff --git a/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx b/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx
new file mode 100644
index 000000000..8f7ec09d9
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/CustomDomainPage.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import { Button } from "@cap/ui";
+import { Effect } from "effect";
+import { useRouter } from "next/navigation";
+import { startTransition, useState } from "react";
+import { toast } from "sonner";
+import { UpgradeModal } from "@/components/UpgradeModal";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+import { Base } from "./Base";
+
+export function CustomDomainPage() {
+ const router = useRouter();
+ const [showUpgradeModal, setShowUpgradeModal] = useState(false);
+
+ const customDomainMutation = useEffectMutation({
+ mutationFn: (redirect: boolean) =>
+ Effect.gen(function* () {
+ yield* withRpc((r) =>
+ r.UserCompleteOnboardingStep({
+ step: "customDomain",
+ data: undefined,
+ }),
+ );
+ return redirect;
+ }),
+ onSuccess: (redirect: boolean) => {
+ startTransition(() => {
+ if (redirect) {
+ router.push("/onboarding/invite-team");
+ router.refresh();
+ }
+ });
+ },
+ onError: () => {
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ const handleSubmit = async (redirect = true) =>
+ await customDomainMutation.mutateAsync(redirect);
+
+ return (
+ <Base
+ title="Custom Domain"
+ description={
+ <div>
+ <p className="w-full text-base max-w-[340px] text-gray-10">
+ Pro users can setup a custom domain to access their shareable Cap
+ links i.e{" "}
+ <span className="font-medium text-blue-500">
+ cap.yourdomain.com
+ </span>
+ </p>
+ </div>
+ }
+ descriptionClassName="max-w-[400px]"
+ >
+ <Button
+ onClick={() => setShowUpgradeModal(true)}
+ className="w-full"
+ disabled={customDomainMutation.isPending}
+ variant="blue"
+ >
+ Upgrade to Pro
+ </Button>
+ <div className="w-full h-px bg-gray-4" />
+ <Button
+ type="button"
+ variant="dark"
+ spinner={customDomainMutation.isPending}
+ disabled={customDomainMutation.isPending}
+ className="mx-auto w-full"
+ onClick={() => handleSubmit()}
+ >
+ Skip
+ </Button>
+ <UpgradeModal
+ onCheckout={async () => {
+ await handleSubmit();
+ }}
+ onboarding={true}
+ open={showUpgradeModal}
+ onOpenChange={setShowUpgradeModal}
+ />
+ </Base>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/components/DownloadPage.tsx b/apps/web/app/(org)/onboarding/components/DownloadPage.tsx
new file mode 100644
index 000000000..aff7d06e9
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/DownloadPage.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import { Button, LogoBadge } from "@cap/ui";
+import { useDetectPlatform } from "hooks/useDetectPlatform";
+import { Clapperboard, Zap } from "lucide-react";
+import { useRouter } from "next/navigation";
+import { startTransition, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+import {
+ getDownloadButtonText,
+ getDownloadUrl,
+ getPlatformIcon,
+} from "@/utils/platform";
+
+const recordingModes = [
+ {
+ name: "Instant Mode",
+ icon: <Zap fill="yellow" className="mb-4 size-8" strokeWidth={1.5} />,
+ description:
+ "Hit record, stop, share link. Your video is live in seconds with automatically generated captions, a title, summary, chapters, and more. Perfect for quick feedback, bug reports, or when you just need to show something fast.",
+ },
+ {
+ name: "Studio Mode",
+ icon: (
+ <Clapperboard
+ fill="var(--blue-9)"
+ className="mb-4 size-8"
+ strokeWidth={1.5}
+ />
+ ),
+ description:
+ "Professional recordings with local editing, custom backgrounds, and export options. When you need pixel-perfect demos, tutorials, or presentations that represent your brand.",
+ },
+];
+
+export function DownloadPage() {
+ const { platform, isIntel } = useDetectPlatform();
+ const loading = platform === null;
+ const router = useRouter();
+ const [clickedContinue, setClickedContinue] = useState(false);
+
+ //mark as complete when loading the page
+ useEffect(() => {
+ onboardingRequest.mutate();
+ router.refresh();
+ }, []);
+
+ const onboardingRequest = useEffectMutation({
+ mutationFn: () =>
+ withRpc((r) => {
+ return r.UserCompleteOnboardingStep({
+ step: "download",
+ data: undefined,
+ });
+ }),
+ onSuccess: () => {
+ if (clickedContinue) {
+ startTransition(() => {
+ router.push("/dashboard/caps");
+ router.refresh();
+ });
+ }
+ },
+ onError: () => {
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ return (
+ <div className="flex flex-col gap-12 justify-center items-center min-h-fit lg:gap-20">
+ <div className="space-y-10">
+ <div className="flex flex-col gap-6 justify-center items-center">
+ <LogoBadge className="mx-auto w-auto h-12" />
+ <div className="space-y-1 text-center">
+ <h1 className="text-3xl font-medium text-gray-12">Download Cap</h1>
+ <p className="text-lg text-center text-gray-11 text-pretty">
+ Start recording beautiful screen recordings today
+ </p>
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-10 justify-center items-center w-full max-w-[1000px] mx-auto">
+ {recordingModes.map((recordingMode) => (
+ <div
+ key={recordingMode.name}
+ className="flex flex-col w-full max-w-[440px] gap-2 items-center p-6 text-center rounded-xl border bg-gray-2 border-gray-3"
+ >
+ {recordingMode.icon}
+ <h2 className="text-xl font-medium text-gray-12">
+ {recordingMode.name}
+ </h2>
+ <p className="text-base text-gray-10 text-pretty">
+ {recordingMode.description}
+ </p>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-4 justify-center">
+ <Button
+ variant="blue"
+ size="lg"
+ href={getDownloadUrl(platform, isIntel)}
+ className="hidden justify-center items-center py-6 font-medium text-white lg:flex"
+ >
+ {!loading && getPlatformIcon(platform)}
+ {getDownloadButtonText(platform, loading, isIntel)}
+ </Button>
+ <Button
+ onClick={() => {
+ setClickedContinue(true);
+ onboardingRequest.mutate();
+ }}
+ spinner={onboardingRequest.isPending && clickedContinue}
+ disabled={onboardingRequest.isPending && clickedContinue}
+ className="min-w-[120px]"
+ variant="dark"
+ size="lg"
+ >
+ Continue
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx b/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx
new file mode 100644
index 000000000..6a3e8cbd9
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/InviteTeamPage.tsx
@@ -0,0 +1,259 @@
+"use client";
+
+import { Button, Switch } from "@cap/ui";
+import { faMinus, faPlus } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import NumberFlow from "@number-flow/react";
+import { useMutation } from "@tanstack/react-query";
+import clsx from "clsx";
+import { Effect } from "effect";
+import { useRouter } from "next/navigation";
+import { type MouseEvent, startTransition, useId, useState } from "react";
+import { toast } from "sonner";
+import { useStripeContext } from "@/app/Layout/StripeContext";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+import { homepageCopy } from "../../../../data/homepage-copy";
+import { Base } from "./Base";
+
+export function InviteTeamPage() {
+ const billingCycleId = useId();
+ const stripeCtx = useStripeContext();
+ const [users, setUsers] = useState(1);
+ const [isAnnually, setIsAnnually] = useState(true);
+ const router = useRouter();
+ const CAP_PRO_ANNUAL_PRICE_PER_USER = homepageCopy.pricing.pro.pricing.annual;
+ const CAP_PRO_MONTHLY_PRICE_PER_USER =
+ homepageCopy.pricing.pro.pricing.monthly;
+
+ const currentTotalPrice =
+ users *
+ (isAnnually
+ ? CAP_PRO_ANNUAL_PRICE_PER_USER
+ : CAP_PRO_MONTHLY_PRICE_PER_USER);
+ const billingCycleText = isAnnually
+ ? "per user, billed annually"
+ : "per user, billed monthly";
+
+ const incrementUsers = () => setUsers((n) => n + 1);
+ const decrementUsers = () => setUsers((n) => (n > 1 ? n - 1 : 1));
+
+ const inviteTeamMutation = useEffectMutation({
+ mutationFn: (redirect: boolean) =>
+ Effect.gen(function* () {
+ yield* withRpc((r) =>
+ r.UserCompleteOnboardingStep({
+ step: "inviteTeam",
+ data: undefined,
+ }),
+ );
+ return redirect;
+ }),
+ onSuccess: (redirect: boolean) => {
+ startTransition(() => {
+ if (redirect) {
+ router.push("/onboarding/download");
+ router.refresh();
+ }
+ });
+ },
+ onError: () => {
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ const handleSubmit = async (
+ e: MouseEvent<HTMLButtonElement>,
+ redirect = true,
+ ) => {
+ e.preventDefault();
+ await inviteTeamMutation.mutateAsync(redirect);
+ };
+
+ const planCheckout = async (e: MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault();
+ try {
+ const planId = stripeCtx.plans[isAnnually ? "yearly" : "monthly"];
+
+ const response = await fetch(`/api/settings/billing/subscribe`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ priceId: planId,
+ quantity: users,
+ isOnBoarding: true,
+ }),
+ });
+ if (!response.ok) {
+ toast.error("Unable to start checkout. Please try again.");
+ return;
+ }
+ const data = await response.json();
+ if (data.subscription === true) {
+ toast.success("You are already on the Cap Pro plan");
+ return;
+ }
+
+ await handleSubmit(e, false);
+
+ if (data.url) {
+ window.location.href = data.url;
+ }
+ } catch (error) {
+ console.error("Plan checkout error:", error);
+ toast.error("Something went wrong. Please try again.");
+ }
+ };
+
+ const planCheckoutMutation = useMutation({
+ mutationFn: (e: MouseEvent<HTMLButtonElement>) => planCheckout(e),
+ onError: (error) => {
+ console.error("Plan checkout error:", error);
+ toast.error("Something went wrong. Please try again.");
+ },
+ });
+
+ return (
+ <Base
+ title="Invite your team"
+ descriptionClassName="max-w-[360px]"
+ description="Invite members of your team to join your organization and share Caps together"
+ >
+ <div className="text-center">
+ <span className="mr-2 text-2xl tabular-nums lg:text-3xl text-gray-12">
+ $<NumberFlow suffix="/mo" value={currentTotalPrice} />
+ </span>
+ <span className="text-base tabular-nums text-gray-10">
+ {" "}
+ {billingCycleText}
+ </span>
+ {isAnnually ? (
+ <p className="text-base text-gray-10">
+ or,{" "}
+ <NumberFlow
+ value={CAP_PRO_MONTHLY_PRICE_PER_USER * users}
+ className="text-sm tabular-nums lg:text-base text-gray-12"
+ format={{
+ notation: "compact",
+ style: "currency",
+ currency: "USD",
+ }}
+ suffix="/mo"
+ />{" "}
+ {users === 1 ? (
+ "per user, "
+ ) : (
+ <>
+ for{" "}
+ <NumberFlow value={users} className="text-base tabular-nums" />{" "}
+ users,{" "}
+ </>
+ )}
+ billed monthly
+ </p>
+ ) : (
+ <p className="text-base text-gray-10">
+ or,{" "}
+ <NumberFlow
+ value={CAP_PRO_ANNUAL_PRICE_PER_USER * users}
+ className="text-sm tabular-nums lg:text-base text-gray-12"
+ format={{
+ notation: "compact",
+ style: "currency",
+ currency: "USD",
+ }}
+ suffix="/mo"
+ />{" "}
+ {users === 1 ? (
+ "per user, "
+ ) : (
+ <>
+ for{" "}
+ <NumberFlow value={users} className="text-base tabular-nums" />{" "}
+ users,{" "}
+ </>
+ )}
+ billed annually
+ </p>
+ )}
+ </div>
+
+ <div className="space-y-3">
+ <div className="flex flex-wrap gap-5 justify-center items-center p-5 w-full rounded-xl border bg-gray-3 border-gray-4 xs:gap-3 xs:p-3 xs:rounded-full xs:justify-between">
+ <div className="flex gap-2 items-center">
+ <p className="text-sm text-gray-12">Per user</p>
+ <div className="flex items-center">
+ <Button
+ onClick={decrementUsers}
+ className="p-1 bg-gray-12 hover:bg-gray-11 min-w-fit h-fit"
+ aria-label="Decrease user count"
+ >
+ <FontAwesomeIcon
+ icon={faMinus}
+ className="text-gray-1 size-2.5"
+ />
+ </Button>
+ <span className="w-6 font-medium tabular-nums text-center text-gray-12">
+ <NumberFlow value={users} />
+ </span>
+ <Button
+ onClick={incrementUsers}
+ className="p-1 bg-gray-12 hover:bg-gray-11 min-w-fit h-fit"
+ aria-label="Increase user count"
+ >
+ <FontAwesomeIcon
+ icon={faPlus}
+ className="text-gray-1 size-2.5"
+ />
+ </Button>
+ </div>
+ </div>
+ <div className="flex items-center">
+ <span
+ className={clsx(
+ "text-sm",
+ !isAnnually ? "text-gray-12" : "text-gray-10",
+ )}
+ >
+ {homepageCopy.pricing.pro.labels.monthly}
+ </span>
+ <Switch
+ checked={isAnnually}
+ onCheckedChange={setIsAnnually}
+ aria-label="Billing Cycle"
+ className="scale-75"
+ id={billingCycleId}
+ />
+ <span
+ className={clsx(
+ "text-sm",
+ isAnnually ? "text-gray-12" : "text-gray-10",
+ )}
+ >
+ {homepageCopy.pricing.pro.labels.annually}
+ </span>
+ </div>
+ </div>
+ <Button
+ className="w-full"
+ variant="blue"
+ spinner={planCheckoutMutation.isPending}
+ disabled={planCheckoutMutation.isPending}
+ onClick={planCheckoutMutation.mutate}
+ >
+ Get Started
+ </Button>
+ </div>
+ <div className="w-full h-px bg-gray-4" />
+ <Button
+ variant="dark"
+ className="mx-auto w-full"
+ onClick={handleSubmit}
+ spinner={inviteTeamMutation.isPending}
+ disabled={inviteTeamMutation.isPending}
+ >
+ Skip
+ </Button>
+ </Base>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx b/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx
new file mode 100644
index 000000000..a34804fc8
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/OrganizationSetupPage.tsx
@@ -0,0 +1,159 @@
+"use client";
+
+import { Button, Input } from "@cap/ui";
+import { faImage } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Effect } from "effect";
+import Image from "next/image";
+import { useRouter } from "next/navigation";
+import { startTransition, useRef, useState } from "react";
+import { toast } from "sonner";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+import { Base } from "./Base";
+
+export function OrganizationSetupPage({
+ firstName,
+}: {
+ firstName: string | null | undefined;
+}) {
+ const [organizationName, setOrganizationName] = useState(
+ firstName ? `${firstName}'s organization` : "",
+ );
+ const [selectedFile, setSelectedFile] = useState<File | null>(null);
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const router = useRouter();
+
+ const handleFileChange = () => {
+ const file = fileInputRef.current?.files?.[0];
+ if (file) {
+ setSelectedFile(file);
+ }
+ };
+
+ const orgSetupMutation = useEffectMutation({
+ mutationFn: (data: { organizationName: string; icon?: File }) =>
+ Effect.gen(function* () {
+ let organizationIcon:
+ | {
+ data: Uint8Array;
+ contentType: string;
+ fileName: string;
+ }
+ | undefined;
+
+ if (data.icon) {
+ const icon = data.icon;
+ const arrayBuffer = yield* Effect.promise(() => icon.arrayBuffer());
+ organizationIcon = {
+ data: new Uint8Array(arrayBuffer),
+ contentType: icon.type,
+ fileName: icon.name,
+ };
+ }
+
+ yield* withRpc((r) =>
+ r.UserCompleteOnboardingStep({
+ step: "organizationSetup",
+ data: {
+ organizationName: data.organizationName,
+ organizationIcon,
+ },
+ }),
+ );
+ }),
+ onSuccess: () => {
+ startTransition(() => {
+ router.push("/onboarding/custom-domain");
+ router.refresh();
+ });
+ },
+ onError: (error) => {
+ console.error(error);
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ orgSetupMutation.mutate({
+ organizationName,
+ icon: selectedFile || undefined,
+ });
+ };
+
+ return (
+ <Base
+ title="Organization Setup"
+ description="Let's get your dashboard setup with your organization"
+ >
+ <form onSubmit={handleSubmit} className="space-y-7">
+ <div className="space-y-3">
+ <Input
+ type="text"
+ disabled={orgSetupMutation.isPending}
+ value={organizationName}
+ onChange={(e) => setOrganizationName(e.target.value)}
+ placeholder="Organization Name"
+ name="organizationName"
+ required
+ />
+ <div className="rounded-xl border bg-gray-1 h-fit border-gray-4">
+ <h3 className="px-3 py-3 text-sm font-medium border-b border-gray-4 text-gray-12">
+ Organization Logo
+ </h3>
+ <div className="flex gap-5 p-5">
+ <div className="flex justify-center items-center rounded-full border border-dashed size-14 bg-gray-3 border-gray-6">
+ {selectedFile ? (
+ <Image
+ src={URL.createObjectURL(selectedFile)}
+ alt="Selected File"
+ width={56}
+ className="object-cover rounded-full size-14"
+ height={56}
+ />
+ ) : (
+ <FontAwesomeIcon
+ icon={faImage}
+ className="size-4 text-gray-9"
+ />
+ )}
+ </div>
+ <input
+ type="file"
+ className="hidden h-0"
+ accept="image/jpeg, image/jpg, image/png, image/svg+xml"
+ ref={fileInputRef}
+ onChange={handleFileChange}
+ />
+ <div className="space-y-3">
+ <Button
+ type="button"
+ variant="gray"
+ disabled={orgSetupMutation.isPending}
+ size="xs"
+ onClick={() => fileInputRef.current?.click()}
+ >
+ Upload Image
+ </Button>
+ <p className="text-xs text-gray-10">
+ Recommended size: 120x120
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="w-full h-px bg-gray-4" />
+ <Button
+ type="submit"
+ variant="dark"
+ className="mx-auto w-full"
+ spinner={orgSetupMutation.isPending}
+ disabled={orgSetupMutation.isPending}
+ >
+ Create Organization
+ </Button>
+ </form>
+ </Base>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/components/Stepper.tsx b/apps/web/app/(org)/onboarding/components/Stepper.tsx
new file mode 100644
index 000000000..70b28743f
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/Stepper.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { faCheck } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import clsx from "clsx";
+import { usePathname } from "next/navigation";
+import { Fragment, useMemo } from "react";
+
+export default function Stepper({
+ completedSteps,
+}: {
+ completedSteps: {
+ welcome?: boolean;
+ organizationSetup?: boolean;
+ customDomain?: boolean;
+ inviteTeam?: boolean;
+ download?: boolean;
+ };
+}) {
+ const currentPath = usePathname();
+ const currentStep = useMemo(() => {
+ if (currentPath === "/onboarding/welcome") return "Welcome";
+ if (currentPath === "/onboarding/organization-setup")
+ return "Organization Setup";
+ if (currentPath === "/onboarding/custom-domain") return "Custom Domain";
+ if (currentPath === "/onboarding/invite-team") return "Invite your team";
+ if (currentPath === "/onboarding/download") return "Download";
+ }, [currentPath]);
+
+ const steps = [
+ {
+ id: "1",
+ name: "Welcome",
+ completed: completedSteps.welcome || false,
+ },
+ {
+ id: "2",
+ name: "Organization Setup",
+ completed: completedSteps.organizationSetup || false,
+ },
+ {
+ id: "3",
+ name: "Custom Domain",
+ completed: completedSteps.customDomain || false,
+ },
+ {
+ id: "4",
+ name: "Invite your team",
+ completed: completedSteps.inviteTeam || false,
+ },
+ {
+ id: "5",
+ name: "Download",
+ completed: completedSteps.download || false,
+ },
+ ];
+
+ return (
+ <>
+ {/* Mobile Stepper - shows on devices up to 1024px */}
+ <div className="justify-center mx-auto mb-10 max-w-fit lg:hidden">
+ <MobileStepper currentStep={currentStep} steps={steps} />
+ </div>
+
+ {/* Desktop Stepper - shows on devices 1024px and up */}
+ <div className="hidden absolute right-0 left-0 top-6 justify-center items-center p-4 mx-auto rounded-xl border lg:flex max-w-fit bg-gray-2 border-gray-4">
+ {steps.map((step, idx) => {
+ return (
+ <Fragment key={step.id}>
+ <div className="flex justify-center items-center">
+ {idx !== 0 && (
+ <div className="flex-1 mx-5 border-t border-dashed min-w-[72px] h-[2px] border-gray-8" />
+ )}
+ <div className="flex flex-1 gap-2 justify-center items-center min-w-fit">
+ <div
+ className={clsx(
+ "flex justify-center items-center text-xs text-white rounded-full size-5 min-size-5",
+ currentStep === step.name && !step.completed
+ ? "bg-blue-500"
+ : step.completed
+ ? "bg-green-500"
+ : "bg-gray-7",
+ )}
+ >
+ {step.completed ? (
+ <FontAwesomeIcon
+ icon={faCheck}
+ className="text-white size-2"
+ />
+ ) : (
+ <p>{step.id}</p>
+ )}
+ </div>
+ <p
+ className={clsx(
+ "text-[13px] text-nowrap",
+ step.completed || currentStep === step.name
+ ? "text-gray-12"
+ : "text-gray-9",
+ )}
+ >
+ {step.name}
+ </p>
+ </div>
+ </div>
+ </Fragment>
+ );
+ })}
+ </div>
+ </>
+ );
+}
+
+const MobileStepper = ({
+ currentStep,
+ steps,
+}: {
+ currentStep: string | undefined;
+ steps: Array<{
+ id: string;
+ name: string;
+ completed: boolean;
+ }>;
+}) => {
+ const activeStep = steps.find((step) => step.name === currentStep);
+
+ if (!activeStep) return null;
+
+ return (
+ <div className="flex gap-x-4 items-center p-3 rounded-xl border bg-gray-2 border-gray-4">
+ <div className="flex gap-2 items-center">
+ <div
+ className={clsx(
+ "flex justify-center items-center text-xs text-white rounded-full size-5 min-size-5",
+ "bg-blue-500",
+ )}
+ >
+ <p>{activeStep.id}</p>
+ </div>
+ <p className="text-sm font-medium text-gray-12">{activeStep.name}</p>
+ </div>
+ <div>
+ <p className="text-[13px] text-gray-10">
+ Step <span className="text-gray-11">{activeStep.id}/5</span>
+ </p>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/app/(org)/onboarding/components/WelcomePage.tsx b/apps/web/app/(org)/onboarding/components/WelcomePage.tsx
new file mode 100644
index 000000000..070bd97d5
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/components/WelcomePage.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import { Button, Input } from "@cap/ui";
+import { useRouter } from "next/navigation";
+import { startTransition, useState } from "react";
+import { toast } from "sonner";
+import { useEffectMutation } from "@/lib/EffectRuntime";
+import { withRpc } from "@/lib/Rpcs";
+import { Base } from "./Base";
+
+export function WelcomePage() {
+ const [firstName, setFirstName] = useState("");
+ const [lastName, setLastName] = useState("");
+ const router = useRouter();
+
+ const welcomeMutation = useEffectMutation({
+ mutationFn: (data: { firstName: string; lastName?: string }) =>
+ withRpc((r) =>
+ r.UserCompleteOnboardingStep({
+ step: "welcome",
+ data,
+ }),
+ ),
+ onSuccess: () => {
+ startTransition(() => {
+ router.push("/onboarding/organization-setup");
+ router.refresh();
+ });
+ },
+ onError: () => {
+ toast.error("An error occurred, please try again");
+ },
+ });
+
+ const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ welcomeMutation.mutate({ firstName, lastName });
+ };
+
+ return (
+ <Base
+ title="Welcome to Cap"
+ description="Let's get you started"
+ hideBackButton
+ >
+ <form className="space-y-7" onSubmit={handleSubmit}>
+ <div className="space-y-3">
+ <Input
+ value={firstName}
+ disabled={welcomeMutation.isPending}
+ onChange={(e) => setFirstName(e.target.value)}
+ type="text"
+ placeholder="First name"
+ name="firstName"
+ required
+ />
+ <Input
+ value={lastName}
+ disabled={welcomeMutation.isPending}
+ onChange={(e) => setLastName(e.target.value)}
+ type="text"
+ placeholder="Last name (optional)"
+ name="lastName"
+ />
+ </div>
+ <div className="w-full h-px bg-gray-4" />
+ <Button
+ spinner={welcomeMutation.isPending}
+ disabled={!firstName || welcomeMutation.isPending}
+ type="submit"
+ variant="dark"
+ className="mx-auto w-full"
+ >
+ Continue
+ </Button>
+ </form>
+ </Base>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/layout.tsx b/apps/web/app/(org)/onboarding/layout.tsx
new file mode 100644
index 000000000..01164bbc2
--- /dev/null
+++ b/apps/web/app/(org)/onboarding/layout.tsx
@@ -0,0 +1,20 @@
+import { getCurrentUser } from "@cap/database/auth/session";
+import Bottom from "./components/Bottom";
+import Stepper from "./components/Stepper";
+
+export default async function OnboardingLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const user = await getCurrentUser();
+ const completedSteps = user?.onboardingSteps || {};
+
+ return (
+ <div className="flex relative flex-col justify-center items-center px-5 py-10 w-full custom-scroll min-h-fit lg:min-h-auto h-dvh bg-gray-1">
+ <Stepper completedSteps={completedSteps} />
+ {children}
+ <Bottom />
+ </div>
+ );
+}
diff --git a/apps/web/app/(org)/onboarding/page.tsx b/apps/web/app/(org)/onboarding/page.tsx
index d69b74ff2..da18f52f1 100644
--- a/apps/web/app/(org)/onboarding/page.tsx
+++ b/apps/web/app/(org)/onboarding/page.tsx
@@ -1,45 +1,5 @@
-import { getCurrentUser } from "@cap/database/auth/session";
-import { LogoBadge } from "@cap/ui";
import { redirect } from "next/navigation";
-import { Onboarding } from "./Onboarding";
-export const dynamic = "force-dynamic";
-
-export default async function OnboardingPage() {
- const user = await getCurrentUser();
-
- if (!user) {
- redirect("/login");
- }
-
- if (
- user &&
- user.name &&
- user.name.length > 1 &&
- user.activeOrganizationId &&
- user.activeOrganizationId.length > 1
- ) {
- redirect("/dashboard");
- } else if (!user) {
- redirect("/login");
- }
-
- return (
- <div className="flex justify-center items-center w-full h-screen bg-gray-1">
- <div className="overflow-hidden relative p-4 space-y-6 w-full max-w-lg sm:rounded-2xl">
- <a href="/">
- <LogoBadge className="mx-auto w-auto h-14" />
- </a>
- <div className="flex flex-col justify-center items-center space-y-1 text-center">
- <h1 className="text-3xl font-semibold text-gray-12">
- Let's get you started
- </h1>
- <p className="text-2xl text-gray-11">What's your name?</p>
- </div>
- <div className="flex flex-col space-y-3">
- <Onboarding />
- </div>
- </div>
- </div>
- );
+export default function Onboarding() {
+ return redirect("/onboarding/welcome");
}
diff --git a/apps/web/app/Layout/devtoolsServer.ts b/apps/web/app/Layout/devtoolsServer.ts
index e43137035..c3796f9e0 100644
--- a/apps/web/app/Layout/devtoolsServer.ts
+++ b/apps/web/app/Layout/devtoolsServer.ts
@@ -21,6 +21,23 @@ export async function promoteToPro() {
.where(eq(users.id, user.id));
}
+export async function restartOnboarding() {
+ if (process.env.NODE_ENV !== "development")
+ throw new Error("restartOnboarding can only be used in development");
+
+ const user = await getCurrentUser();
+ if (!user) throw new Error("No current user session");
+ await db()
+ .update(users)
+ .set({
+ onboardingSteps: null,
+ name: null,
+ lastName: null,
+ onboarding_completed_at: null,
+ })
+ .where(eq(users.id, user.id));
+}
+
export async function demoteFromPro() {
if (process.env.NODE_ENV !== "development")
throw new Error("demoteFromPro can only be used in development");
diff --git a/apps/web/app/Layout/providers.tsx b/apps/web/app/Layout/providers.tsx
index 8735a9db9..1c61ba97f 100644
--- a/apps/web/app/Layout/providers.tsx
+++ b/apps/web/app/Layout/providers.tsx
@@ -71,7 +71,11 @@ export function ReactQueryProvider({
}
import { SessionProvider as NASessionProvider } from "next-auth/react";
-import { demoteFromPro, promoteToPro } from "./devtoolsServer";
+import {
+ demoteFromPro,
+ promoteToPro,
+ restartOnboarding,
+} from "./devtoolsServer";
import { featureFlags, useFeatureFlags } from "./features";
export function SessionProvider({ children }: PropsWithChildren) {
@@ -105,7 +109,7 @@ function CapDevtools() {
const flags = useFeatureFlags();
return (
- <div className="flex flex-col space-y-4 p-4">
+ <div className="flex flex-col p-4 space-y-4">
<h1 className="text-2xl font-semibold">Cap Devtools</h1>
{/*<div className="space-y-2">
<h1 className="text-lg font-semibold">Features</h1>
@@ -132,7 +136,7 @@ function CapDevtools() {
<form action={promoteToPro}>
<button
type="submit"
- className="rounded bg-green-600 px-2 py-1 text-xs font-medium text-white hover:bg-green-700"
+ className="px-2 py-1 text-xs font-medium text-white bg-green-600 rounded hover:bg-green-700"
>
Promote to Pro
</button>
@@ -140,13 +144,27 @@ function CapDevtools() {
<form action={demoteFromPro}>
<button
type="submit"
- className="rounded bg-red-600 px-2 py-1 text-xs font-medium text-white hover:bg-red-700"
+ className="px-2 py-1 text-xs font-medium text-white bg-red-600 rounded hover:bg-red-700"
>
Demote from Pro
</button>
</form>
</div>
</div>
+ <div className="space-y-2">
+ <h1 className="text-lg font-semibold">Onboarding</h1>
+ <p className="text-xs text-muted-foreground">
+ Restart the onboarding process for the current user (dev only)
+ </p>
+ <form action={restartOnboarding}>
+ <button
+ type="submit"
+ className="px-2 py-1 text-xs font-medium text-white bg-blue-600 rounded hover:bg-blue-700"
+ >
+ Restart Onboarding
+ </button>
+ </form>
+ </div>
</div>
);
}
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.ts
index 78f5d6bcb..ebb9b816b 100644
--- a/apps/web/app/api/settings/billing/subscribe/route.ts
+++ b/apps/web/app/api/settings/billing/subscribe/route.ts
@@ -11,7 +11,7 @@ import type Stripe from "stripe";
export async function POST(request: NextRequest) {
const user = await getCurrentUser();
let customerId = user?.stripeCustomerId;
- const { priceId, quantity } = await request.json();
+ const { priceId, quantity, isOnBoarding } = await request.json();
if (!priceId) {
console.error("Price ID not found");
@@ -62,14 +62,23 @@ export async function POST(request: NextRequest) {
.where(eq(users.id, user.id));
customerId = customer.id;
}
+
const checkoutSession = await stripe().checkout.sessions.create({
customer: customerId as string,
line_items: [{ price: priceId, quantity: quantity }],
mode: "subscription",
- success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&session_id={CHECKOUT_SESSION_ID}`,
- cancel_url: `${serverEnv().WEB_URL}/pricing`,
+ success_url: isOnBoarding
+ ? `${serverEnv().WEB_URL}/dashboard/settings/organization?upgrade=true&session_id={CHECKOUT_SESSION_ID}`
+ : `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&session_id={CHECKOUT_SESSION_ID}`,
+ cancel_url: isOnBoarding
+ ? `${serverEnv().WEB_URL}/onboarding`
+ : `${serverEnv().WEB_URL}/pricing`,
allow_promotion_codes: true,
- metadata: { platform: "web", dubCustomerId: user.id },
+ metadata: {
+ platform: "web",
+ dubCustomerId: user.id,
+ isOnBoarding: isOnBoarding ? "true" : "false",
+ },
});
if (checkoutSession.url) {
diff --git a/apps/web/app/api/settings/onboarding/route.ts b/apps/web/app/api/settings/onboarding/route.ts
deleted file mode 100644
index 3720d242b..000000000
--- a/apps/web/app/api/settings/onboarding/route.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { db } from "@cap/database";
-import { getCurrentUser } from "@cap/database/auth/session";
-import { nanoId } from "@cap/database/helpers";
-import {
- organizationMembers,
- organizations,
- users,
-} from "@cap/database/schema";
-import { Organisation } from "@cap/web-domain";
-import { and, eq, ne, or } from "drizzle-orm";
-import { revalidatePath } from "next/cache";
-import type { NextRequest } from "next/server";
-
-export async function POST(request: NextRequest) {
- const user = await getCurrentUser();
- const { firstName, lastName } = await request.json();
-
- if (!user) {
- console.error("User not found");
- return Response.json({ error: true }, { status: 401 });
- }
-
- await db()
- .update(users)
- .set({
- name: firstName,
- lastName: lastName,
- })
- .where(eq(users.id, user.id));
-
- let fullName = firstName;
- if (lastName) {
- fullName += ` ${lastName}`;
- }
-
- const memberButNotOwner = await db()
- .select()
- .from(organizationMembers)
- .leftJoin(
- organizations,
- eq(organizationMembers.organizationId, organizations.id),
- )
- .where(
- and(
- eq(organizationMembers.userId, user.id),
- ne(organizations.ownerId, user.id),
- ),
- )
- .limit(1);
-
- const isMemberOfOrganization = memberButNotOwner.length > 0;
-
- const [organization] = await db()
- .select()
- .from(organizations)
- .where(
- or(
- eq(organizations.ownerId, user.id),
- eq(organizationMembers.userId, user.id),
- ),
- )
- .leftJoin(
- organizationMembers,
- eq(organizations.id, organizationMembers.organizationId),
- );
-
- if (!organization) {
- const organizationId = Organisation.OrganisationId.make(nanoId());
-
- await db()
- .insert(organizations)
- .values({
- id: organizationId,
- ownerId: user.id,
- name: `${fullName}'s Organization`,
- });
-
- await db().insert(organizationMembers).values({
- id: nanoId(),
- userId: user.id,
- role: "owner",
- organizationId,
- });
-
- await db()
- .update(users)
- .set({ activeOrganizationId: organizationId })
- .where(eq(users.id, user.id));
- }
-
- revalidatePath("/onboarding");
-
- return Response.json(
- {
- success: true,
- message: "Onboarding completed successfully",
- isMemberOfOrganization,
- },
- { status: 200 },
- );
-}
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index 63e8887ba..8624da99b 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -231,6 +231,7 @@ export const POST = async (req: Request) => {
(total, item) => total + (item.quantity || 1),
0,
);
+ const isOnBoarding = session.metadata?.isOnBoarding === "true";
console.log("Updating user in database with:", {
subscriptionId: session.subscription,
@@ -238,6 +239,8 @@ export const POST = async (req: Request) => {
customerId: customer.id,
inviteQuota,
});
+ console.log("Session metadata:", session.metadata);
+ console.log("Is onboarding:", isOnBoarding);
await db()
.update(users)
@@ -246,6 +249,7 @@ export const POST = async (req: Request) => {
stripeSubscriptionStatus: subscription.status,
stripeCustomerId: customer.id,
inviteQuota: inviteQuota,
+ onboarding_completed_at: isOnBoarding ? new Date() : undefined,
})
.where(eq(users.id, dbUser.id));
@@ -268,15 +272,8 @@ export const POST = async (req: Request) => {
invite_quota: inviteQuota,
price_id: subscription.items.data[0]?.price.id,
quantity: inviteQuota,
- platform:
- typeof session.metadata === "object" &&
- session.metadata !== null &&
- "platform" in session.metadata &&
- typeof (session.metadata as Record<string, unknown>)
- .platform === "string"
- ? ((session.metadata as Record<string, unknown>)
- .platform as string)
- : "web",
+ is_onboarding: session.metadata?.isOnBoarding === "true",
+ platform: session.metadata?.platform === "web",
is_first_purchase: isFirstPurchase,
is_guest_checkout: isGuestCheckout,
},
@@ -456,7 +453,9 @@ export const POST = async (req: Request) => {
console.error("❌ Webhook handler failed:", error);
return new Response(
'Webhook error: "Webhook handler failed. View logs."',
- { status: 400 },
+ {
+ status: 400,
+ },
);
}
}
diff --git a/apps/web/components/FileInput.tsx b/apps/web/components/FileInput.tsx
index 1b1585c71..7c39a7af5 100644
--- a/apps/web/components/FileInput.tsx
+++ b/apps/web/components/FileInput.tsx
@@ -241,7 +241,7 @@ export const FileInput: React.FC<FileInputProps> = ({
onClick={handleRemove}
>
<FontAwesomeIcon
- className="size-2.5 text-gray-12 group-hover:text-gray-1"
+ className="size-2.5 transition-colors text-gray-12 group-hover:text-gray-10"
icon={faTrash}
/>
</Button>
diff --git a/apps/web/components/UpgradeModal.tsx b/apps/web/components/UpgradeModal.tsx
index 74c5c6a18..519589525 100644
--- a/apps/web/components/UpgradeModal.tsx
+++ b/apps/web/components/UpgradeModal.tsx
@@ -27,7 +27,9 @@ import { useStripeContext } from "@/app/Layout/StripeContext";
interface UpgradeModalProps {
open: boolean;
+ onboarding?: boolean;
onOpenChange: (open: boolean) => void;
+ onCheckout?: () => Promise<void>;
}
const modalVariants = {
@@ -57,7 +59,12 @@ const modalVariants = {
},
};
-const UpgradeModalImpl = ({ open, onOpenChange }: UpgradeModalProps) => {
+const UpgradeModalImpl = ({
+ open,
+ onOpenChange,
+ onCheckout,
+ onboarding,
+}: UpgradeModalProps) => {
const stripeCtx = useStripeContext();
const [isAnnual, setIsAnnual] = useState(true);
const [proQuantity, setProQuantity] = useState(1);
@@ -131,7 +138,7 @@ const UpgradeModalImpl = ({ open, onOpenChange }: UpgradeModalProps) => {
},
];
- const planCheckout = useMutation({
+ const proCheckoutMutation = useMutation({
mutationFn: async () => {
const planId = stripeCtx.plans[isAnnual ? "yearly" : "monthly"];
@@ -140,7 +147,11 @@ const UpgradeModalImpl = ({ open, onOpenChange }: UpgradeModalProps) => {
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({ priceId: planId, quantity: proQuantity }),
+ body: JSON.stringify({
+ priceId: planId,
+ quantity: proQuantity,
+ isOnBoarding: onboarding,
+ }),
});
const data = await response.json();
@@ -156,6 +167,13 @@ const UpgradeModalImpl = ({ open, onOpenChange }: UpgradeModalProps) => {
onOpenChange(false);
}
+ if (data.subscription === true) {
+ toast.success("You are already on the Cap Pro plan");
+ onOpenChange(false);
+ }
+
+ await onCheckout?.();
+
if (data.url) {
window.location.href = data.url;
}
@@ -257,11 +275,15 @@ const UpgradeModalImpl = ({ open, onOpenChange }: UpgradeModalProps) => {
<Button
variant="blue"
- onClick={() => planCheckout.mutate()}
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ proCheckoutMutation.mutate();
+ }}
className="mt-5 w-full max-w-sm h-14 text-lg"
- disabled={planCheckout.isPending}
+ disabled={proCheckoutMutation.isPending}
>
- {planCheckout.isPending
+ {proCheckoutMutation.isPending
? "Loading..."
: "Upgrade to Cap Pro"}
</Button>
diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.ts
index 3f0b8c927..8f39e2575 100644
--- a/packages/database/auth/auth-options.ts
+++ b/packages/database/auth/auth-options.ts
@@ -120,80 +120,6 @@ export const authOptions = (): NextAuthOptions => {
},
},
},
- events: {
- async signIn({ user, account, isNewUser }) {
- const [dbUser] = await db()
- .select()
- .from(users)
- .where(eq(users.id, User.UserId.make(user.id)))
- .limit(1);
-
- const needsOrganizationSetup =
- isNewUser ||
- !dbUser?.activeOrganizationId ||
- dbUser.activeOrganizationId === "";
-
- if (needsOrganizationSetup) {
- const { cookies } = await import("next/headers");
- const dubId = (await cookies()).get("dub_id")?.value;
- const dubPartnerData = (await cookies()).get(
- "dub_partner_data",
- )?.value;
-
- if (dubId && isNewUser) {
- try {
- console.log("Attempting to track lead with Dub...");
- const trackResult = await dub().track.lead({
- clickId: dubId,
- eventName: "Sign Up",
- externalId: user.id,
- customerName: user.name || undefined,
- customerEmail: user.email || undefined,
- customerAvatar: user.image || undefined,
- });
-
- console.log("Dub tracking successful:", trackResult);
-
- (await cookies()).delete("dub_id");
- if (dubPartnerData) {
- (await cookies()).delete("dub_partner_data");
- }
- } catch (error) {
- console.error("Failed to track lead with Dub:", error);
- console.error("Error details:", JSON.stringify(error, null, 2));
- }
- } else if (!isNewUser) {
- console.log(
- "Guest checkout user signing in for the first time - setting up organization",
- );
- }
-
- const organizationId = Organisation.OrganisationId.make(nanoId());
-
- await db()
- .insert(organizations)
- .values({
- id: organizationId,
- name: "My Organization",
- ownerId: User.UserId.make(user.id),
- });
-
- await db()
- .insert(organizationMembers)
- .values({
- id: nanoId(),
- userId: User.UserId.make(user.id),
- organizationId: organizationId,
- role: "owner",
- });
-
- await db()
- .update(users)
- .set({ activeOrganizationId: organizationId })
- .where(eq(users.id, User.UserId.make(user.id)));
- }
- },
- },
callbacks: {
async signIn({ user, email, credentials }) {
const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index d045a0c84..d06d96363 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -71,6 +71,13 @@
"when": 1759993551600,
"tag": "0009_sad_carmella_unuscione",
"breakpoints": true
+ },
+ {
+ "idx": 10,
+ "version": "5",
+ "when": 1760343098514,
+ "tag": "0010_unusual_leo",
+ "breakpoints": true
}
]
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 9c80af165..c7711c51b 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -98,6 +98,13 @@ export const users = mysqlTable(
).$type<Organisation.OrganisationId>(),
created_at: timestamp("created_at").notNull().defaultNow(),
updated_at: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
+ onboardingSteps: json("onboardingSteps").$type<{
+ welcome?: boolean;
+ organizationSetup?: boolean;
+ customDomain?: boolean;
+ inviteTeam?: boolean;
+ download?: boolean;
+ }>(),
onboarding_completed_at: timestamp("onboarding_completed_at"),
customBucket: nanoIdNullable("customBucket"),
inviteQuota: int("inviteQuota").notNull().default(1),
diff --git a/packages/ui/src/components/Button.tsx b/packages/ui/src/components/Button.tsx
index 9a7756922..ea8303698 100644
--- a/packages/ui/src/components/Button.tsx
+++ b/packages/ui/src/components/Button.tsx
@@ -29,6 +29,8 @@ const buttonVariants = cva(
"bg-gradient-to-t button-gradient-border from-[#0f0f0f] to-[#404040] shadow-[0_0_0_1px] hover:brightness-110 shadow-[#383838] text-gray-50 hover:bg-[#383838] disabled:bg-[#383838] border-transparent",
radialblue:
"text-gray-50 border button-gradient-border shadow-[0_0_0_1px] shadow-blue-400 disabled:bg-gray-1 border-0 [background:radial-gradient(90%_100%_at_15%_12%,#9BC4FF_0%,#3588FF_100%)] border-transparent hover:opacity-80",
+ transparent:
+ "bg-transparent text-gray-10 hover:underline transition-all duration-200 hover:text-gray-12",
},
size: {
xs: "text-xs h-[32px]",
diff --git a/packages/web-backend/src/Rpcs.ts b/packages/web-backend/src/Rpcs.ts
index 5f45ea0c6..10bd49404 100644
--- a/packages/web-backend/src/Rpcs.ts
+++ b/packages/web-backend/src/Rpcs.ts
@@ -8,9 +8,14 @@ import { Effect, Layer, Option } from "effect";
import { getCurrentUser } from "./Auth.ts";
import { Database } from "./Database.ts";
import { FolderRpcsLive } from "./Folders/FoldersRpcs.ts";
+import { UsersRpcsLive } from "./Users/UsersRpcs.ts";
import { VideosRpcsLive } from "./Videos/VideosRpcs.ts";
-export const RpcsLive = Layer.mergeAll(VideosRpcsLive, FolderRpcsLive);
+export const RpcsLive = Layer.mergeAll(
+ VideosRpcsLive,
+ FolderRpcsLive,
+ UsersRpcsLive,
+);
export const RpcAuthMiddlewareLive = Layer.effect(
RpcAuthMiddleware,
diff --git a/packages/web-backend/src/Users/UsersOnboarding.ts b/packages/web-backend/src/Users/UsersOnboarding.ts
new file mode 100644
index 000000000..2a8adb534
--- /dev/null
+++ b/packages/web-backend/src/Users/UsersOnboarding.ts
@@ -0,0 +1,225 @@
+import { nanoId } from "@cap/database/helpers";
+import * as Db from "@cap/database/schema";
+import { CurrentUser, Organisation } from "@cap/web-domain";
+import * as Dz from "drizzle-orm";
+import { Effect, Option } from "effect";
+
+import { Database } from "../Database.ts";
+import { S3Buckets } from "../S3Buckets/index.ts";
+
+export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
+ "UsersOnboarding",
+ {
+ effect: Effect.gen(function* () {
+ const db = yield* Database;
+ const s3Buckets = yield* S3Buckets;
+
+ return {
+ welcome: Effect.fn("Onboarding.welcome")(function* (data: {
+ firstName: string;
+ lastName?: string;
+ }) {
+ const currentUser = yield* CurrentUser;
+
+ const [user] = yield* db.use((db) =>
+ db
+ .select()
+ .from(Db.users)
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+
+ yield* db.use((db) =>
+ db
+ .update(Db.users)
+ .set({
+ onboardingSteps: {
+ ...user.onboardingSteps,
+ welcome: true,
+ },
+ name: data.firstName,
+ lastName: data.lastName || "",
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+ }),
+
+ organizationSetup: Effect.fn("Onboarding.organizationSetup")(
+ function* (data: {
+ organizationName: string;
+ organizationIcon?: {
+ data: Uint8Array;
+ contentType: string;
+ fileName: string;
+ };
+ }) {
+ const currentUser = yield* CurrentUser;
+
+ const [user] = yield* db.use((db) =>
+ db
+ .select()
+ .from(Db.users)
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+
+ const organizationId = Organisation.OrganisationId.make(nanoId());
+
+ yield* db.use((db) =>
+ db.transaction(async (tx) => {
+ await tx.insert(Db.organizations).values({
+ id: organizationId,
+ ownerId: currentUser.id,
+ name: data.organizationName,
+ });
+
+ await tx.insert(Db.organizationMembers).values({
+ id: nanoId(),
+ userId: currentUser.id,
+ role: "owner",
+ organizationId,
+ });
+
+ await tx
+ .update(Db.users)
+ .set({
+ activeOrganizationId: organizationId,
+ onboardingSteps: {
+ ...user.onboardingSteps,
+ organizationSetup: true,
+ },
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id));
+ }),
+ );
+
+ if (data.organizationIcon) {
+ const organizationIcon = data.organizationIcon;
+ const uploadEffect = Effect.gen(function* () {
+ const { data: fileData, contentType } = organizationIcon;
+ const allowedExt = new Map<string, string>([
+ ["image/png", "png"],
+ ["image/jpeg", "jpg"],
+ ["image/webp", "webp"],
+ ["image/svg+xml", "svg"],
+ ]);
+ const fileExtension = allowedExt.get(contentType);
+ if (!fileExtension)
+ throw new Error("Unsupported icon content type");
+ const fileKey = `organizations/${organizationId}/icon-${Date.now()}.${fileExtension}`;
+
+ const [bucket] = yield* s3Buckets.getBucketAccess(
+ Option.none(),
+ );
+
+ yield* bucket.putObject(fileKey, fileData, { contentType });
+ const iconUrl = yield* bucket.getSignedObjectUrl(fileKey);
+
+ yield* db.use((db) =>
+ db
+ .update(Db.organizations)
+ .set({ iconUrl })
+ .where(Dz.eq(Db.organizations.id, organizationId)),
+ );
+ }).pipe(
+ Effect.catchAll((error) =>
+ Effect.logError("Failed to upload organization icon", error),
+ ),
+ );
+
+ yield* uploadEffect;
+ }
+
+ return { organizationId };
+ },
+ ),
+
+ customDomain: Effect.fn("Onboarding.customDomain")(function* () {
+ const currentUser = yield* CurrentUser;
+
+ const [user] = yield* db.use((db) =>
+ db
+ .select()
+ .from(Db.users)
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+
+ yield* db.use((db) =>
+ db
+ .update(Db.users)
+ .set({
+ onboardingSteps: {
+ ...user.onboardingSteps,
+ customDomain: true,
+ },
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+ }),
+
+ inviteTeam: Effect.fn("Onboarding.inviteTeam")(function* () {
+ const currentUser = yield* CurrentUser;
+
+ const [user] = yield* db.use((db) =>
+ db
+ .select()
+ .from(Db.users)
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+
+ yield* db.use((db) =>
+ db
+ .update(Db.users)
+ .set({
+ onboardingSteps: {
+ ...user.onboardingSteps,
+ inviteTeam: true,
+ },
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+ }),
+
+ download: Effect.fn("Onboarding.download")(function* () {
+ const currentUser = yield* CurrentUser;
+
+ const [user] = yield* db.use((db) =>
+ db
+ .select()
+ .from(Db.users)
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+
+ yield* db.use((db) =>
+ db
+ .update(Db.users)
+ .set({
+ onboardingSteps: { ...user.onboardingSteps, download: true },
+ onboarding_completed_at: new Date(),
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+ }),
+
+ skipToDashboard: Effect.fn("Onboarding.skipToDashboard")(function* () {
+ const currentUser = yield* CurrentUser;
+
+ yield* db.use((db) =>
+ db
+ .update(Db.users)
+ .set({
+ name: "Cap",
+ onboardingSteps: {
+ welcome: true,
+ organizationSetup: true,
+ customDomain: true,
+ inviteTeam: true,
+ download: true,
+ },
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id)),
+ );
+ }),
+ };
+ }),
+ dependencies: [Database.Default, S3Buckets.Default],
+ },
+) {}
diff --git a/packages/web-backend/src/Users/UsersRpcs.ts b/packages/web-backend/src/Users/UsersRpcs.ts
new file mode 100644
index 000000000..8c6353a04
--- /dev/null
+++ b/packages/web-backend/src/Users/UsersRpcs.ts
@@ -0,0 +1,46 @@
+import { InternalError, User } from "@cap/web-domain";
+import { Effect, Layer } from "effect";
+import { UsersOnboarding } from "./UsersOnboarding";
+
+export const UsersRpcsLive = User.UserRpcs.toLayer(
+ Effect.gen(function* () {
+ const onboarding = yield* UsersOnboarding;
+ return {
+ UserCompleteOnboardingStep: (payload) =>
+ Effect.gen(function* () {
+ switch (payload.step) {
+ case "welcome":
+ yield* onboarding.welcome(payload.data);
+ return { step: "welcome" as const, data: undefined };
+
+ case "organizationSetup": {
+ const result = yield* onboarding.organizationSetup(payload.data);
+ return {
+ step: "organizationSetup" as const,
+ data: result,
+ };
+ }
+ case "customDomain":
+ yield* onboarding.customDomain();
+ return { step: "customDomain" as const, data: undefined };
+
+ case "inviteTeam":
+ yield* onboarding.inviteTeam();
+ return { step: "inviteTeam" as const, data: undefined };
+
+ case "download":
+ yield* onboarding.download();
+ return { step: "download" as const, data: undefined };
+ case "skipToDashboard":
+ yield* onboarding.skipToDashboard();
+ return { step: "skipToDashboard" as const, data: undefined };
+ }
+ }).pipe(
+ Effect.catchTag(
+ "DatabaseError",
+ () => new InternalError({ type: "database" }),
+ ),
+ ),
+ };
+ }),
+).pipe(Layer.provide(UsersOnboarding.Default));
diff --git a/packages/web-backend/src/Users/index.ts b/packages/web-backend/src/Users/index.ts
new file mode 100644
index 000000000..a31bcd919
--- /dev/null
+++ b/packages/web-backend/src/Users/index.ts
@@ -0,0 +1,10 @@
+import { Effect } from "effect";
+import { Database } from "../Database";
+
+export class Users extends Effect.Service<Users>()("Users", {
+ effect: Effect.gen(function* () {
+ yield* Database;
+
+ return {};
+ }),
+}) {}
diff --git a/packages/web-domain/src/Rpcs.ts b/packages/web-domain/src/Rpcs.ts
index 6cb50ece2..1d890286d 100644
--- a/packages/web-domain/src/Rpcs.ts
+++ b/packages/web-domain/src/Rpcs.ts
@@ -1,6 +1,7 @@
import { RpcGroup } from "@effect/rpc";
import { FolderRpcs } from "./Folder.ts";
+import { UserRpcs } from "./User.ts";
import { VideoRpcs } from "./Video.ts";
-export const Rpcs = RpcGroup.make().merge(VideoRpcs, FolderRpcs);
+export const Rpcs = RpcGroup.make().merge(VideoRpcs, FolderRpcs, UserRpcs);
diff --git a/packages/web-domain/src/User.ts b/packages/web-domain/src/User.ts
index 2ef26ac3d..8113a870e 100644
--- a/packages/web-domain/src/User.ts
+++ b/packages/web-domain/src/User.ts
@@ -1,4 +1,85 @@
+import { Rpc, RpcGroup } from "@effect/rpc";
import { Schema } from "effect";
+import { RpcAuthMiddleware } from "./Authentication.ts";
+import { InternalError } from "./Errors.ts";
+import { OrganisationId } from "./Organisation.ts";
+
export const UserId = Schema.String.pipe(Schema.brand("UserId"));
export type UserId = typeof UserId.Type;
+
+export const OnboardingStepPayload = Schema.Union(
+ Schema.Struct({
+ step: Schema.Literal("welcome"),
+ data: Schema.Struct({
+ firstName: Schema.String,
+ lastName: Schema.optional(Schema.String),
+ }),
+ }),
+ Schema.Struct({
+ step: Schema.Literal("organizationSetup"),
+ data: Schema.Struct({
+ organizationName: Schema.String,
+ organizationIcon: Schema.optional(
+ Schema.Struct({
+ data: Schema.Uint8Array,
+ contentType: Schema.String,
+ fileName: Schema.String,
+ }),
+ ),
+ }),
+ }),
+ Schema.Struct({
+ step: Schema.Literal("customDomain"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("inviteTeam"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("download"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("skipToDashboard"),
+ data: Schema.Void,
+ }),
+);
+
+export const OnboardingStepResult = Schema.Union(
+ Schema.Struct({
+ step: Schema.Literal("welcome"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("organizationSetup"),
+ data: Schema.Struct({
+ organizationId: OrganisationId,
+ }),
+ }),
+ Schema.Struct({
+ step: Schema.Literal("customDomain"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("inviteTeam"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("download"),
+ data: Schema.Void,
+ }),
+ Schema.Struct({
+ step: Schema.Literal("skipToDashboard"),
+ data: Schema.Void,
+ }),
+);
+
+export class UserRpcs extends RpcGroup.make(
+ Rpc.make("UserCompleteOnboardingStep", {
+ payload: OnboardingStepPayload,
+ success: OnboardingStepResult,
+ error: InternalError,
+ }).middleware(RpcAuthMiddleware),
+) {}