import {GlassButton, html, TextField, useState, useToast} from 'vendor'; import {api, useFetch} from '../api.js'; import {ROLE_NAME} from '../format.js'; import {DataTable} from '../components/DataTable.js'; import {FormDialog} from '../components/FormDialog.js'; import {Loading, Section, Select} from '../components/ui.js'; const ROLES = [{value: 'user', label: '普通用户'}, {value: 'admin', label: '管理员'}]; export default function Users() { const toast = useToast(); const {data, reload} = useFetch('/api/users'); const [adding, setAdding] = useState(false); const [resetting, setResetting] = useState(null); /** 发送请求:成功提示并刷新列表;失败提示后继续抛出(让表单弹窗保持打开) */ const send = async (url, options, message) => { try { await api(url, options); } catch (e) { toast({message: e.message, tone: 'error'}); throw e; } toast({message, tone: 'success'}); reload(); }; const checkPassword = password => { if (password.length >= 6) return; toast({message: '密码至少 6 位', tone: 'error'}); throw new Error('invalid'); }; const addUser = d => { checkPassword(d.password); return send('/api/users', {json: d}, '已新增'); }; const resetPassword = d => { checkPassword(d.password); return send(`/api/users/${resetting.id}`, {method: 'PUT', json: d}, '密码已重置'); }; const toggleRole = u => send(`/api/users/${u.id}`, {method: 'PUT', json: {role: u.role === 'admin' ? 'user' : 'admin'}}, '角色已更新').catch(() => {}); const removeUser = u => { if (confirm(`确认删除用户「${u.username}」?`)) send(`/api/users/${u.id}`, {method: 'DELETE'}, '已删除').catch(() => {}); }; const columns = [ {key: 'id', title: 'ID'}, {key: 'username', title: '用户名'}, {key: 'role', title: '角色', render: v => ROLE_NAME[v]}, {key: 'created_at', title: '创建时间'}, {key: '_ops', title: '操作', render: (_, u) => html`
<${GlassButton} variant="tinted" controlSize="small" onClick=${() => setResetting(u)}>重置密码 <${GlassButton} variant="gray" controlSize="small" onClick=${() => toggleRole(u)}> 设为${u.role === 'admin' ? '普通用户' : '管理员'} <${GlassButton} variant="destructive" controlSize="small" onClick=${() => removeUser(u)}>删除
`}, ]; return html` <${Section}>
密码使用 PBKDF2-SHA256 加盐哈希存储。管理员:全部功能;普通用户:查询、统计、看板、导出,以及更新闭环处理进度。 <${GlassButton} variant="glassProminent" onClick=${() => setAdding(true)}>新增用户
${data ? html`<${DataTable} columns=${columns} rows=${data.rows}/>` : html`<${Loading}/>`} ${adding && html` <${FormDialog} onClose=${() => setAdding(false)} onSubmit=${addUser} title="新增用户" description="系统不开放自助注册,由管理员分配账号"> <${TextField} name="username" label="用户名" required autoComplete="off"/> <${TextField} name="password" label="初始密码(≥6 位)" type="password" required autoComplete="new-password"/> <${Select} name="role" label="角色" showLabel options=${ROLES} value="user"/> `} ${resetting && html` <${FormDialog} onClose=${() => setResetting(null)} onSubmit=${resetPassword} title="重置密码" description=${`用户:${resetting.username}`}> <${TextField} className="full" name="password" label="新密码(≥6 位)" type="password" required autoComplete="new-password"/> `} `; }