www_site/components/account-panel.tsx

62 lines
6.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 { PreviewNotice, StatusCard } from "@/components/ui";
const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL ?? "/api/v1";
2026-09-11 08:52:29 +00:00
type User = { email: string; 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("");
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;
setPasswordMessage("");
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 ?? "密码修改失败");
else { setPasswordMessage("密码已修改,其他会话已撤销"); form.reset(); }
}
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]">
2026-09-11 09:29:55 +00:00
<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><dl className="mt-6 space-y-5 text-sm"><div className="flex justify-between gap-4 border-b border-line pb-4"><dt className="text-muted"></dt><dd className="text-copy">{user.username}</dd></div><div className="flex justify-between gap-4 border-b border-line pb-4"><dt className="text-muted"></dt><dd className="text-copy">{user.email}</dd></div><div className="flex justify-between gap-4 border-b border-line pb-4"><dt className="text-muted"></dt><dd className="text-copy">{user.role}</dd></div>{user.role === "admin" ? <><div className="flex justify-between gap-4 border-b border-line pb-4"><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 border-b border-line pb-4"><dt className="text-muted"></dt><dd><a className="text-cyan hover:text-copy" href="/cms/admin"> CMS</a></dd></div></> : null}<div className="flex justify-between gap-4"><dt className="text-muted"></dt><dd className="text-right text-subtle">{new Date(usage.period_start).toLocaleDateString()} {new Date(usage.period_end).toLocaleDateString()}</dd></div></dl><button className="button-ghost mt-7 w-full" onClick={logout} type="button">退 <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"></button></form></section></div>
</div>
</>;
}