feat(portal): add client settings routes and translations

This commit is contained in:
poyrazavsever
2026-07-21 12:49:55 +03:00
parent fcc6f2078a
commit 48f9d7bc87
15 changed files with 1720 additions and 68 deletions
+33
View File
@@ -0,0 +1,33 @@
"use server";
import { cookies } from "next/headers";
import { revalidatePath } from "next/cache";
import {
COLOR_MODE_COOKIE,
COLOR_MODE_COOKIE_MAX_AGE,
} from "@/lib/color-mode";
import { getServerConfig } from "@/server/config";
import { updateColorModePreference } from "@/server/settings/preferences";
import { requirePortalBackend } from "@/server/web/portal";
export async function savePortalColorModeAction(colorMode: string) {
try {
const { actor } = await requirePortalBackend();
const preferences = updateColorModePreference(actor, { colorMode });
const config = getServerConfig();
(await cookies()).set(COLOR_MODE_COOKIE, preferences.colorMode, {
httpOnly: false,
maxAge: COLOR_MODE_COOKIE_MAX_AGE,
path: "/",
sameSite: "lax",
secure: config.secureCookies,
});
revalidatePath("/", "layout");
revalidatePath("/portal", "layout");
revalidatePath("/portal/settings/appearance");
return { success: true, colorMode: preferences.colorMode };
} catch (error) {
console.error("Portal color mode update failed", error);
return { errorKey: "settings.appearance.errors.colorMode" };
}
}
+10
View File
@@ -0,0 +1,10 @@
import { getUserPreferences } from "@/server/settings/preferences";
import { requirePortalBackend } from "@/server/web/portal";
import { PortalAppearanceForm } from "./portal-appearance-form";
export default async function PortalAppearanceSettingsPage() {
const { actor } = await requirePortalBackend();
const preferences = getUserPreferences(actor);
return <PortalAppearanceForm initialColorMode={preferences.colorMode} />;
}
@@ -0,0 +1,113 @@
"use client";
import { useState, useTransition } from "react";
import { Monitor, Moon, Sun } from "lucide-react";
import { Button, Card, CardContent, Label, RadioGroup, RadioGroupItem } from "poyraz-ui/atoms";
import { toast } from "poyraz-ui/molecules";
import { useTranslations } from "@/components/i18n/i18n-provider";
import { applyColorMode } from "@/components/theme/color-mode-sync";
import { isColorMode, type ColorMode } from "@/lib/color-mode";
import { savePortalColorModeAction } from "./actions";
const themeOptions = [
{ value: "light", icon: Sun },
{ value: "dark", icon: Moon },
{ value: "system", icon: Monitor },
] as const;
export function PortalAppearanceForm({
initialColorMode,
}: {
initialColorMode: ColorMode;
}) {
const t = useTranslations();
const [colorMode, setColorMode] = useState(initialColorMode);
const [pending, startTransition] = useTransition();
function changeColorMode(value: string) {
if (!isColorMode(value) || value === colorMode || pending) return;
const previous = colorMode;
setColorMode(value);
applyColorMode(value);
startTransition(async () => {
const result = await savePortalColorModeAction(value);
if (result.errorKey) {
setColorMode(previous);
applyColorMode(previous);
toast.error(t(result.errorKey));
return;
}
toast.success(t("settings.appearance.messages.themeSaved"));
});
}
return (
<Card>
<CardContent className="space-y-6 p-6 sm:p-8">
<div className="space-y-1.5">
<h2 className="text-xl font-semibold text-foreground">
{t("settings.portal.appearance.title")}
</h2>
<p className="max-w-2xl text-sm text-muted-foreground">
{t("settings.portal.appearance.description")}
</p>
</div>
<RadioGroup
value={colorMode}
onValueChange={changeColorMode}
disabled={pending}
aria-label={t("settings.appearance.theme.ariaLabel")}
className="grid gap-3 sm:grid-cols-3"
>
{themeOptions.map((option) => {
const Icon = option.icon;
const selected = colorMode === option.value;
return (
<Label
key={option.value}
htmlFor={`portal-color-mode-${option.value}`}
className={`flex min-h-36 cursor-pointer flex-col justify-between gap-5 rounded-md border p-4 transition-colors ${
selected
? "border-primary bg-primary/5 ring-1 ring-primary"
: "border-border bg-card hover:border-primary/50 hover:bg-muted/40"
}`}
>
<div className="flex items-start justify-between gap-3">
<span className="flex h-10 w-10 items-center justify-center rounded-md border border-border bg-muted text-muted-foreground">
<Icon className="h-5 w-5" aria-hidden="true" />
</span>
<RadioGroupItem
id={`portal-color-mode-${option.value}`}
value={option.value}
aria-label={t(`settings.appearance.theme.${option.value}.label`)}
/>
</div>
<span className="space-y-1">
<span className="block text-sm font-semibold text-foreground">
{t(`settings.appearance.theme.${option.value}.label`)}
</span>
<span className="block text-xs font-normal text-muted-foreground">
{t(`settings.appearance.theme.${option.value}.description`)}
</span>
</span>
</Label>
);
})}
</RadioGroup>
<div className="rounded-md border border-dashed border-border bg-muted/20 p-4 text-sm text-muted-foreground">
{t("settings.portal.appearance.brandingNotice")}
</div>
<div className="flex justify-end border-t border-border pt-6">
<Button type="button" variant="secondary" effect="shine" loading={pending} disabled>
{t("settings.portal.appearance.autoSave")}
</Button>
</div>
</CardContent>
</Card>
);
}
+67
View File
@@ -0,0 +1,67 @@
"use server";
import { revalidatePath } from "next/cache";
import { eq } from "drizzle-orm";
import { getSqliteConnection } from "@/server/db/client";
import {
clients,
instanceI18nSettings,
instanceLocales,
} from "@/server/db/schema";
import { updateLanguagePreference } from "@/server/settings/preferences";
import { requirePortalBackend } from "@/server/web/portal";
export async function savePortalLanguagePreferenceAction(language: string) {
try {
const { actor } = await requirePortalBackend();
const preferences = updateLanguagePreference(actor, { language });
revalidatePortalSettings();
return { success: true, language: preferences.language };
} catch (error) {
console.error("Portal language preference update failed", error);
return { errorKey: "settings.languagePreference.errors.saveFailed" };
}
}
export async function resetPortalLanguagePreferenceAction() {
try {
const { actor, context } = await requirePortalBackend();
const language = readClientAssignedLanguage(context.profile.clientId);
const preferences = updateLanguagePreference(actor, { language });
revalidatePortalSettings();
return { success: true, language: preferences.language };
} catch (error) {
console.error("Portal language preference reset failed", error);
return { errorKey: "settings.portal.language.errors.resetFailed" };
}
}
function readClientAssignedLanguage(clientId: string | null) {
const { db } = getSqliteConnection();
const defaultLocale = db
.select({ defaultLocale: instanceI18nSettings.defaultLocale })
.from(instanceI18nSettings)
.where(eq(instanceI18nSettings.key, "default"))
.get()?.defaultLocale ?? "tr";
const portalLocale = clientId
? db
.select({ portalLocale: clients.portalLocale })
.from(clients)
.where(eq(clients.id, clientId))
.get()?.portalLocale
: null;
const candidate = portalLocale ?? defaultLocale;
const active = db
.select({ code: instanceLocales.code, status: instanceLocales.status })
.from(instanceLocales)
.where(eq(instanceLocales.code, candidate))
.get();
return active?.status === "active" ? candidate : defaultLocale;
}
function revalidatePortalSettings() {
revalidatePath("/", "layout");
revalidatePath("/portal", "layout");
revalidatePath("/portal/settings/language");
}
+54
View File
@@ -0,0 +1,54 @@
import { eq } from "drizzle-orm";
import { getSqliteConnection } from "@/server/db/client";
import {
clients,
instanceI18nSettings,
instanceLocales,
} from "@/server/db/schema";
import { resolvePortalLocale } from "@/server/i18n/resolver";
import { getUserPreferences } from "@/server/settings/preferences";
import { requirePortalBackend } from "@/server/web/portal";
import { PortalLanguagePreferenceForm } from "./portal-language-preference-form";
export default async function PortalLanguageSettingsPage() {
const { actor, context } = await requirePortalBackend();
const { db } = getSqliteConnection();
const activeLocales = db
.select({
code: instanceLocales.code,
name: instanceLocales.name,
nativeName: instanceLocales.nativeName,
})
.from(instanceLocales)
.where(eq(instanceLocales.status, "active"))
.all();
const defaultLocale = db
.select({ defaultLocale: instanceI18nSettings.defaultLocale })
.from(instanceI18nSettings)
.where(eq(instanceI18nSettings.key, "default"))
.get()?.defaultLocale ?? "tr";
const rawAssignedLanguage = context.profile.clientId
? db
.select({ portalLocale: clients.portalLocale })
.from(clients)
.where(eq(clients.id, context.profile.clientId))
.get()?.portalLocale ?? defaultLocale
: defaultLocale;
const assignedLanguage = activeLocales.some((locale) => locale.code === rawAssignedLanguage)
? rawAssignedLanguage
: defaultLocale;
const preferredLanguage = getUserPreferences(actor).language;
const resolved = await resolvePortalLocale(context);
const preferenceIsActive = activeLocales.some(
(locale) => locale.code === preferredLanguage,
);
return (
<PortalLanguagePreferenceForm
activeLocales={activeLocales}
assignedLanguage={assignedLanguage}
initialLanguage={preferenceIsActive ? preferredLanguage : resolved.locale}
preferenceNeedsSelection={!preferenceIsActive}
/>
);
}
@@ -0,0 +1,159 @@
"use client";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { AlertTriangle, Check, Globe2, RotateCcw, Save } from "lucide-react";
import { Badge, Button, Card, CardContent, Label, RadioGroup, RadioGroupItem } from "poyraz-ui/atoms";
import { Alert, AlertDescription, AlertTitle, toast } from "poyraz-ui/molecules";
import { useTranslations } from "@/components/i18n/i18n-provider";
import {
resetPortalLanguagePreferenceAction,
savePortalLanguagePreferenceAction,
} from "./actions";
type LocaleOption = {
code: string;
name: string;
nativeName: string;
};
export function PortalLanguagePreferenceForm({
activeLocales,
assignedLanguage,
initialLanguage,
preferenceNeedsSelection,
}: {
activeLocales: LocaleOption[];
assignedLanguage: string;
initialLanguage: string;
preferenceNeedsSelection: boolean;
}) {
const t = useTranslations();
const router = useRouter();
const [language, setLanguage] = useState(initialLanguage);
const [pending, startTransition] = useTransition();
const assignedLocale = activeLocales.find((locale) => locale.code === assignedLanguage);
function submit() {
startTransition(async () => {
const result = await savePortalLanguagePreferenceAction(language);
if (result.errorKey) {
toast.error(t(result.errorKey));
return;
}
toast.success(t("settings.languagePreference.messages.saved"));
router.refresh();
});
}
function reset() {
startTransition(async () => {
const result = await resetPortalLanguagePreferenceAction();
if (result.errorKey) {
toast.error(t(result.errorKey));
return;
}
setLanguage(result.language ?? assignedLanguage);
toast.success(t("settings.portal.language.messages.reset"));
router.refresh();
});
}
return (
<Card>
<CardContent className="space-y-8 p-6 sm:p-8">
<div className="space-y-1.5">
<h2 className="text-xl font-semibold text-foreground">
{t("settings.portal.language.title")}
</h2>
<p className="max-w-2xl text-sm text-muted-foreground">
{t("settings.portal.language.description")}
</p>
</div>
<Alert>
<Globe2 className="h-4 w-4" aria-hidden="true" />
<AlertTitle>{t("settings.portal.language.assigned.title")}</AlertTitle>
<AlertDescription>
{assignedLocale
? t("settings.portal.language.assigned.value", {
language: assignedLocale.nativeName,
code: assignedLocale.code,
})
: assignedLanguage}
</AlertDescription>
</Alert>
{preferenceNeedsSelection && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" aria-hidden="true" />
<AlertTitle>{t("settings.languagePreference.fallback.title")}</AlertTitle>
<AlertDescription>
{t("settings.languagePreference.fallback.description")}
</AlertDescription>
</Alert>
)}
<RadioGroup
value={language}
onValueChange={setLanguage}
className="grid gap-3 sm:grid-cols-2"
aria-label={t("settings.languagePreference.listAriaLabel")}
>
{activeLocales.map((locale) => (
<Label
key={locale.code}
htmlFor={`portal-language-${locale.code}`}
className="flex cursor-pointer items-center gap-4 rounded-xl border border-border bg-card p-4 transition-colors hover:bg-accent/50"
>
<RadioGroupItem id={`portal-language-${locale.code}`} value={locale.code} />
<span className="min-w-0 flex-1">
<span className="block font-medium text-foreground">
{locale.nativeName}
</span>
<span className="block text-sm text-muted-foreground">
{locale.name} · {locale.code}
</span>
</span>
{language === locale.code && (
<Check className="h-4 w-4 text-primary" aria-hidden="true" />
)}
{assignedLanguage === locale.code && (
<Badge variant="secondary">
{t("settings.portal.language.assigned.badge")}
</Badge>
)}
</Label>
))}
</RadioGroup>
<div className="flex flex-col-reverse gap-3 border-t border-border pt-6 sm:flex-row sm:justify-end">
<Button
type="button"
variant="secondary"
effect="shine"
loading={pending}
disabled={language === assignedLanguage}
onClick={reset}
className="gap-2"
>
<RotateCcw className="h-4 w-4" aria-hidden="true" />
{t("settings.portal.language.actions.reset")}
</Button>
<Button
type="button"
variant="default"
effect="shine"
loading={pending}
disabled={!language}
onClick={submit}
className="gap-2"
>
<Save className="h-4 w-4" aria-hidden="true" />
{t("settings.languagePreference.actions.save")}
</Button>
</div>
</CardContent>
</Card>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { PageHeader } from "@/components/system/page-header";
import { resolvePortalLocale } from "@/server/i18n/resolver";
import { createTranslator } from "@/server/i18n/translator";
import { requirePortalBackend } from "@/server/web/portal";
import { PortalSettingsNavigation } from "./settings-navigation";
export default async function PortalSettingsLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
const { context } = await requirePortalBackend();
const locale = await resolvePortalLocale(context);
const t = createTranslator(locale.locale, ["settings"]).t;
return (
<div className="mx-auto flex max-w-7xl flex-col gap-6">
<PageHeader title={t("settings.portal.title")} />
<div className="flex min-w-0 flex-col gap-8 md:flex-row md:items-start">
<PortalSettingsNavigation
labels={{
language: t("settings.navigation.language"),
appearance: t("settings.navigation.appearance"),
profile: t("settings.navigation.profile"),
security: t("settings.navigation.security"),
}}
/>
<section className="min-w-0 flex-1">{children}</section>
</div>
</div>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function PortalSettingsPage() {
redirect("/portal/settings/language");
}
+23
View File
@@ -0,0 +1,23 @@
import { Card, CardContent } from "poyraz-ui/atoms";
import { createTranslator } from "@/server/i18n/translator";
import { resolvePortalLocale } from "@/server/i18n/resolver";
import { requirePortalBackend } from "@/server/web/portal";
export default async function PortalProfileSettingsPage() {
const { context } = await requirePortalBackend();
const locale = await resolvePortalLocale(context);
const t = createTranslator(locale.locale, ["settings"]).t;
return (
<Card>
<CardContent className="space-y-2 p-6 sm:p-8">
<h2 className="text-xl font-semibold text-foreground">
{t("settings.portal.profile.title")}
</h2>
<p className="text-sm text-muted-foreground">
{t("settings.portal.profile.description")}
</p>
</CardContent>
</Card>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { Card, CardContent } from "poyraz-ui/atoms";
import { createTranslator } from "@/server/i18n/translator";
import { resolvePortalLocale } from "@/server/i18n/resolver";
import { requirePortalBackend } from "@/server/web/portal";
export default async function PortalSecuritySettingsPage() {
const { context } = await requirePortalBackend();
const locale = await resolvePortalLocale(context);
const t = createTranslator(locale.locale, ["settings"]).t;
return (
<Card>
<CardContent className="space-y-2 p-6 sm:p-8">
<h2 className="text-xl font-semibold text-foreground">
{t("settings.portal.security.title")}
</h2>
<p className="text-sm text-muted-foreground">
{t("settings.portal.security.description")}
</p>
</CardContent>
</Card>
);
}
@@ -0,0 +1,55 @@
"use client";
import { Languages, Palette, Shield, User } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Button } from "poyraz-ui/atoms";
export type PortalSettingsNavigationLabels = {
appearance: string;
language: string;
profile: string;
security: string;
};
const items = [
{ key: "language", href: "/portal/settings/language", icon: Languages },
{ key: "appearance", href: "/portal/settings/appearance", icon: Palette },
{ key: "profile", href: "/portal/settings/profile", icon: User },
{ key: "security", href: "/portal/settings/security", icon: Shield },
] as const;
export function PortalSettingsNavigation({
labels,
}: {
labels: PortalSettingsNavigationLabels;
}) {
const pathname = usePathname();
return (
<nav
aria-label={labels.language}
className="tiny-scrollbar flex w-full shrink-0 gap-2 overflow-x-auto pb-2 md:sticky md:top-8 md:max-h-[calc(100vh-4rem)] md:w-60 md:self-start md:flex-col md:overflow-y-auto md:pb-0"
>
{items.map((item) => {
const Icon = item.icon;
const active = pathname === item.href || pathname.startsWith(`${item.href}/`);
return (
<Button
key={item.href}
asChild
effect="shine"
variant={active ? "default" : "secondary"}
className="h-auto shrink-0 justify-start gap-3 px-4 py-3 text-left"
>
<Link href={item.href} aria-current={active ? "page" : undefined}>
<Icon className="h-4 w-4" aria-hidden="true" />
{labels[item.key]}
</Link>
</Button>
);
})}
</nav>
);
}