支持自部署需求管理、交付流程与飞书集成
This commit is contained in:
1 parent
2149aeb6ed
commit
51a2e548f2
152 files changed
+8652
-6394
No files matched your search
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { appPath } from '@/lib/base-path';
|
||||
import type { FeishuBinding } from '@/lib/feishu';
|
||||
|
||||
export function FeishuAccount({ binding, configured, passwordSet = true }: { binding: FeishuBinding; configured: boolean; passwordSet?: boolean }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState('');
|
||||
async function unbind(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const password = new FormData(form).get('password');
|
||||
setBusy(true); setError(''); setSuccess('');
|
||||
try {
|
||||
const response = await fetch(appPath('/api/account/feishu'), { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || '解绑失败,请重试。');
|
||||
form.reset(); setSuccess('已解除飞书绑定,其他设备的登录已失效。'); router.replace('/account/feishu'); router.refresh();
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '网络异常,请重试。'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <div>
|
||||
{error && <div className="error-banner" role="alert">{error}</div>}
|
||||
{success && <div className="account-success" role="status">{success}</div>}
|
||||
{binding ? <>
|
||||
<p className="feishu-binding-name">已绑定:<strong>{binding.name}</strong></p>
|
||||
{!passwordSet ? <>
|
||||
<p className="account-intro">当前账号通过飞书注册,尚未设置系统密码。请先设置密码,再解除绑定。</p>
|
||||
<Link className="btn" href="/account/password">设置系统密码</Link>
|
||||
</> : <>
|
||||
<p className="account-intro">解除绑定需验证系统密码,其他设备需重新登录。解绑后此飞书身份再次登录会创建新账号;原需求仍可通过当前账号密码访问。</p>
|
||||
<form className="account-form" onSubmit={unbind} aria-busy={busy}>
|
||||
<fieldset disabled={busy}><label className="account-field" htmlFor="unbind-password">当前系统密码<input id="unbind-password" name="password" type="password" autoComplete="current-password" required maxLength={128} /></label>
|
||||
<button className="btn" type="submit">{busy ? '正在解绑…' : '验证密码并解除绑定'}</button></fieldset>
|
||||
</form>
|
||||
</>}
|
||||
</> : configured ? <form action={appPath('/api/auth/feishu/start')} method="post">
|
||||
<input type="hidden" name="intent" value="bind" /><button type="submit" className="btn primary feishu-login-button">绑定我的飞书账号</button>
|
||||
</form> : <p className="account-intro">飞书登录尚未配置,请联系管理员完成飞书应用设置。</p>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
'use client';
|
||||
import Link from 'next/link';
|
||||
import { useState } from 'react';
|
||||
import { appPath } from '@/lib/base-path';
|
||||
import type { FeishuDeliveryFilter, FeishuStatus } from '@/lib/feishu';
|
||||
|
||||
const deliveryLabels = { pending: '等待发送', sending: '发送中', sent: '已发送', failed: '发送失败' };
|
||||
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false });
|
||||
export function FeishuManagement({ initial }: { initial: FeishuStatus }) {
|
||||
const [status, setStatus] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [pageCursors, setPageCursors] = useState<Array<string | null>>([null]);
|
||||
async function request(action?: 'test' | 'retry', id?: string, selection?: { filter: FeishuDeliveryFilter; cursors: Array<string | null> }) {
|
||||
setBusy(true); setError(''); setMessage('');
|
||||
try {
|
||||
const params = new URLSearchParams({ filter: selection?.filter ?? status.deliveryFilter });
|
||||
const cursor = (selection?.cursors ?? pageCursors).at(-1);
|
||||
if (cursor) params.set('cursor', cursor);
|
||||
const response = await fetch(appPath('/api/admin/feishu?' + params.toString()), action ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, id }) } : { cache: 'no-store' });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || '操作失败,请重试。');
|
||||
setStatus(data); setMessage(action === 'test' ? '测试消息已发送,请在飞书群中查看。' : action === 'retry' ? '已加入发送队列,稍后刷新查看结果。' : '状态已刷新。');
|
||||
if (selection) setPageCursors(selection.cursors);
|
||||
} catch (cause) { setError(cause instanceof Error ? cause.message : '网络异常,请重试。'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <div className="account-admin-page">
|
||||
<header className="account-admin-header"><Link className="account-back-link" href="/">返回工作台</Link><strong>需有序</strong></header>
|
||||
<main className="account-admin-main feishu-admin">
|
||||
<div className="page-heading"><div><h1>飞书集成</h1><p>管理飞书登录与需求流转群通知。</p></div><button className="btn" disabled={busy} onClick={() => request()}>{busy ? '正在处理…' : '刷新状态'}</button></div>
|
||||
{error && <div className="error-banner" role="alert">{error}</div>}
|
||||
{message && <div className="account-success" role="status">{message}</div>}
|
||||
{status.configurationError && <div className="error-banner" role="alert">{status.configurationError}</div>}
|
||||
<div className="feishu-settings-grid">
|
||||
<section className="panel feishu-settings"><h2>飞书登录 <span className="feishu-status">{status.loginConfigured ? '已配置' : '未配置'}</span></h2>
|
||||
<p>首次飞书登录自动创建普通成员账号,直接进入工作台;已有绑定继续使用原账号的角色和需求。</p>
|
||||
<dl><dt>授权回调地址</dt><dd><code>{status.callbackUrl}</code></dd><dt>企业限制</dt><dd>{status.tenantRestricted ? '已限制为指定企业' : '按飞书应用可用范围注册及登录'}</dd></dl>
|
||||
<Link className="text-button" href="/account/feishu">绑定我的飞书账号</Link>
|
||||
</section>
|
||||
<section className="panel feishu-settings"><h2>群机器人 <span className="feishu-status">{status.botConfigured ? '已配置' : '未配置'}</span></h2>
|
||||
<p>正式需求每次成功保存后发送流转摘要,包含标题、状态、操作人和详情链接。草稿不推送。</p>
|
||||
<p>签名校验:{status.botSigned ? '已配置' : '未配置'}</p>
|
||||
<button className="btn" disabled={busy || !status.botConfigured} onClick={() => request('test')}>向飞书群发送测试消息</button>
|
||||
</section>
|
||||
</div>
|
||||
<details className="panel feishu-settings"><summary>配置步骤与通知范围</summary>
|
||||
<ol><li>在飞书开放平台创建企业自建应用,配置网页应用能力,将上方回调地址加入安全设置的重定向 URL,发布应用并设置成员可用范围。</li>
|
||||
<li>在服务器环境变量配置 FEISHU_APP_ID、FEISHU_APP_SECRET,可用 FEISHU_TENANT_KEY 限定企业。</li>
|
||||
<li>在目标群添加自定义机器人,配置 FEISHU_BOT_WEBHOOK;开启签名校验时同时配置 FEISHU_BOT_SECRET。关键词校验可填写「需有序」。</li>
|
||||
<li>重启服务后刷新状态,发送测试消息。密钥仅在服务器设置,无需填写到浏览器。</li></ol>
|
||||
<p>群成员均可看到通知摘要,请选择适合接收全部正式需求摘要的群。查看详情仍需系统登录及对应权限。发送失败自动重试最多 5 次,之后可手动重试;网络超时可能导致重复消息,可按需求编号和保存版本核对。</p>
|
||||
</details>
|
||||
<section className="panel feishu-settings" aria-labelledby="deliveries-title" aria-busy={busy}>
|
||||
<div className="feishu-delivery-tools"><h2 id="deliveries-title">通知记录</h2><div className="account-field"><label htmlFor="feishu-delivery-filter">通知筛选</label><select id="feishu-delivery-filter" disabled={busy} value={status.deliveryFilter} onChange={event => request(undefined, undefined, { filter: event.target.value as FeishuDeliveryFilter, cursors: [null] })}><option value="all">全部通知</option><option value="failed">发送失败({status.failedCount})</option></select></div></div>
|
||||
{status.deliveries.length ? <div className="account-users-table-wrap"><table className="account-users-table feishu-deliveries"><thead><tr><th>需求 / 保存版本</th><th>发送状态</th><th>尝试次数</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||
<tbody>{status.deliveries.map(item => <tr key={item.id}><td><Link href={'/?demand=' + encodeURIComponent(item.demandId)}>{item.demandId}</Link><small>第 {item.revision} 次保存</small></td><td>{deliveryLabels[item.status]}{item.lastError && <small>{item.lastError}</small>}</td><td>{item.attempts}</td><td>{date(item.createdAt)}</td><td>{item.status === 'failed' ? <button className="text-button" disabled={busy} onClick={() => request('retry', item.id)}>重试发送</button> : '—'}</td></tr>)}</tbody></table></div>
|
||||
: <p className="feishu-empty">{status.deliveryFilter === 'failed' ? '当前页暂无失败通知。可返回上一页或切换为全部通知。' : pageCursors.length > 1 ? '当前页暂无通知,请返回上一页。' : '暂无通知。配置机器人后,新登记及后续流转的正式需求会显示在这里。'}</p>}
|
||||
<div className="feishu-pagination"><span>第 {pageCursors.length} 页 · 每页最多 50 条{status.failedCount > 0 ? ` · 共有 ${status.failedCount} 条失败通知` : ''}</span><div><button className="btn" disabled={busy || pageCursors.length === 1} onClick={() => request(undefined, undefined, { filter: status.deliveryFilter, cursors: pageCursors.slice(0, -1) })}>上一页</button><button className="btn" disabled={busy || !status.nextCursor} onClick={() => request(undefined, undefined, { filter: status.deliveryFilter, cursors: [...pageCursors, status.nextCursor] })}>下一页</button></div></div>
|
||||
</section>
|
||||
</main>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
import { appPath } from '@/lib/base-path';
|
||||
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ArrowRight, CircleAlert, Eye, EyeOff, LoaderCircle } from 'lucide-react';
|
||||
|
||||
export function LoginForm({ returnTo = '/' }: { returnTo?: string }) {
|
||||
const router = useRouter();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const fields = new FormData(event.currentTarget);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await fetch(appPath('/api/auth/login'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: String(fields.get('username')).trim(), password: fields.get('password') }),
|
||||
});
|
||||
const data = await response.json() as { error?: string; user?: { mustChangePassword: boolean } };
|
||||
if (!response.ok || !data.user) throw new Error(data.error || '暂时无法登录,请稍后重试。');
|
||||
router.replace(data.user.mustChangePassword ? '/account/password' : returnTo);
|
||||
router.refresh();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <form className="account-form" onSubmit={submit} aria-busy={busy}>
|
||||
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
|
||||
<fieldset disabled={busy}>
|
||||
<label className="account-field" htmlFor="username">账号
|
||||
<input id="username" name="username" autoComplete="username" autoCapitalize="none" spellCheck={false} required maxLength={64} placeholder="请输入管理员分配的账号" autoFocus />
|
||||
</label>
|
||||
<label className="account-field" htmlFor="password">密码</label>
|
||||
<div className="account-password-input">
|
||||
<input id="password" name="password" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} placeholder="请输入密码" />
|
||||
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏密码' : '显示密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
|
||||
</div>
|
||||
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在登录…</> : <>登录工作台<ArrowRight size={18} /></>}</button>
|
||||
</fieldset>
|
||||
<p className="account-help">需要开通账号或忘记密码,请联系系统管理员。</p>
|
||||
</form>;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
import { appPath } from '@/lib/base-path';
|
||||
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ArrowLeft, CircleAlert, Eye, EyeOff, Info, LoaderCircle, LogOut } from 'lucide-react';
|
||||
|
||||
export function PasswordForm({ username, mustChangePassword, passwordSet = true }: { username: string; mustChangePassword: boolean; passwordSet?: boolean }) {
|
||||
const router = useRouter();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const fields = new FormData(event.currentTarget);
|
||||
setError('');
|
||||
if (fields.get('newPassword') !== fields.get('confirmation')) {
|
||||
setError('两次输入的新密码不一致,请重新确认。');
|
||||
event.currentTarget.querySelector<HTMLInputElement>('#confirmation')?.focus();
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const response = await fetch(appPath('/api/auth/password'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...(passwordSet ? { currentPassword: fields.get('currentPassword') } : {}), newPassword: fields.get('newPassword') }),
|
||||
});
|
||||
const data = await response.json() as { error?: string };
|
||||
if (!response.ok) throw new Error(data.error || '修改失败,请稍后重试。');
|
||||
router.replace('/');
|
||||
router.refresh();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
setLeaving(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await fetch(appPath('/api/auth/logout'), { method: 'POST' });
|
||||
if (!response.ok) throw new Error('退出登录失败,请重试。');
|
||||
router.replace('/login');
|
||||
router.refresh();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '退出登录失败,请重试。');
|
||||
setLeaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <>
|
||||
{!passwordSet && <div className="info-banner account-password-notice"><Info size={18} /><span>你当前通过飞书登录。设置系统密码后,也可使用上方账号和密码登录。</span></div>}
|
||||
{mustChangePassword && <div className="info-banner account-password-notice"><Info size={18} /><span>请将管理员分配的临时密码改为自己的密码,完成后即可进入工作台。</span></div>}
|
||||
<form className="account-form" onSubmit={submit} aria-busy={busy}>
|
||||
<input type="text" name="username" value={username} autoComplete="username" readOnly hidden />
|
||||
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
|
||||
<fieldset disabled={busy || leaving}>
|
||||
{passwordSet && <label className="account-field" htmlFor="currentPassword">{mustChangePassword ? '临时密码' : '当前密码'}
|
||||
<input id="currentPassword" name="currentPassword" type={visible ? 'text' : 'password'} autoComplete="current-password" required maxLength={128} autoFocus />
|
||||
</label>}
|
||||
<div className="account-field"><label htmlFor="newPassword">新密码</label>
|
||||
<input id="newPassword" name="newPassword" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="password-guidance" autoFocus={!passwordSet} />
|
||||
<small id="password-guidance">12–128 个字符,可使用方便记忆的长密码。</small>
|
||||
</div>
|
||||
<label className="account-field" htmlFor="confirmation">确认新密码
|
||||
<input id="confirmation" name="confirmation" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} />
|
||||
</label>
|
||||
<button className="text-button account-show-password" type="button" onClick={() => setVisible(!visible)} aria-pressed={visible}>{visible ? <EyeOff size={17} /> : <Eye size={17} />}{visible ? '隐藏密码' : '显示密码'}</button>
|
||||
<button className="btn primary account-submit" type="submit">{busy ? <><LoaderCircle className="account-spinner" size={18} />正在保存…</> : '保存密码并进入工作台'}</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
<div className="account-form-footer">
|
||||
{!mustChangePassword && <Link href="/" className="text-button"><ArrowLeft size={16} />返回工作台</Link>}
|
||||
<button className="text-button" onClick={logout} disabled={busy || leaving}><LogOut size={16} />{leaving ? '正在退出…' : '退出登录'}</button>
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
'use client';
|
||||
import { appPath } from '@/lib/base-path';
|
||||
|
||||
import { useCallback, useEffect, useState, type FormEvent } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { ArrowLeft, CheckCircle2, CircleAlert, Eye, EyeOff, KeyRound, LoaderCircle, Plus, RotateCw, Search, ShieldCheck, UserRound, UsersRound, X } from 'lucide-react';
|
||||
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
|
||||
import type { AdminUser } from '@/lib/server/auth';
|
||||
|
||||
type AccountAction = { kind: 'create' } | { kind: 'reset-password' | 'disable' | 'enable'; user: AdminUser };
|
||||
|
||||
async function readResponse(response: Response) {
|
||||
const data = await response.json() as { error?: string; users?: AdminUser[] };
|
||||
if (!response.ok) throw new Error(data.error || '操作失败,请稍后重试。');
|
||||
return data;
|
||||
}
|
||||
|
||||
function AccountDialog({ action, onClose, onSaved }: { action: AccountAction; onClose: () => void; onSaved: (message: string) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const creating = action.kind === 'create';
|
||||
const settingPassword = creating || action.kind === 'reset-password';
|
||||
const title = creating ? '开通账号' : action.kind === 'reset-password' ? '重置密码' : action.kind === 'disable' ? '停用账号' : '启用账号';
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const fields = new FormData(event.currentTarget);
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const body = action.kind === 'create'
|
||||
? { username: String(fields.get('username')).trim(), displayName: String(fields.get('displayName')).trim(), password: fields.get('password'), role: fields.get('role') }
|
||||
: { id: action.user.userId, action: action.kind, ...(settingPassword ? { password: fields.get('password') } : {}) };
|
||||
await readResponse(await fetch(appPath('/api/admin/users'), {
|
||||
method: creating ? 'POST' : 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}));
|
||||
const name = action.kind === 'create' ? String(fields.get('displayName')).trim() : action.user.displayName;
|
||||
onSaved(action.kind === 'create' ? `已为 ${name} 开通账号,请将账号和临时密码告知本人。` : action.kind === 'reset-password' ? `已重置 ${name} 的密码,下次登录时需要设置新密码。` : `已${action.kind === 'disable' ? '停用' : '启用'} ${name} 的账号。`);
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '无法连接服务,请检查网络后重试。');
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <Dialog open onOpenChange={open => { if (!open && !busy) onClose(); }}>
|
||||
<DialogContent className="account-dialog" showCloseButton={false} onEscapeKeyDown={event => { if (busy) event.preventDefault(); }} onPointerDownOutside={event => { if (busy) event.preventDefault(); }}>
|
||||
<div className="account-dialog-heading"><DialogTitle>{title}</DialogTitle><DialogClose asChild><button type="button" className="account-icon-button" aria-label="关闭" disabled={busy}><X size={20} /></button></DialogClose></div>
|
||||
<DialogDescription className="account-dialog-description">{creating ? '为指定用户创建账号,首次登录后由用户设置自己的密码。' : action.kind === 'reset-password' ? `为 ${action.user.displayName}(${action.user.username})设置新的临时密码,原有登录将失效。` : action.kind === 'disable' ? `停用后,${action.user.displayName} 将退出登录且无法再次登录。已登记的需求会保留。` : `启用后,${action.user.displayName} 可继续使用原账号和密码登录。`}</DialogDescription>
|
||||
<form className="account-form" onSubmit={submit} aria-busy={busy}>
|
||||
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span></div>}
|
||||
<fieldset disabled={busy}>
|
||||
{creating && <>
|
||||
<label className="account-field" htmlFor="new-username">登录账号
|
||||
<input id="new-username" name="username" autoComplete="off" autoCapitalize="none" spellCheck={false} required minLength={3} maxLength={64} pattern="[a-zA-Z0-9][a-zA-Z0-9._@\-]{2,63}" aria-describedby="username-guidance" placeholder="例如 zhangsan" />
|
||||
<small id="username-guidance">3–64 位,以字母或数字开头,可包含 . _ @ -;不区分大小写。</small>
|
||||
</label>
|
||||
<label className="account-field" htmlFor="new-displayName">用户姓名
|
||||
<input id="new-displayName" name="displayName" autoComplete="off" required maxLength={80} placeholder="例如 张三" />
|
||||
</label>
|
||||
<label className="account-field" htmlFor="new-role">账号角色
|
||||
<select id="new-role" name="role" defaultValue="user"><option value="user">业务用户</option><option value="admin">管理员</option></select>
|
||||
<small>管理员可以开通、停用账号和重置密码。</small>
|
||||
</label>
|
||||
</>}
|
||||
{settingPassword && <>
|
||||
<label className="account-field" htmlFor="new-account-password">临时密码</label>
|
||||
<div className="account-password-input">
|
||||
<input id="new-account-password" name="password" type={visible ? 'text' : 'password'} autoComplete="new-password" required minLength={12} maxLength={128} aria-describedby="temporary-password-guidance" />
|
||||
<button type="button" onClick={() => setVisible(!visible)} aria-label={visible ? '隐藏临时密码' : '显示临时密码'} aria-pressed={visible}>{visible ? <EyeOff size={19} /> : <Eye size={19} />}</button>
|
||||
</div>
|
||||
<small className="account-field-hint" id="temporary-password-guidance">12–128 个字符。请保存并告知用户,关闭后无法查看。</small>
|
||||
</>}
|
||||
<div className="account-dialog-actions"><button type="button" className="btn" onClick={onClose}>取消</button><button className={`btn ${action.kind === 'disable' ? 'danger-button' : 'primary'}`} type="submit">{busy ? <><LoaderCircle className="account-spinner" size={17} />正在保存…</> : title}</button></div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>;
|
||||
}
|
||||
|
||||
export function UserManagement({ currentUserId }: { currentUserId: string }) {
|
||||
const [users, setUsers] = useState<AdminUser[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [action, setAction] = useState<AccountAction | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
|
||||
const load = useCallback((signal?: AbortSignal) => fetch(appPath('/api/admin/users'), { cache: 'no-store', signal })
|
||||
.then(readResponse)
|
||||
.then(data => {
|
||||
if (!signal?.aborted) { setUsers(data.users || []); setError(''); }
|
||||
}).catch(cause => {
|
||||
if (!signal?.aborted) setError(cause instanceof Error ? cause.message : '无法加载账号,请重试。');
|
||||
}).finally(() => {
|
||||
if (!signal?.aborted) setLoading(false);
|
||||
}), []);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void load(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [load]);
|
||||
|
||||
const search = query.trim().toLocaleLowerCase();
|
||||
const matching = users.filter(user => `${user.username} ${user.displayName}`.toLocaleLowerCase().includes(search));
|
||||
|
||||
function reload() {
|
||||
setLoading(true);
|
||||
void load();
|
||||
}
|
||||
|
||||
function saved(text: string) {
|
||||
setAction(null);
|
||||
setMessage(text);
|
||||
reload();
|
||||
}
|
||||
|
||||
return <div className="account-admin-page">
|
||||
<header className="account-admin-header"><Link className="account-back-link" href="/"><ArrowLeft size={18} />返回工作台</Link><div className="account-admin-brand"><div className="brand-mark" aria-hidden="true"><i /><i /><i /><i /></div><strong>需有序</strong></div></header>
|
||||
<main className="account-admin-main">
|
||||
<div className="page-heading"><div><h1>账号管理</h1><p>为指定用户开通访问权限,统一管理账号状态。</p></div><button className="btn primary" onClick={() => { setMessage(''); setAction({ kind: 'create' }); }}><Plus size={18} />开通账号</button></div>
|
||||
<div className="info-banner account-admin-note"><ShieldCheck size={19} /><p>仅已开通且处于启用状态的账号可以登录。每位用户只能查看和管理自己登记的需求。</p></div>
|
||||
{message && <div className="account-success" role="status"><CheckCircle2 size={18} /><span>{message}</span><button className="account-icon-button" aria-label="关闭操作提示" onClick={() => setMessage('')}><X size={18} /></button></div>}
|
||||
{error && <div className="error-banner" role="alert"><CircleAlert size={18} /><span>{error}</span><button className="text-button" onClick={reload} disabled={loading}>重新加载</button></div>}
|
||||
<section className="panel account-users-panel" aria-labelledby="users-list-heading" aria-busy={loading}>
|
||||
<div className="account-users-toolbar"><div className="account-users-title"><UsersRound size={19} /><h2 id="users-list-heading">全部账号</h2><span>{users.length}</span></div><div className="account-users-tools"><label className="search-field"><Search size={17} /><input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="搜索账号或姓名" aria-label="搜索账号或姓名" /></label><button className="account-icon-button" onClick={reload} disabled={loading} aria-label="刷新账号列表"><RotateCw size={18} className={loading ? 'account-spinner' : ''} /></button></div></div>
|
||||
<div className="account-users-table-wrap"><table className="account-users-table"><thead><tr><th scope="col">用户</th><th scope="col">角色</th><th scope="col">状态</th><th scope="col">最近登录</th><th scope="col">操作</th></tr></thead><tbody>
|
||||
{matching.map(user => <tr key={user.userId}><td><div className="account-user-identity"><span className="avatar"><UserRound size={19} /></span><div><strong>{user.displayName}{user.userId === currentUserId && <span className="account-self">我</span>}</strong><span>{user.username}</span></div></div></td><td><span className={user.role === 'admin' ? 'account-role-admin' : ''}>{user.role === 'admin' ? '管理员' : '业务用户'}</span></td><td><span className={`status ${user.disabled ? 'gray' : 'green'}`}>{user.disabled ? '已停用' : '已启用'}</span>{user.mustChangePassword && !user.disabled && <small className="account-password-pending">待设置密码</small>}</td><td className="account-login-date">{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }) : '尚未登录'}</td><td><div className="account-row-actions">{user.userId === currentUserId ? <a className="text-button" href={appPath('/account/password')}><KeyRound size={15} />修改密码</a> : <><button className="text-button" onClick={() => setAction({ kind: 'reset-password', user })}>重置密码</button><button className={`text-button ${user.disabled ? '' : 'danger-text'}`} onClick={() => setAction({ kind: user.disabled ? 'enable' : 'disable', user })}>{user.disabled ? '启用' : '停用'}</button></>}</div></td></tr>)}
|
||||
</tbody></table></div>
|
||||
{loading && users.length === 0 && <div className="account-list-empty" role="status"><LoaderCircle className="account-spinner" size={24} /><p>正在加载账号…</p></div>}
|
||||
{!loading && !matching.length && <div className="account-list-empty"><UsersRound size={28} /><h3>{query ? '没有找到匹配的账号' : error ? '账号列表暂不可用' : '暂无账号'}</h3><p>{query ? '试试其他账号或姓名。' : error ? '请重新加载后再试。' : '点击“开通账号”为指定用户添加访问权限。'}</p></div>}
|
||||
<div className="account-users-footer">{search ? `找到 ${matching.length} 个账号` : `共 ${users.length} 个账号,${users.filter(user => !user.disabled).length} 个已启用`}<span>停用账号会保留已登记的需求</span></div>
|
||||
</section>
|
||||
</main>
|
||||
{action && <AccountDialog action={action} onClose={() => setAction(null)} onSaved={saved} />}
|
||||
</div>;
|
||||
}
|
||||
Reference in new issue
Block a user