feat(onboarding): create-workspace flow

- /onboarding page (server component): redirects to /sign-in if not authed,
  to /dashboard if user already has a team. Otherwise renders form.
- createWorkspaceAction:
  * teams.create (user becomes owner via session SDK)
  * tablesDB.createRow on tenant_settings (admin SDK) with team-scoped permissions:
    Permission.read(Role.team(id)), update(owner|admin), delete(owner)
  * account.updatePrefs({ activeTenant }) — persisted source of truth
  * isletmem-tenant cookie for fast access
  * redirect to /dashboard
- setActiveTenantAction stub for future workspace switcher
- lib/appwrite/tenant.ts: getUserTeams, getActiveTenantId helpers (server-only)
- tenant-types.ts holds WorkspaceState + ACTIVE_TENANT_COOKIE (no 'use server')
This commit is contained in:
kovakmedya
2026-04-30 03:22:48 +03:00
parent 647716e042
commit 30cbb8f1be
5 changed files with 281 additions and 0 deletions
@@ -0,0 +1,112 @@
"use client";
import { useActionState } from "react";
import { Building2, Loader2, ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Logo } from "@/components/logo";
import { createWorkspaceAction } from "@/lib/appwrite/tenant-actions";
import { initialWorkspaceState } from "@/lib/appwrite/tenant-types";
export function CreateWorkspaceForm({ userName }: { userName?: string }) {
const [state, formAction, isPending] = useActionState(
createWorkspaceAction,
initialWorkspaceState,
);
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-center gap-2 font-medium">
<div className="bg-primary text-primary-foreground flex size-9 items-center justify-center rounded-md">
<Logo size={22} />
</div>
<span className="text-xl font-semibold">İşletmem</span>
</div>
<Card>
<CardHeader className="text-center">
<div className="bg-primary/10 text-primary mx-auto mb-2 flex size-12 items-center justify-center rounded-full">
<Building2 className="size-6" />
</div>
<CardTitle className="text-2xl">
{userName ? `Hoş geldiniz, ${userName}` : "Çalışma alanı oluştur"}
</CardTitle>
<CardDescription>
Şirketinizin bilgilerini girin birkaç saniyede çalışma alanınız hazır.
</CardDescription>
</CardHeader>
<CardContent>
<form action={formAction} className="flex flex-col gap-5">
<div className="grid gap-3">
<Label htmlFor="companyName">Şirket adı *</Label>
<Input
id="companyName"
name="companyName"
type="text"
placeholder="KovakSoft Yazılım Ltd."
autoComplete="organization"
required
autoFocus
/>
</div>
<div className="grid gap-3">
<Label htmlFor="companyTaxId">
Vergi numarası <span className="text-muted-foreground text-xs">(opsiyonel)</span>
</Label>
<Input
id="companyTaxId"
name="companyTaxId"
type="text"
placeholder="1234567890"
inputMode="numeric"
/>
</div>
<div className="grid gap-3">
<Label htmlFor="companyPhone">
Telefon <span className="text-muted-foreground text-xs">(opsiyonel)</span>
</Label>
<Input
id="companyPhone"
name="companyPhone"
type="tel"
placeholder="+90 555 123 45 67"
autoComplete="tel"
/>
</div>
{state.error && (
<p className="text-destructive text-sm text-center" role="alert">
{state.error}
</p>
)}
<Button type="submit" className="w-full" disabled={isPending}>
{isPending ? (
<>
<Loader2 className="size-4 animate-spin" />
Hazırlanıyor...
</>
) : (
"Çalışma alanını oluştur"
)}
</Button>
<p className="text-muted-foreground flex items-center justify-center gap-1.5 text-xs">
<ShieldCheck className="size-3.5" />
Verileriniz yalnızca sizin ekibinize özel multi-tenant izolasyon
</p>
</form>
</CardContent>
</Card>
<p className="text-muted-foreground text-center text-xs">
Bu bilgileri daha sonra Profil ayarlarından düzenleyebilirsiniz.
</p>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/appwrite/server";
import { getUserTeams } from "@/lib/appwrite/tenant";
import { CreateWorkspaceForm } from "./components/create-workspace-form";
export const metadata: Metadata = {
title: "İşletmem — Çalışma alanı oluştur",
description: "İşletmem için ilk çalışma alanınızı kurun.",
};
export default async function OnboardingPage() {
const user = await getCurrentUser();
if (!user) redirect("/sign-in");
const teams = await getUserTeams();
if (teams && teams.total > 0) {
redirect("/dashboard");
}
return (
<div className="bg-muted flex min-h-svh flex-col items-center justify-center p-6 md:p-10">
<div className="w-full max-w-md">
<CreateWorkspaceForm userName={user.name?.split(" ")[0]} />
</div>
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { AppwriteException, ID, Permission, Role } from "node-appwrite";
import { createAdminClient, createSessionClient } from "./server";
import { DATABASE_ID, TABLES } from "./schema";
import { ACTIVE_TENANT_COOKIE, type WorkspaceState } from "./tenant-types";
function appwriteError(e: unknown): string {
if (e instanceof AppwriteException) {
if (e.type === "team_already_exists") return "Bu isimde bir çalışma alanı zaten var.";
if (e.type === "general_unauthorized_scope") return "Yetki hatası. Tekrar giriş yapın.";
return e.message || "Beklenmeyen bir hata oluştu.";
}
return "Bağlantı hatası. Tekrar deneyin.";
}
async function setActiveTenantCookie(tenantId: string) {
(await cookies()).set(ACTIVE_TENANT_COOKIE, tenantId, {
path: "/",
httpOnly: true,
sameSite: "strict",
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 365,
});
}
export async function createWorkspaceAction(
_prev: WorkspaceState,
formData: FormData,
): Promise<WorkspaceState> {
const companyName = String(formData.get("companyName") ?? "").trim();
const companyTaxId = String(formData.get("companyTaxId") ?? "").trim() || undefined;
const companyPhone = String(formData.get("companyPhone") ?? "").trim() || undefined;
if (!companyName) {
return { ok: false, error: "Şirket adı zorunlu." };
}
let teamId: string;
try {
const session = await createSessionClient();
const user = await session.account.get();
const team = await session.teams.create(ID.unique(), companyName, ["owner"]);
teamId = team.$id;
const admin = createAdminClient();
await admin.tablesDB.createRow(
DATABASE_ID,
TABLES.tenantSettings,
ID.unique(),
{
tenantId: teamId,
companyName,
companyTaxId,
companyPhone,
createdBy: user.$id,
},
[
Permission.read(Role.team(teamId)),
Permission.update(Role.team(teamId, "owner")),
Permission.update(Role.team(teamId, "admin")),
Permission.delete(Role.team(teamId, "owner")),
],
);
await session.account.updatePrefs({
...(user.prefs ?? {}),
activeTenant: teamId,
});
await setActiveTenantCookie(teamId);
} catch (e) {
return { ok: false, error: appwriteError(e) };
}
redirect("/dashboard");
}
export async function setActiveTenantAction(tenantId: string) {
try {
const { account } = await createSessionClient();
const user = await account.get();
const teams = await (await createSessionClient()).teams.list();
const owns = teams.teams.some((t) => t.$id === tenantId);
if (!owns) {
return { ok: false, error: "Bu çalışma alanına erişiminiz yok." };
}
await account.updatePrefs({ ...(user.prefs ?? {}), activeTenant: tenantId });
await setActiveTenantCookie(tenantId);
return { ok: true };
} catch (e) {
return { ok: false, error: appwriteError(e) };
}
}
+8
View File
@@ -0,0 +1,8 @@
export type WorkspaceState = {
ok: boolean;
error?: string;
};
export const initialWorkspaceState: WorkspaceState = { ok: false };
export const ACTIVE_TENANT_COOKIE = "isletmem-tenant";
+31
View File
@@ -0,0 +1,31 @@
import "server-only";
import { cookies } from "next/headers";
import { createSessionClient } from "./server";
import { ACTIVE_TENANT_COOKIE } from "./tenant-types";
export async function getUserTeams() {
try {
const { teams } = await createSessionClient();
return await teams.list();
} catch {
return null;
}
}
export async function getActiveTenantId(): Promise<string | null> {
const cookie = (await cookies()).get(ACTIVE_TENANT_COOKIE)?.value;
if (cookie) return cookie;
try {
const { account } = await createSessionClient();
const user = await account.get();
const fromPrefs = (user.prefs as Record<string, unknown> | undefined)?.activeTenant;
if (typeof fromPrefs === "string" && fromPrefs.length > 0) return fromPrefs;
} catch {
return null;
}
return null;
}