www_site/components/account-panel.tsx

72 lines
7.5 KiB
TypeScript
Raw Normal View History

"use client";
import Link from "next/link";
import { FormEvent, useEffect, useState } from "react";
import { ArrowRight } from "@/components/icons";
import { BrandIcon } from "@/components/brand-icon";
import { PreviewNotice, StatusCard } from "@/components/ui";
const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL ?? "/api/v1";
type User = { email: string | null; phone: string | null; username: string; role: "user" | "admin"; plan: "free" | "vip"; status: string; email_verified: boolean; phone_verified: boolean };
type Usage = { period_start: string; period_end: string; limit: number; adjustment: number; used: number; reserved: number; available: number; plan: string };
export function AccountPanel() {
const [csrf, setCsrf] = useState("");
const [user, setUser] = useState<User | null>(null);
const [usage, setUsage] = useState<Usage | null>(null);
const [error, setError] = useState("");
const [passwordMessage, setPasswordMessage] = useState("");
const [profileMessage, setProfileMessage] = useState("");
async function load() {
const csrfResponse = await fetch(`${apiBase}/auth/csrf`, { credentials: "include" });
const csrfBody = await csrfResponse.json();
setCsrf(csrfBody.csrf_token ?? "");
const [meResponse, usageResponse] = await Promise.all([
fetch(`${apiBase}/auth/me`, { credentials: "include" }),
fetch(`${apiBase}/account/usage`, { credentials: "include" }),
]);
if (!meResponse.ok) throw new Error("请先登录后查看账户");
setUser(await meResponse.json());
if (usageResponse.ok) setUsage(await usageResponse.json());
}
useEffect(() => { load().catch((loadError) => setError(loadError instanceof Error ? loadError.message : "无法加载账户")); }, []);
async function logout() {
await fetch(`${apiBase}/auth/logout`, { method: "POST", credentials: "include", headers: { "X-CSRF-Token": csrf } });
window.location.assign("/login");
}
async function changePassword(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const data = new FormData(form);
const response = await fetch(`${apiBase}/auth/password/change`, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf }, body: JSON.stringify({ current_password: data.get("current_password"), new_password: data.get("new_password") }) });
const body = await response.json().catch(() => ({}));
if (!response.ok) setPasswordMessage(body.error?.message ?? body.detail?.message ?? "密码修改失败");
else { setPasswordMessage("密码已修改,其他会话已撤销"); form.reset(); }
}
async function updateProfile(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const response = await fetch(`${apiBase}/auth/profile`, { method: "PATCH", credentials: "include", headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf }, body: JSON.stringify({ username: data.get("username"), email: data.get("email") || null, phone: data.get("phone") || null }) });
const body = await response.json().catch(() => ({}));
if (!response.ok) setProfileMessage(body.error?.message ?? body.detail?.message ?? "资料保存失败");
else { setUser(body); setProfileMessage("资料已保存;如修改邮箱或手机号,请重新完成验证"); }
}
if (error) return <div className="mt-8"><PreviewNotice>{error}<Link className="text-cyan underline" href="/login"></Link></PreviewNotice></div>;
if (!user || !usage) return <div className="mt-8"><StatusCard title="正在加载账户" description="正在从业务 API 读取当前用户和额度。" tone="info" /></div>;
return <>
<div className="mt-8 grid gap-5 md:grid-cols-2 lg:grid-cols-4"><StatusCard title="账户状态" description={user.status === "active" ? "正常" : "已停用"} tone="success" /><StatusCard title="会员计划" description={usage.plan.toUpperCase()} /><StatusCard title="可用额度" description={`${usage.available.toLocaleString()} 字符`} tone="info" /><StatusCard title="验证状态" description={`邮箱 ${user.email_verified ? "已验证" : "未验证"} · 手机 ${user.phone_verified ? "已验证" : "未验证"}`} tone="warning" /></div>
<div className="mt-8 grid gap-6 lg:grid-cols-[0.8fr_1.2fr]">
<section className="rounded-2xl border border-line bg-panel/60 p-6"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-subtle">Profile</p><h2 className="mt-3 text-xl font-semibold"></h2><form className="mt-6 space-y-4" onSubmit={updateProfile}><div><label className="field-label" htmlFor="profile-username"></label><input className="field-input" id="profile-username" name="username" required defaultValue={user.username} /></div><div><label className="field-label" htmlFor="profile-email"></label><input className="field-input" id="profile-email" name="email" type="email" defaultValue={user.email ?? ""} /></div><div><label className="field-label" htmlFor="profile-phone"></label><input className="field-input" id="profile-phone" name="phone" defaultValue={user.phone ?? ""} /></div>{profileMessage ? <p className="text-sm text-muted" role="status">{profileMessage}</p> : null}<button className="button-secondary w-full" type="submit"><BrandIcon /></button></form>{user.role === "admin" ? <div className="mt-6 space-y-4 border-t border-line pt-5"><div className="flex justify-between gap-4 text-sm"><dt className="text-muted"></dt><dd><Link className="text-cyan hover:text-copy" href="/admin"></Link></dd></div><div className="flex justify-between gap-4 text-sm"><dt className="text-muted"></dt><dd><a className="text-cyan hover:text-copy" href="/cms/admin"> CMS</a></dd></div></div> : null}<button className="button-ghost mt-7 w-full" onClick={logout} type="button"><BrandIcon />退 <ArrowRight /></button></section>
<div className="space-y-6"><section className="rounded-2xl border border-line bg-panel/60 p-6"><div className="flex items-center justify-between gap-4"><div><p className="text-xs font-semibold uppercase tracking-[0.18em] text-subtle">Usage</p><h2 className="mt-3 text-xl font-semibold"></h2></div><Link className="text-sm text-cyan hover:text-copy" href="/tts"></Link></div><div className="mt-6 grid gap-4 sm:grid-cols-3"><StatusCard title="周期上限" description={usage.limit.toLocaleString()} /><StatusCard title="已使用" description={usage.used.toLocaleString()} /><StatusCard title="冻结" description={usage.reserved.toLocaleString()} /></div></section><section className="rounded-2xl border border-line bg-panel/60 p-6"><p className="text-xs font-semibold uppercase tracking-[0.18em] text-subtle">Security</p><h2 className="mt-3 text-xl font-semibold"></h2><form className="mt-5 grid gap-4 sm:grid-cols-2" onSubmit={changePassword}><div><label className="field-label" htmlFor="current-password"></label><input className="field-input" id="current-password" name="current_password" required type="password" /></div><div><label className="field-label" htmlFor="new-password"></label><input className="field-input" id="new-password" minLength={8} name="new_password" required type="password" /></div>{passwordMessage ? <p className="sm:col-span-2 text-sm text-muted" role="status">{passwordMessage}</p> : null}<button className="button-secondary sm:col-span-2" type="submit"><BrandIcon /></button></form></section></div>
</div>
</>;
}