调整目录
This commit is contained in:
@@ -0,0 +1,335 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { Controller, Resolver, useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { SearchIcon, ShieldAlertIcon, ShieldCheckIcon, ShieldIcon } from "lucide-react"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import type { AdminRole, AdminUser } from "@/lib/api/admin"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
} from "@/components/ui/drawer"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Status } from "@/lib/generated/enums"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
type AssignRolesDrawerProps = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
loading: boolean
|
||||
item: AdminUser | null
|
||||
roles: AdminRole[]
|
||||
selectedRoleIds: number[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (roleIds: number[]) => Promise<void>
|
||||
}
|
||||
|
||||
const assignRolesSchema = z.object({
|
||||
roleIds: z.array(z.number().int().positive()),
|
||||
})
|
||||
|
||||
type AssignRolesForm = z.infer<typeof assignRolesSchema>
|
||||
|
||||
const assignRolesResolver = zodResolver(assignRolesSchema as never) as Resolver<
|
||||
z.input<typeof assignRolesSchema>,
|
||||
undefined,
|
||||
z.output<typeof assignRolesSchema>
|
||||
>
|
||||
|
||||
function buildForm(selectedRoleIds: number[]): AssignRolesForm {
|
||||
return {
|
||||
roleIds: selectedRoleIds,
|
||||
}
|
||||
}
|
||||
|
||||
export function AssignRolesDrawer({
|
||||
open,
|
||||
saving,
|
||||
loading,
|
||||
item,
|
||||
roles,
|
||||
selectedRoleIds,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: AssignRolesDrawerProps) {
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={onOpenChange} direction="right">
|
||||
{open ? (
|
||||
<AssignRolesDrawerBody
|
||||
key={item ? `assign-roles-${item.id}` : "assign-roles"}
|
||||
saving={saving}
|
||||
loading={loading}
|
||||
item={item}
|
||||
roles={roles}
|
||||
selectedRoleIds={selectedRoleIds}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
) : null}
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
type AssignRolesDrawerBodyProps = {
|
||||
saving: boolean
|
||||
loading: boolean
|
||||
item: AdminUser | null
|
||||
roles: AdminRole[]
|
||||
selectedRoleIds: number[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (roleIds: number[]) => Promise<void>
|
||||
}
|
||||
|
||||
function AssignRolesDrawerBody({
|
||||
saving,
|
||||
loading,
|
||||
item,
|
||||
roles,
|
||||
selectedRoleIds,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: AssignRolesDrawerBodyProps) {
|
||||
const [keyword, setKeyword] = useState("")
|
||||
const form = useForm<
|
||||
z.input<typeof assignRolesSchema>,
|
||||
undefined,
|
||||
z.output<typeof assignRolesSchema>
|
||||
>({
|
||||
resolver: assignRolesResolver,
|
||||
defaultValues: buildForm(selectedRoleIds),
|
||||
})
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = form
|
||||
|
||||
useEffect(() => {
|
||||
reset(buildForm(selectedRoleIds))
|
||||
}, [reset, selectedRoleIds])
|
||||
|
||||
const roleMap = useMemo(
|
||||
() => new Map(roles.map((role) => [role.id, role])),
|
||||
[roles]
|
||||
)
|
||||
|
||||
async function onFormSubmit(values: AssignRolesForm) {
|
||||
await onSubmit(values.roleIds)
|
||||
}
|
||||
|
||||
return (
|
||||
<DrawerContent className="flex min-w-2xl flex-col overflow-hidden">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>分配角色</DrawerTitle>
|
||||
</DrawerHeader>
|
||||
<form
|
||||
className="flex min-h-0 flex-1 flex-col overflow-hidden"
|
||||
onSubmit={handleSubmit(onFormSubmit)}
|
||||
>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
<Controller
|
||||
control={control}
|
||||
name="roleIds"
|
||||
render={({ field }) => {
|
||||
const value = field.value || []
|
||||
const selectedRoleSet = new Set(value)
|
||||
const initiallySelectedSet = new Set(selectedRoleIds)
|
||||
const selectedRoles = roles.filter((role) => selectedRoleSet.has(role.id))
|
||||
const removedRoles = selectedRoleIds
|
||||
.map((roleId) => roleMap.get(roleId))
|
||||
.filter((role): role is AdminRole => !!role && !selectedRoleSet.has(role.id))
|
||||
const addedRoles = value
|
||||
.map((roleId) => roleMap.get(roleId))
|
||||
.filter((role): role is AdminRole => !!role && !initiallySelectedSet.has(role.id))
|
||||
const filteredRoles = roles.filter((role) => {
|
||||
const output = keyword.trim().toLowerCase()
|
||||
if (!output) {
|
||||
return true
|
||||
}
|
||||
return `${role.name} ${role.code}`.toLowerCase().includes(output)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="space-y-4 px-4 pb-4">
|
||||
<Field>
|
||||
<FieldLabel>当前已分配</FieldLabel>
|
||||
<FieldContent>
|
||||
<div className="rounded-lg border p-3">
|
||||
{selectedRoles.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{selectedRoles.map((role) => (
|
||||
<Badge
|
||||
key={role.id}
|
||||
variant={role.status === Status.Ok ? "secondary" : "outline"}
|
||||
className="gap-1"
|
||||
>
|
||||
{role.status === Status.Ok ? (
|
||||
<ShieldCheckIcon className="size-3" />
|
||||
) : (
|
||||
<ShieldAlertIcon className="size-3" />
|
||||
)}
|
||||
{role.name}
|
||||
{role.status !== Status.Ok ? "(已禁用)" : ""}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">当前未分配角色</div>
|
||||
)}
|
||||
</div>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.roleIds}>
|
||||
<FieldLabel>角色列表</FieldLabel>
|
||||
<FieldContent>
|
||||
<div className="relative">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={keyword}
|
||||
onChange={(event) => setKeyword(event.target.value)}
|
||||
placeholder="搜索角色名称或编码"
|
||||
className="pl-9"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-2 max-h-[360px] space-y-1 overflow-y-auto rounded-lg border p-2">
|
||||
{loading ? (
|
||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
||||
正在加载角色列表...
|
||||
</div>
|
||||
) : filteredRoles.length > 0 ? (
|
||||
filteredRoles.map((role) => {
|
||||
const checked = selectedRoleSet.has(role.id)
|
||||
const disabled = role.status !== Status.Ok && !checked
|
||||
|
||||
return (
|
||||
<label
|
||||
key={role.id}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-md border px-2.5 py-2 text-sm transition-colors",
|
||||
disabled
|
||||
? "cursor-not-allowed border-dashed bg-muted/20 opacity-70"
|
||||
: "cursor-pointer hover:bg-muted/50",
|
||||
checked && "border-primary/40 bg-primary/5"
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onCheckedChange={(nextChecked) => {
|
||||
if (nextChecked) {
|
||||
field.onChange([...value, role.id])
|
||||
return
|
||||
}
|
||||
field.onChange(
|
||||
value.filter((currentId) => currentId !== role.id)
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 whitespace-nowrap">
|
||||
<span className="truncate font-medium">{role.name}</span>
|
||||
<span className="truncate text-muted-foreground">
|
||||
{role.code}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{role.isSystem ? (
|
||||
<Badge variant="outline" className="shrink-0">
|
||||
系统
|
||||
</Badge>
|
||||
) : null}
|
||||
<Badge
|
||||
variant={role.status === Status.Ok ? "secondary" : "outline"}
|
||||
className="shrink-0"
|
||||
>
|
||||
{role.status === Status.Ok ? "启用" : "禁用"}
|
||||
</Badge>
|
||||
</label>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="py-8 text-center text-sm text-muted-foreground">
|
||||
没有匹配的角色
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<FieldError errors={[errors.roleIds]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel>本次变更</FieldLabel>
|
||||
<FieldContent>
|
||||
<div className="space-y-3 rounded-lg border p-3">
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-medium">新增角色</div>
|
||||
{addedRoles.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{addedRoles.map((role) => (
|
||||
<Badge key={role.id} variant="secondary" className="gap-1">
|
||||
<ShieldIcon className="size-3" />
|
||||
{role.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">无新增</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-sm font-medium">移除角色</div>
|
||||
{removedRoles.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{removedRoles.map((role) => (
|
||||
<Badge key={role.id} variant="outline" className="gap-1">
|
||||
<ShieldIcon className="size-3" />
|
||||
{role.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground">无移除</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<DrawerFooter className="border-t">
|
||||
<Button type="submit" disabled={saving || loading || !item}>
|
||||
{saving ? "保存中..." : "确认分配"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
</form>
|
||||
</DrawerContent>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { Controller, Resolver, useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { SearchIcon, ShieldAlertIcon, ShieldCheckIcon } from "lucide-react"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import {
|
||||
fetchRoleListAll,
|
||||
type AdminRole,
|
||||
type CreateAdminUserPayload,
|
||||
} from "@/lib/api/admin"
|
||||
import { Status } from "@/lib/generated/enums"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
} from "@/components/ui/drawer"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
|
||||
type CreateUserDrawerProps = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: CreateAdminUserPayload) => Promise<void>
|
||||
}
|
||||
|
||||
const createFormSchema = z.object({
|
||||
username: z.string().trim().min(1, "用户名不能为空"),
|
||||
nickname: z.string().trim(),
|
||||
avatar: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) => value.length === 0 || /^https?:\/\/\S+$/i.test(value),
|
||||
"头像地址必须是 http 或 https 链接"
|
||||
),
|
||||
mobile: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) => value.length === 0 || /^[0-9+\-\s]{6,20}$/.test(value),
|
||||
"手机号格式不正确"
|
||||
),
|
||||
email: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) =>
|
||||
value.length === 0 || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
|
||||
"邮箱格式不正确"
|
||||
),
|
||||
remark: z.string().trim(),
|
||||
roleIds: z.array(z.number().int().positive()),
|
||||
})
|
||||
|
||||
type CreateForm = z.infer<typeof createFormSchema>
|
||||
|
||||
const emptyForm: CreateForm = {
|
||||
username: "",
|
||||
nickname: "",
|
||||
avatar: "",
|
||||
mobile: "",
|
||||
email: "",
|
||||
remark: "",
|
||||
roleIds: [],
|
||||
}
|
||||
|
||||
const createFormResolver = zodResolver(createFormSchema as never) as Resolver<
|
||||
z.input<typeof createFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof createFormSchema>
|
||||
>
|
||||
|
||||
function toNullableString(value: string) {
|
||||
const output = value.trim()
|
||||
return output ? output : null
|
||||
}
|
||||
|
||||
function buildPayload(form: CreateForm): CreateAdminUserPayload {
|
||||
return {
|
||||
username: form.username.trim(),
|
||||
nickname: form.nickname.trim(),
|
||||
avatar: form.avatar.trim(),
|
||||
mobile: toNullableString(form.mobile),
|
||||
email: toNullableString(form.email),
|
||||
remark: form.remark.trim(),
|
||||
roleIds: form.roleIds,
|
||||
}
|
||||
}
|
||||
|
||||
export function CreateUserDrawer({
|
||||
open,
|
||||
saving,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: CreateUserDrawerProps) {
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={onOpenChange} direction="right">
|
||||
{open ? (
|
||||
<CreateUserDrawerBody
|
||||
key="create-user"
|
||||
saving={saving}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
) : null}
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
type CreateUserDrawerBodyProps = {
|
||||
saving: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: CreateAdminUserPayload) => Promise<void>
|
||||
}
|
||||
|
||||
function CreateUserDrawerBody({
|
||||
saving,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: CreateUserDrawerBodyProps) {
|
||||
const [rolesLoading, setRolesLoading] = useState(true)
|
||||
const [roles, setRoles] = useState<AdminRole[]>([])
|
||||
const [roleKeyword, setRoleKeyword] = useState("")
|
||||
const form = useForm<
|
||||
z.input<typeof createFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof createFormSchema>
|
||||
>({
|
||||
resolver: createFormResolver,
|
||||
defaultValues: emptyForm,
|
||||
})
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
register,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = form
|
||||
|
||||
useEffect(() => {
|
||||
async function loadRoles() {
|
||||
setRolesLoading(true)
|
||||
try {
|
||||
const list = await fetchRoleListAll()
|
||||
setRoles(list)
|
||||
} catch {
|
||||
setRoles([])
|
||||
} finally {
|
||||
setRolesLoading(false)
|
||||
}
|
||||
}
|
||||
void loadRoles()
|
||||
}, [])
|
||||
|
||||
const filteredRoles = useMemo(() => {
|
||||
const q = roleKeyword.trim().toLowerCase()
|
||||
if (!q) {
|
||||
return roles
|
||||
}
|
||||
return roles.filter((role) =>
|
||||
`${role.name} ${role.code}`.toLowerCase().includes(q)
|
||||
)
|
||||
}, [roleKeyword, roles])
|
||||
|
||||
async function onFormSubmit(values: CreateForm) {
|
||||
await onSubmit(buildPayload(values))
|
||||
reset(emptyForm)
|
||||
setRoleKeyword("")
|
||||
}
|
||||
|
||||
return (
|
||||
<DrawerContent className="min-w-2xl">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>添加用户</DrawerTitle>
|
||||
<DrawerDescription>
|
||||
提交后由系统生成初始密码,并仅展示一次,请妥善保存。
|
||||
</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
<form
|
||||
className="flex h-full flex-col"
|
||||
onSubmit={handleSubmit(onFormSubmit)}
|
||||
>
|
||||
<div className="space-y-4 overflow-y-auto px-4 pb-4">
|
||||
<Field data-invalid={!!errors.username}>
|
||||
<FieldLabel htmlFor="create-username">用户名</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-username"
|
||||
placeholder="登录名,必填"
|
||||
autoComplete="off"
|
||||
aria-invalid={!!errors.username}
|
||||
{...register("username")}
|
||||
/>
|
||||
<FieldError errors={[errors.username]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.nickname}>
|
||||
<FieldLabel htmlFor="create-nickname">昵称</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-nickname"
|
||||
placeholder="可选,默认同用户名"
|
||||
aria-invalid={!!errors.nickname}
|
||||
{...register("nickname")}
|
||||
/>
|
||||
<FieldError errors={[errors.nickname]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.avatar}>
|
||||
<FieldLabel htmlFor="create-avatar">头像地址</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-avatar"
|
||||
placeholder="可选,http(s) 链接"
|
||||
aria-invalid={!!errors.avatar}
|
||||
{...register("avatar")}
|
||||
/>
|
||||
<FieldError errors={[errors.avatar]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.mobile}>
|
||||
<FieldLabel htmlFor="create-mobile">手机号</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-mobile"
|
||||
placeholder="可选"
|
||||
aria-invalid={!!errors.mobile}
|
||||
{...register("mobile")}
|
||||
/>
|
||||
<FieldError errors={[errors.mobile]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.email}>
|
||||
<FieldLabel htmlFor="create-email">邮箱</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-email"
|
||||
placeholder="可选"
|
||||
aria-invalid={!!errors.email}
|
||||
{...register("email")}
|
||||
/>
|
||||
<FieldError errors={[errors.email]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.remark}>
|
||||
<FieldLabel htmlFor="create-remark">备注</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="create-remark"
|
||||
placeholder="可选"
|
||||
aria-invalid={!!errors.remark}
|
||||
{...register("remark")}
|
||||
/>
|
||||
<FieldError errors={[errors.remark]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.roleIds}>
|
||||
<FieldLabel>角色(可选)</FieldLabel>
|
||||
<FieldContent>
|
||||
<div className="relative">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={roleKeyword}
|
||||
onChange={(event) => setRoleKeyword(event.target.value)}
|
||||
placeholder="搜索角色"
|
||||
className="pl-9"
|
||||
disabled={rolesLoading}
|
||||
/>
|
||||
</div>
|
||||
<Controller
|
||||
control={control}
|
||||
name="roleIds"
|
||||
render={({ field }) => {
|
||||
const value = field.value || []
|
||||
const selectedSet = new Set(value)
|
||||
return (
|
||||
<div className="mt-2 max-h-[240px] space-y-1 overflow-y-auto rounded-lg border p-2">
|
||||
{rolesLoading ? (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
正在加载角色...
|
||||
</div>
|
||||
) : filteredRoles.length > 0 ? (
|
||||
filteredRoles.map((role) => {
|
||||
const checked = selectedSet.has(role.id)
|
||||
const disabled = role.status !== Status.Ok && !checked
|
||||
return (
|
||||
<label
|
||||
key={role.id}
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-md border px-2.5 py-2 text-sm transition-colors",
|
||||
disabled
|
||||
? "cursor-not-allowed border-dashed bg-muted/20 opacity-70"
|
||||
: "cursor-pointer hover:bg-muted/50",
|
||||
checked && "border-primary/40 bg-primary/5"
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onCheckedChange={(nextChecked) => {
|
||||
if (nextChecked) {
|
||||
field.onChange([...value, role.id])
|
||||
return
|
||||
}
|
||||
field.onChange(
|
||||
value.filter(
|
||||
(id: number) => id !== role.id
|
||||
)
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
{role.status === Status.Ok ? (
|
||||
<ShieldCheckIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
) : (
|
||||
<ShieldAlertIcon className="size-3.5 shrink-0 text-muted-foreground" />
|
||||
)}
|
||||
<span className="truncate">{role.name}</span>
|
||||
{role.status !== Status.Ok ? (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
已禁用
|
||||
</Badge>
|
||||
) : null}
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
暂无角色
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<FieldError errors={[errors.roleIds]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</div>
|
||||
<DrawerFooter className="border-t">
|
||||
<Button type="submit" disabled={saving || rolesLoading}>
|
||||
{saving ? "创建中..." : "创建用户"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
</form>
|
||||
</DrawerContent>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { Resolver, useForm } from "react-hook-form"
|
||||
import { z } from "zod/v4"
|
||||
|
||||
import {
|
||||
type AdminUser,
|
||||
type UpdateAdminUserPayload,
|
||||
fetchUserDetail,
|
||||
} from "@/lib/api/admin"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
} from "@/components/ui/drawer"
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldError,
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
|
||||
type UserEditDrawerProps = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
itemId: number | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: UpdateAdminUserPayload) => Promise<void>
|
||||
}
|
||||
|
||||
const emptyForm: EditForm = {
|
||||
nickname: "",
|
||||
avatar: "",
|
||||
mobile: "",
|
||||
email: "",
|
||||
}
|
||||
|
||||
const editFormSchema = z.object({
|
||||
nickname: z.string().trim().min(1, "昵称不能为空"),
|
||||
avatar: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) => value.length === 0 || /^https?:\/\/\S+$/i.test(value),
|
||||
"头像地址必须是 http 或 https 链接"
|
||||
),
|
||||
mobile: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) => value.length === 0 || /^[0-9+\-\s]{6,20}$/.test(value),
|
||||
"手机号格式不正确"
|
||||
),
|
||||
email: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine(
|
||||
(value) =>
|
||||
value.length === 0 || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
|
||||
"邮箱格式不正确"
|
||||
),
|
||||
})
|
||||
|
||||
type EditForm = z.infer<typeof editFormSchema>
|
||||
const editFormResolver = zodResolver(editFormSchema as never) as Resolver<
|
||||
z.input<typeof editFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof editFormSchema>
|
||||
>
|
||||
|
||||
function toNullableString(value: string) {
|
||||
const output = value.trim()
|
||||
return output ? output : null
|
||||
}
|
||||
|
||||
function buildForm(item: AdminUser | null): EditForm {
|
||||
if (!item) {
|
||||
return emptyForm
|
||||
}
|
||||
|
||||
return {
|
||||
nickname: item.nickname || "",
|
||||
avatar: item.avatar || "",
|
||||
mobile: item.mobile || "",
|
||||
email: item.email || "",
|
||||
}
|
||||
}
|
||||
|
||||
function buildPayload(userId: number, form: EditForm): UpdateAdminUserPayload {
|
||||
return {
|
||||
id: userId,
|
||||
nickname: form.nickname.trim(),
|
||||
avatar: form.avatar.trim(),
|
||||
mobile: toNullableString(form.mobile),
|
||||
email: toNullableString(form.email),
|
||||
remark: "",
|
||||
}
|
||||
}
|
||||
|
||||
export function EditDrawer({
|
||||
open,
|
||||
saving,
|
||||
itemId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: UserEditDrawerProps) {
|
||||
return (
|
||||
<Drawer open={open} onOpenChange={onOpenChange} direction="right">
|
||||
{open ? (
|
||||
<UserEditDrawerBody
|
||||
key={itemId ? `edit-${itemId}` : "edit"}
|
||||
itemId={itemId}
|
||||
saving={saving}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
) : null}
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
type UserEditDrawerBodyProps = {
|
||||
saving: boolean
|
||||
itemId: number | null
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: UpdateAdminUserPayload) => Promise<void>
|
||||
}
|
||||
|
||||
function UserEditDrawerBody({
|
||||
saving,
|
||||
itemId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: UserEditDrawerBodyProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [item, setItem] = useState<AdminUser | null>(null)
|
||||
const form = useForm<
|
||||
z.input<typeof editFormSchema>,
|
||||
undefined,
|
||||
z.output<typeof editFormSchema>
|
||||
>({
|
||||
resolver: editFormResolver,
|
||||
defaultValues: emptyForm,
|
||||
})
|
||||
const {
|
||||
handleSubmit,
|
||||
reset,
|
||||
register,
|
||||
formState: { errors },
|
||||
} = form
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDetail() {
|
||||
if (!itemId) {
|
||||
setItem(null)
|
||||
reset(emptyForm)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchUserDetail(itemId)
|
||||
setItem(data)
|
||||
reset(buildForm(data))
|
||||
} catch (error) {
|
||||
console.error("Failed to load user:", error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
void loadDetail()
|
||||
}, [itemId, reset])
|
||||
|
||||
async function onFormSubmit(values: EditForm) {
|
||||
if (!itemId) {
|
||||
return
|
||||
}
|
||||
|
||||
await onSubmit(buildPayload(itemId, values))
|
||||
}
|
||||
|
||||
return (
|
||||
<DrawerContent className="min-w-2xl">
|
||||
<DrawerHeader>
|
||||
<DrawerTitle>修改用户</DrawerTitle>
|
||||
<DrawerDescription>当前用户:{item?.username || "-"}</DrawerDescription>
|
||||
</DrawerHeader>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-muted-foreground">加载中...</div>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="flex h-full flex-col"
|
||||
onSubmit={handleSubmit(onFormSubmit)}
|
||||
>
|
||||
<div className="space-y-4 px-4 pb-4">
|
||||
<Field data-invalid={!!errors.nickname}>
|
||||
<FieldLabel htmlFor="user-nickname">昵称</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="user-nickname"
|
||||
placeholder="请输入昵称"
|
||||
aria-invalid={!!errors.nickname}
|
||||
{...register("nickname")}
|
||||
/>
|
||||
<FieldError errors={[errors.nickname]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.avatar}>
|
||||
<FieldLabel htmlFor="user-avatar">头像地址</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="user-avatar"
|
||||
placeholder="请输入头像 URL"
|
||||
aria-invalid={!!errors.avatar}
|
||||
{...register("avatar")}
|
||||
/>
|
||||
<FieldError errors={[errors.avatar]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.mobile}>
|
||||
<FieldLabel htmlFor="user-mobile">手机号</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="user-mobile"
|
||||
placeholder="请输入手机号"
|
||||
aria-invalid={!!errors.mobile}
|
||||
{...register("mobile")}
|
||||
/>
|
||||
<FieldError errors={[errors.mobile]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field data-invalid={!!errors.email}>
|
||||
<FieldLabel htmlFor="user-email">邮箱</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
id="user-email"
|
||||
placeholder="请输入邮箱"
|
||||
aria-invalid={!!errors.email}
|
||||
{...register("email")}
|
||||
/>
|
||||
<FieldError errors={[errors.email]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</div>
|
||||
<DrawerFooter className="border-t">
|
||||
<Button type="submit" disabled={saving || loading}>
|
||||
{saving ? "保存中..." : "保存修改"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</DrawerFooter>
|
||||
</form>
|
||||
)}
|
||||
</DrawerContent>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { CopyIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
type InitialPasswordDialogProps = {
|
||||
open: boolean
|
||||
username: string
|
||||
password: string
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function InitialPasswordDialog({
|
||||
open,
|
||||
username,
|
||||
password,
|
||||
onOpenChange,
|
||||
}: InitialPasswordDialogProps) {
|
||||
const [copying, setCopying] = useState(false)
|
||||
|
||||
async function handleCopy() {
|
||||
if (!password || copying) {
|
||||
return
|
||||
}
|
||||
|
||||
setCopying(true)
|
||||
try {
|
||||
await navigator.clipboard.writeText(password)
|
||||
toast.success("密码已复制")
|
||||
} catch {
|
||||
toast.error("复制失败,请手动复制")
|
||||
} finally {
|
||||
setCopying(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>用户已创建</DialogTitle>
|
||||
<DialogDescription>
|
||||
{username || "-"} 的初始密码已生成,仅在此展示一次,请及时复制并安全传达。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="rounded-xl border bg-muted/40 p-4">
|
||||
<div className="text-xs text-muted-foreground">初始密码</div>
|
||||
<div className="mt-2 break-all font-mono text-base">{password}</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => void handleCopy()}
|
||||
disabled={copying || !password}
|
||||
>
|
||||
<CopyIcon />
|
||||
{copying ? "复制中..." : "复制密码"}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => onOpenChange(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { CopyIcon } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { type AdminUser } from "@/lib/api/admin"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
|
||||
type ResetPasswordDialogsProps = {
|
||||
open: boolean
|
||||
saving: boolean
|
||||
item: AdminUser | null
|
||||
password: string
|
||||
onOpenChange: (open: boolean) => void
|
||||
onConfirm: () => Promise<void>
|
||||
}
|
||||
|
||||
export function ResetPasswordDialogs({
|
||||
open,
|
||||
saving,
|
||||
item,
|
||||
password,
|
||||
onOpenChange,
|
||||
onConfirm,
|
||||
}: ResetPasswordDialogsProps) {
|
||||
const [copying, setCopying] = useState(false)
|
||||
const showingResult = password.trim().length > 0
|
||||
|
||||
async function handleCopy() {
|
||||
if (!password || copying) {
|
||||
return
|
||||
}
|
||||
|
||||
setCopying(true)
|
||||
try {
|
||||
await navigator.clipboard.writeText(password)
|
||||
toast.success("密码已复制")
|
||||
} catch {
|
||||
toast.error("复制失败,请手动复制")
|
||||
} finally {
|
||||
setCopying(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open && !showingResult} onOpenChange={onOpenChange}>
|
||||
<DialogContent showCloseButton={!saving}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>确认重置密码</DialogTitle>
|
||||
<DialogDescription>
|
||||
确认后将为 {item?.username || "-"} 生成新的随机密码,并使该用户当前登录会话失效。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button onClick={() => void onConfirm()} disabled={saving}>
|
||||
{saving ? "重置中..." : "确认重置"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={saving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<Dialog open={open && showingResult} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>重置密码成功</DialogTitle>
|
||||
<DialogDescription>
|
||||
{item?.username || "-"} 的新密码已生成,请及时复制并安全传达。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="rounded-xl border bg-muted/40 p-4">
|
||||
<div className="text-xs text-muted-foreground">新密码</div>
|
||||
<div className="mt-2 break-all font-mono text-base">{password}</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => void handleCopy()} disabled={copying}>
|
||||
<CopyIcon />
|
||||
{copying ? "复制中..." : "复制密码"}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => onOpenChange(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
"use client"
|
||||
|
||||
import { type KeyboardEvent, useCallback, useEffect, useState } from "react"
|
||||
import {
|
||||
KeyRoundIcon,
|
||||
MoreHorizontalIcon,
|
||||
PlusIcon,
|
||||
RefreshCwIcon,
|
||||
SearchIcon,
|
||||
ShieldIcon,
|
||||
UserRoundIcon,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import {
|
||||
assignUserRoles,
|
||||
createUser,
|
||||
fetchRoleListAll,
|
||||
fetchUserDetail,
|
||||
fetchUsers,
|
||||
resetUserPassword,
|
||||
updateUser,
|
||||
updateUserStatus,
|
||||
type AdminRole,
|
||||
type AdminUser,
|
||||
type CreateAdminUserPayload,
|
||||
type PageResult,
|
||||
type ResetPasswordResult,
|
||||
type UpdateAdminUserPayload,
|
||||
} from "@/lib/api/admin"
|
||||
import { Status } from "@/lib/generated/enums"
|
||||
import { formatDateTime } from "@/lib/utils"
|
||||
import { AssignRolesDrawer } from "./_components/assign-roles"
|
||||
import { CreateUserDrawer } from "./_components/create"
|
||||
import { EditDrawer } from "./_components/edit"
|
||||
import { InitialPasswordDialog } from "./_components/initial-password-dialog"
|
||||
import { ResetPasswordDialogs } from "./_components/reset-password"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ButtonGroup } from "@/components/ui/button-group"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ListPagination } from "@/components/list-pagination"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
export default function DashboardUsersPage() {
|
||||
const [keywordInput, setKeywordInput] = useState("")
|
||||
const [keyword, setKeyword] = useState("")
|
||||
const [page, setPage] = useState(1)
|
||||
const [limit, setLimit] = useState(20)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [creatingOpen, setCreatingOpen] = useState(false)
|
||||
const [savingCreate, setSavingCreate] = useState(false)
|
||||
const [initialPassword, setInitialPassword] = useState<{
|
||||
username: string
|
||||
password: string
|
||||
} | null>(null)
|
||||
const [savingEdit, setSavingEdit] = useState(false)
|
||||
const [savingPassword, setSavingPassword] = useState(false)
|
||||
const [savingRoles, setSavingRoles] = useState(false)
|
||||
const [editingUser, setEditingUser] = useState<AdminUser | null>(null)
|
||||
const [resettingUser, setResettingUser] = useState<AdminUser | null>(null)
|
||||
const [assigningRolesUser, setAssigningRolesUser] = useState<AdminUser | null>(null)
|
||||
const [assignRoleOptions, setAssignRoleOptions] = useState<AdminRole[]>([])
|
||||
const [assignRoleIds, setAssignRoleIds] = useState<number[]>([])
|
||||
const [assignRolesLoading, setAssignRolesLoading] = useState(false)
|
||||
const [resetPasswordResult, setResetPasswordResult] =
|
||||
useState<ResetPasswordResult | null>(null)
|
||||
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
|
||||
const [result, setResult] = useState<PageResult<AdminUser>>({
|
||||
results: [],
|
||||
page: { page: 1, limit: 20, total: 0 },
|
||||
})
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await fetchUsers({
|
||||
username: keyword.trim() || undefined,
|
||||
page,
|
||||
limit,
|
||||
})
|
||||
setResult(data)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "加载用户失败")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [keyword, limit, page])
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers()
|
||||
}, [loadUsers])
|
||||
|
||||
function applyFilters() {
|
||||
setKeyword(keywordInput)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleFilterKeyDown(event: KeyboardEvent<HTMLInputElement>) {
|
||||
if (event.key !== "Enter") {
|
||||
return
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
function openEditDrawer(user: AdminUser) {
|
||||
setEditingUser(user)
|
||||
}
|
||||
|
||||
async function openAssignRolesDrawer(user: AdminUser) {
|
||||
setActionLoadingId(user.id)
|
||||
setAssigningRolesUser(user)
|
||||
setAssignRolesLoading(true)
|
||||
try {
|
||||
const [roles, userDetail] = await Promise.all([
|
||||
fetchRoleListAll(),
|
||||
fetchUserDetail(user.id),
|
||||
])
|
||||
setAssignRoleOptions(roles)
|
||||
setAssignRoleIds((userDetail.roles || []).map((role) => role.id))
|
||||
} catch (error) {
|
||||
setAssigningRolesUser(null)
|
||||
toast.error(error instanceof Error ? error.message : "加载角色分配数据失败")
|
||||
} finally {
|
||||
setAssignRolesLoading(false)
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handlePageChange(nextPage: number) {
|
||||
if (nextPage < 1 || nextPage === page) {
|
||||
return
|
||||
}
|
||||
setPage(nextPage)
|
||||
}
|
||||
|
||||
function handleLimitChange(nextLimit: number) {
|
||||
if (nextLimit <= 0 || nextLimit === limit) {
|
||||
return
|
||||
}
|
||||
setLimit(nextLimit)
|
||||
setPage(1)
|
||||
}
|
||||
|
||||
function handleEditDrawerOpenChange(open: boolean) {
|
||||
if (savingEdit) {
|
||||
return
|
||||
}
|
||||
if (!open) {
|
||||
setEditingUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handleCreateDrawerOpenChange(open: boolean) {
|
||||
if (savingCreate) {
|
||||
return
|
||||
}
|
||||
if (!open) {
|
||||
setCreatingOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateUser(payload: CreateAdminUserPayload) {
|
||||
if (savingCreate) {
|
||||
return
|
||||
}
|
||||
|
||||
setSavingCreate(true)
|
||||
try {
|
||||
const result = await createUser(payload)
|
||||
toast.success(`已创建用户 ${result.user.username}`)
|
||||
setCreatingOpen(false)
|
||||
setInitialPassword({
|
||||
username: result.user.username,
|
||||
password: result.password,
|
||||
})
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "创建用户失败")
|
||||
} finally {
|
||||
setSavingCreate(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleAssignRolesOpenChange(open: boolean) {
|
||||
if (savingRoles) {
|
||||
return
|
||||
}
|
||||
if (!open) {
|
||||
setAssigningRolesUser(null)
|
||||
setAssignRoleOptions([])
|
||||
setAssignRoleIds([])
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveUser(payload: UpdateAdminUserPayload) {
|
||||
if (savingEdit) {
|
||||
return
|
||||
}
|
||||
|
||||
setSavingEdit(true)
|
||||
try {
|
||||
await updateUser(payload)
|
||||
toast.success(`已更新 ${editingUser?.username || "用户"}`)
|
||||
setEditingUser(null)
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "更新用户失败")
|
||||
} finally {
|
||||
setSavingEdit(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAssignRoles(roleIds: number[]) {
|
||||
if (!assigningRolesUser || savingRoles) {
|
||||
return
|
||||
}
|
||||
|
||||
setSavingRoles(true)
|
||||
try {
|
||||
await assignUserRoles(assigningRolesUser.id, roleIds)
|
||||
toast.success(`已更新 ${assigningRolesUser.username} 的角色`)
|
||||
setAssigningRolesUser(null)
|
||||
setAssignRoleOptions([])
|
||||
setAssignRoleIds([])
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "保存角色分配失败")
|
||||
} finally {
|
||||
setSavingRoles(false)
|
||||
}
|
||||
}
|
||||
|
||||
function openResetDrawer(user: AdminUser) {
|
||||
setResetPasswordResult(null)
|
||||
setResettingUser(user)
|
||||
}
|
||||
|
||||
function handleResetDrawerOpenChange(open: boolean) {
|
||||
if (savingPassword) {
|
||||
return
|
||||
}
|
||||
if (!open) {
|
||||
setResetPasswordResult(null)
|
||||
setResettingUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleResetPassword() {
|
||||
if (!resettingUser || savingPassword) {
|
||||
return
|
||||
}
|
||||
|
||||
setSavingPassword(true)
|
||||
try {
|
||||
const result = await resetUserPassword(resettingUser.id)
|
||||
setResetPasswordResult(result)
|
||||
toast.success(`已重置 ${resettingUser.username} 的密码`)
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "重置密码失败")
|
||||
} finally {
|
||||
setSavingPassword(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleStatus(user: AdminUser) {
|
||||
setActionLoadingId(user.id)
|
||||
try {
|
||||
const nextStatus = user.status === Status.Ok ? Status.Disabled : Status.Ok
|
||||
await updateUserStatus(user.id, nextStatus)
|
||||
toast.success(`${user.username} 已${nextStatus === Status.Ok ? "启用" : "禁用"}`)
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "更新状态失败")
|
||||
} finally {
|
||||
setActionLoadingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-1 flex-col gap-6 p-4 lg:p-6">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end">
|
||||
<Button onClick={() => setCreatingOpen(true)} disabled={loading}>
|
||||
<PlusIcon />
|
||||
添加用户
|
||||
</Button>
|
||||
<div className="relative min-w-72">
|
||||
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={keywordInput}
|
||||
onChange={(event) => setKeywordInput(event.target.value)}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
placeholder="按用户名筛选"
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" onClick={applyFilters} disabled={loading}>
|
||||
查询
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="overflow-hidden rounded-2xl border bg-background">
|
||||
<Table>
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow>
|
||||
<TableHead>用户</TableHead>
|
||||
<TableHead>角色</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>最后登录</TableHead>
|
||||
<TableHead>联系方式</TableHead>
|
||||
<TableHead className="w-[92px] text-right">操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{result.results.map((item) => (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
|
||||
<UserRoundIcon className="size-4" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium">{item.nickname || item.username}</div>
|
||||
<div className="text-xs text-muted-foreground">{item.username}</div>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{(item.roles || []).length > 0 ? (
|
||||
item.roles?.map((role) => (
|
||||
<Badge key={role.id} variant="outline">
|
||||
<ShieldIcon className="size-3" />
|
||||
{role.name}
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground">未分配</span>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={item.status === Status.Ok ? "secondary" : "outline"}>
|
||||
{item.status === Status.Ok ? "启用" : "禁用"}
|
||||
</Badge>
|
||||
{item.isSystem ? (
|
||||
<Badge variant="outline" className="ml-2">
|
||||
系统
|
||||
</Badge>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="text-sm">{formatDateTime(item.lastLoginAt)}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{item.lastLoginIp || "-"}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="text-sm">{item.mobile || "-"}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{item.email || "-"}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<ButtonGroup className="ml-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openEditDrawer(item)}
|
||||
disabled={actionLoadingId === item.id}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={<Button variant="outline" size="icon-sm" />}
|
||||
aria-label={`更多操作 ${item.username}`}
|
||||
>
|
||||
<MoreHorizontalIcon />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||
<DropdownMenuItem
|
||||
onClick={() => void openAssignRolesDrawer(item)}
|
||||
disabled={actionLoadingId === item.id}
|
||||
>
|
||||
<ShieldIcon />
|
||||
{actionLoadingId === item.id
|
||||
? "处理中..."
|
||||
: "分配角色"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => openResetDrawer(item)}
|
||||
disabled={actionLoadingId === item.id}
|
||||
>
|
||||
<KeyRoundIcon />
|
||||
重置密码
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleToggleStatus(item)}
|
||||
disabled={actionLoadingId === item.id}
|
||||
>
|
||||
<ShieldIcon />
|
||||
{actionLoadingId === item.id
|
||||
? "处理中..."
|
||||
: item.status === Status.Ok
|
||||
? "禁用"
|
||||
: "启用"}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</ButtonGroup>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{!loading && result.results.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="py-12 text-center text-muted-foreground">
|
||||
没有匹配的用户数据
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : null}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
<ListPagination
|
||||
page={result.page.page}
|
||||
total={result.page.total}
|
||||
limit={result.page.limit}
|
||||
loading={loading}
|
||||
onPageChange={handlePageChange}
|
||||
onLimitChange={handleLimitChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<CreateUserDrawer
|
||||
open={creatingOpen}
|
||||
saving={savingCreate}
|
||||
onOpenChange={handleCreateDrawerOpenChange}
|
||||
onSubmit={handleCreateUser}
|
||||
/>
|
||||
<InitialPasswordDialog
|
||||
open={!!initialPassword}
|
||||
username={initialPassword?.username ?? ""}
|
||||
password={initialPassword?.password ?? ""}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setInitialPassword(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<EditDrawer
|
||||
open={!!editingUser}
|
||||
saving={savingEdit}
|
||||
itemId={editingUser?.id ?? null}
|
||||
onOpenChange={handleEditDrawerOpenChange}
|
||||
onSubmit={handleSaveUser}
|
||||
/>
|
||||
<ResetPasswordDialogs
|
||||
open={!!resettingUser}
|
||||
saving={savingPassword}
|
||||
item={resettingUser}
|
||||
password={resetPasswordResult?.password || ""}
|
||||
onOpenChange={handleResetDrawerOpenChange}
|
||||
onConfirm={handleResetPassword}
|
||||
/>
|
||||
<AssignRolesDrawer
|
||||
open={!!assigningRolesUser}
|
||||
saving={savingRoles}
|
||||
loading={assignRolesLoading}
|
||||
item={assigningRolesUser}
|
||||
roles={assignRoleOptions}
|
||||
selectedRoleIds={assignRoleIds}
|
||||
onOpenChange={handleAssignRolesOpenChange}
|
||||
onSubmit={handleAssignRoles}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user