feat(team): add page

This commit is contained in:
2026-02-27 09:51:33 +08:00
parent 5325ef7b95
commit 6cb8f98004
29 changed files with 4557 additions and 11 deletions

View File

@@ -0,0 +1,131 @@
"use client"
import { getUserGroupAll, userAdd } from "@/components/label/api/user"
import {
Button,
Group,
Modal,
Select,
Stack,
TextInput,
} from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"
import { useEffect, useState } from "react"
interface ComponentProps {
opened: boolean
onCloseAction: (refresh?: boolean) => void
}
export default function CreateUserModal({
opened,
onCloseAction,
}: ComponentProps) {
const [groupOpts, setGroupOpts] = useState<Array<{ label: string; value: string }>>(
[]
)
const [submitting, setSubmitting] = useState(false)
const form = useForm({
initialValues: {
user_name: "",
group_uuid: "",
base_city: "",
},
validate: {
user_name: (v) => (v.trim() ? null : "请输入用户名"),
group_uuid: (v) => (v ? null : "请选择组织"),
base_city: (v) => (v.trim() ? null : "请输入所在地"),
},
})
useEffect(() => {
if (!opened) return
const run = async () => {
const res = await getUserGroupAll()
setGroupOpts(res ?? [])
}
queueMicrotask(run)
}, [opened])
const submit = form.onSubmit(async (values) => {
try {
setSubmitting(true)
await userAdd({
user_name: values.user_name.trim(),
group_uuid: values.group_uuid,
base_city: values.base_city.trim(),
})
notifications.show({
color: "green",
title: "操作成功",
message: "已新增用户",
})
form.reset()
onCloseAction(true)
} catch (e) {
notifications.show({
color: "red",
title: "操作失败",
message: e instanceof Error ? e.message : "请求失败",
})
} finally {
setSubmitting(false)
}
})
return (
<Modal
opened={opened}
onClose={() => onCloseAction()}
title="新增用户"
centered
size={560}
closeOnClickOutside={false}>
<form onSubmit={submit}>
<Stack gap="sm">
<TextInput
label="用户名"
size="xs"
radius="xs"
withAsterisk
{...form.getInputProps("user_name")}
/>
<Select
label="组织"
size="xs"
radius="xs"
withAsterisk
searchable
data={groupOpts}
{...form.getInputProps("group_uuid")}
/>
<TextInput
label="所在地"
size="xs"
radius="xs"
withAsterisk
{...form.getInputProps("base_city")}
/>
<Group justify="flex-end" mt="xs">
<Button
variant="default"
size="xs"
radius="xs"
onClick={() => onCloseAction()}>
</Button>
<Button
type="submit"
size="xs"
radius="xs"
loading={submitting}>
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}

View File

@@ -0,0 +1,168 @@
"use client"
import { getUserGroupAll, userEditById } from "@/components/label/api/user"
import { User } from "@/components/label/api/user/typing"
import {
Button,
Group,
Modal,
Select,
Stack,
TextInput,
} from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"
import { useEffect, useMemo, useState } from "react"
interface ComponentProps {
opened: boolean
data: User.UserInfo | null
onCloseAction: (refresh?: boolean) => void
}
export default function EditUserModal({
opened,
data,
onCloseAction,
}: ComponentProps) {
const [groupOpts, setGroupOpts] = useState<Array<{ label: string; value: string }>>(
[]
)
const [submitting, setSubmitting] = useState(false)
const groupValueByName = useMemo(() => {
const map = new Map<string, string>()
groupOpts.forEach((g) => map.set(g.label, g.value))
return map
}, [groupOpts])
const form = useForm({
initialValues: {
name: "",
group_uuid: "",
base_city: "",
work_status: "1",
},
validate: {
name: (v) => (v.trim() ? null : "请输入用户名"),
group_uuid: (v) => (v ? null : "请选择组织"),
base_city: (v) => (v.trim() ? null : "请输入所在地"),
work_status: (v) => (v ? null : "请选择状态"),
},
})
useEffect(() => {
if (!opened) return
const run = async () => {
const res = await getUserGroupAll()
setGroupOpts(res ?? [])
}
queueMicrotask(run)
}, [opened])
useEffect(() => {
if (!opened || !data) return
form.setValues({
name: data.name ?? "",
group_uuid: groupValueByName.get(data.group_name ?? "") ?? "",
base_city: data.base_city ?? "",
work_status: data.work_status === 0 ? "0" : "1",
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [opened, data, groupValueByName])
const submit = form.onSubmit(async (values) => {
if (!data?.uid) return
try {
setSubmitting(true)
await userEditById(
{
user_name: values.name.trim(),
group_uuid: values.group_uuid,
base_city: values.base_city.trim(),
work_status: Number(values.work_status),
},
data.uid
)
notifications.show({
color: "green",
title: "操作成功",
message: "已更新用户信息",
})
onCloseAction(true)
} catch (e) {
notifications.show({
color: "red",
title: "操作失败",
message: e instanceof Error ? e.message : "请求失败",
})
} finally {
setSubmitting(false)
}
})
return (
<Modal
opened={opened}
onClose={() => onCloseAction()}
title="编辑用户"
centered
size={560}
closeOnClickOutside={false}>
<form onSubmit={submit}>
<Stack gap="sm">
<TextInput
label="用户名"
size="xs"
radius="xs"
withAsterisk
{...form.getInputProps("name")}
/>
<Select
label="组织"
size="xs"
radius="xs"
withAsterisk
searchable
data={groupOpts}
{...form.getInputProps("group_uuid")}
/>
<TextInput
label="所在地"
size="xs"
radius="xs"
withAsterisk
{...form.getInputProps("base_city")}
/>
<Select
label="状态"
size="xs"
radius="xs"
withAsterisk
data={[
{ label: "在职", value: "1" },
{ label: "离职", value: "0" },
]}
{...form.getInputProps("work_status")}
/>
<Group justify="flex-end" mt="xs">
<Button
variant="default"
size="xs"
radius="xs"
onClick={() => onCloseAction()}>
</Button>
<Button
type="submit"
size="xs"
radius="xs"
loading={submitting}>
</Button>
</Group>
</Stack>
</form>
</Modal>
)
}

View File

@@ -0,0 +1,265 @@
"use client"
import { userImport } from "@/components/label/api/user"
import {
Alert,
Button,
FileInput,
Group,
Modal,
Paper,
Stack,
Text,
} from "@mantine/core"
import { notifications } from "@mantine/notifications"
import { IconAlertCircle, IconDownload, IconUpload } from "@tabler/icons-react"
import { useState } from "react"
import * as XLSX from "xlsx-js-style"
interface ComponentProps {
opened: boolean
onCloseAction: (refresh?: boolean) => void
}
type ImportItem = {
user_name: string
group_name: string
base_city: string
}
export default function ImportModal({ opened, onCloseAction }: ComponentProps) {
const [file, setFile] = useState<File | null>(null)
const [sheetList, setSheetList] = useState<ImportItem[]>([])
const [failedDataTips, setFailedDataTips] = useState<string[]>([])
const [submitting, setSubmitting] = useState(false)
const clearState = () => {
setFile(null)
setSheetList([])
setFailedDataTips([])
}
const parseFile = async (nextFile: File | null) => {
setFile(nextFile)
setSheetList([])
setFailedDataTips([])
if (!nextFile) return
if (!nextFile.name.endsWith(".xlsx")) {
notifications.show({
color: "red",
title: "文件格式错误",
message: "仅支持 .xlsx 文件",
})
setFile(null)
return
}
try {
const data = await nextFile.arrayBuffer()
const workbook = XLSX.read(data, { type: "array" })
const sheetName = workbook.SheetNames[0]
const ws = workbook.Sheets[sheetName]
const arr = XLSX.utils.sheet_to_json<any[]>(ws, { header: 1, raw: false })
const tableData = arr.slice(4).filter((row) => row.length > 0)
if (tableData.length === 0) {
setSheetList([])
return
}
const checkList: Record<number, string> = {
0: "用户名",
1: "组织",
2: "所在地",
}
const tipRows = 4
const errors: string[] = []
const list: ImportItem[] = tableData.map((item: any[], index: number) => {
Object.entries(checkList).forEach(([key, fieldName]) => {
const value = item[Number(key)]
if (!value || (typeof value === "string" && !value.trim())) {
errors.push(
`${index + 1 + tipRows}行数据缺少必填项【${fieldName}】或该必填项全为空格`
)
}
})
return {
user_name: item[0] ? String(item[0]).trim() : "",
group_name: item[1] ? String(item[1]).trim() : "",
base_city: item[2] ? String(item[2]).trim() : "",
}
})
if (errors.length > 0) {
setFailedDataTips(errors)
setSheetList([])
return
}
setSheetList(list)
} catch (e) {
notifications.show({
color: "red",
title: "解析失败",
message: e instanceof Error ? e.message : "读取文件失败",
})
setFile(null)
}
}
const exportTemplateFile = () => {
const tips = [
[`提示:\n1.下列字段均为必填项\n2.【组织】仅可以填入一个组织名称`],
[""],
[""],
]
const col = [["用户名", "组织", "所在地"]]
const wb = XLSX.utils.book_new()
const ws = XLSX.utils.aoa_to_sheet([...tips, ...col])
XLSX.utils.book_append_sheet(wb, ws, "用户信息")
wb.Sheets["用户信息"]["!rows"] = [{ hpx: 20 }, { hpx: 20 }, { hpx: 20 }]
wb.Sheets["用户信息"]["!cols"] = [{ wch: 20 }, { wch: 20 }, { wch: 20 }]
wb.Sheets["用户信息"]["!merges"] = [{ s: { c: 0, r: 0 }, e: { c: 2, r: 2 } }]
if (wb.Sheets["用户信息"]["A1"]) {
wb.Sheets["用户信息"]["A1"].s = { alignment: { wrapText: true } }
}
XLSX.writeFile(wb, "用户信息批量导入模板.xlsx")
}
const submit = async () => {
if (sheetList.length === 0) {
notifications.show({
color: "yellow",
title: "无导入数据",
message: "请先上传并校验 Excel 文件",
})
return
}
try {
setSubmitting(true)
const res = await userImport({ user_infos: sheetList })
if (Array.isArray(res) && res.length > 0) {
setFailedDataTips(res)
notifications.show({
color: "red",
title: "导入失败",
message: "请根据错误提示修正后重试",
})
return
}
notifications.show({
color: "green",
title: "导入成功",
message: "批量新增用户数据成功",
})
clearState()
onCloseAction(true)
} catch (e) {
notifications.show({
color: "red",
title: "导入失败",
message: e instanceof Error ? e.message : "请求失败",
})
} finally {
setSubmitting(false)
}
}
return (
<Modal
opened={opened}
onClose={() => {
clearState()
onCloseAction()
}}
title="批量导入用户信息"
centered
size={760}
closeOnClickOutside={false}>
<Stack gap="sm">
<Paper
withBorder
p="sm"
radius="sm"
style={{
borderColor:
"light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
}}>
<Group gap={8}>
<Text size="sm"></Text>
<Button
variant="subtle"
size="compact-sm"
leftSection={<IconDownload size={14} />}
onClick={exportTemplateFile}>
</Button>
<Text size="sm"></Text>
</Group>
</Paper>
<FileInput
label="上传文件"
description="支持单个 xlsx 文件上传"
size="xs"
radius="xs"
accept=".xlsx"
placeholder="请选择文件"
leftSection={<IconUpload size={16} />}
value={file}
onChange={parseFile}
clearable
/>
<Paper
withBorder
p="xs"
radius="sm"
style={{
borderColor:
"light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
}}>
<Text size="sm">{sheetList.length} </Text>
</Paper>
{failedDataTips.length > 0 ? (
<Alert
icon={<IconAlertCircle size={16} />}
color="red"
radius="sm"
title="错误信息提示">
<Stack gap={4} style={{ maxHeight: 180, overflowY: "auto" }}>
{failedDataTips.map((item) => (
<Text key={item} size="sm">
{item}
</Text>
))}
</Stack>
</Alert>
) : null}
<Group justify="flex-end">
<Button
variant="default"
size="xs"
radius="xs"
onClick={() => {
clearState()
onCloseAction()
}}>
</Button>
<Button
size="xs"
radius="xs"
onClick={submit}
loading={submitting}>
</Button>
</Group>
</Stack>
</Modal>
)
}

View File

@@ -0,0 +1,288 @@
"use client"
import { getUserList, userEditById } from "@/components/label/api/user"
import { User } from "@/components/label/api/user/typing"
import useAuth from "@/components/label/hooks/useAuth"
import { useAllUserStore } from "@/components/label/store/auth"
import {
ActionIcon,
Badge,
Button,
Group,
Paper,
Stack,
Text,
TextInput,
} from "@mantine/core"
import { modals } from "@mantine/modals"
import { notifications } from "@mantine/notifications"
import { IconEdit, IconPlus, IconRefresh, IconSearch, IconUpload } from "@tabler/icons-react"
import { DataTable, DataTableColumn } from "mantine-datatable"
import { useCallback, useEffect, useMemo, useState } from "react"
import CreateUserModal from "./components/CreateUserModal"
import EditUserModal from "./components/EditUserModal"
import ImportModal from "./components/ImportModal"
export default function TeamEmployeePage() {
const { isShow } = useAuth()
const setFlag = useAllUserStore((s) => s.setFlag)
const [name, setName] = useState("")
const [appliedName, setAppliedName] = useState("")
const [records, setRecords] = useState<User.UserInfo[]>([])
const [loading, setLoading] = useState(false)
const [totalItems, setTotalItems] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const [createOpened, setCreateOpened] = useState(false)
const [editOpened, setEditOpened] = useState(false)
const [importOpened, setImportOpened] = useState(false)
const [selectedUser, setSelectedUser] = useState<User.UserInfo | null>(null)
const load = useCallback(async () => {
try {
setLoading(true)
const params: User.ListRequest = {
page_number: page,
page_size: pageSize,
}
if (appliedName.trim()) params.name = appliedName.trim()
const res = await getUserList(params)
setRecords(res?.user_list ?? [])
setTotalItems(res?.total_items ?? 0)
} catch (e) {
setRecords([])
setTotalItems(0)
notifications.show({
color: "red",
title: "加载失败",
message: e instanceof Error ? e.message : "请求失败",
})
} finally {
setLoading(false)
}
}, [appliedName, page, pageSize])
useEffect(() => {
queueMicrotask(load)
}, [load])
const columns = useMemo(() => {
const cols: DataTableColumn<User.UserInfo>[] = [
{ accessor: "uid", title: "UID", width: 120, textAlign: "center" },
{ accessor: "name", title: "姓名", width: 120, textAlign: "center" },
{
accessor: "work_status",
title: "状态",
width: 100,
textAlign: "center",
render: (record) =>
record.work_status === 1 ? (
<Badge color="green" variant="light">
</Badge>
) : (
<Badge color="gray" variant="light">
</Badge>
),
},
{
accessor: "group_name",
title: "组织",
width: 180,
textAlign: "center",
},
{
accessor: "base_city",
title: "所在地",
width: 180,
textAlign: "center",
},
{
accessor: "operation",
title: "操作",
width: 220,
textAlign: "center",
render: (record) => (
<Group justify="center" gap={4} wrap="nowrap">
{isShow("edit") ? (
<Button
variant="subtle"
size="compact-xs"
onClick={() => {
modals.openConfirmModal({
title: "重置密码",
centered: true,
children: (
<Text size="sm"> 123456</Text>
),
labels: { confirm: "确定", cancel: "取消" },
onConfirm: async () => {
await userEditById({ password: "123456" }, record.uid)
notifications.show({
color: "green",
title: "操作成功",
message: "已重置密码",
})
},
})
}}>
</Button>
) : null}
{isShow("edit") ? (
<ActionIcon
variant="subtle"
color="blue"
onClick={() => {
setSelectedUser(record)
setEditOpened(true)
}}>
<IconEdit size={16} />
</ActionIcon>
) : null}
</Group>
),
},
]
return cols
}, [isShow])
return (
<Stack w="100%" h="calc(100vh - 56px)" p="md" gap="md">
<Paper
withBorder
p="md"
radius="md"
style={{
borderColor:
"light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
}}>
<Group justify="space-between" wrap="wrap">
<Group>
<TextInput
placeholder="请输入姓名"
size="xs"
radius="xs"
value={name}
onChange={(e) => setName(e.currentTarget.value)}
/>
<Button
size="xs"
radius="xs"
leftSection={<IconSearch size={16} />}
onClick={() => {
setAppliedName(name)
setPage(1)
}}>
</Button>
<Button
variant="default"
size="xs"
radius="xs"
leftSection={<IconRefresh size={16} />}
onClick={() => {
setName("")
setAppliedName("")
setPage(1)
setPageSize(20)
}}>
</Button>
</Group>
<Group>
{isShow("add") ? (
<Button
size="xs"
radius="xs"
leftSection={<IconPlus size={16} />}
onClick={() => setCreateOpened(true)}>
</Button>
) : null}
{isShow("add") ? (
<Button
size="xs"
radius="xs"
variant="default"
leftSection={<IconUpload size={16} />}
onClick={() => setImportOpened(true)}>
</Button>
) : null}
</Group>
</Group>
</Paper>
<Paper
withBorder
p="md"
radius="md"
style={{
borderColor:
"light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4))",
flex: 1,
minHeight: 0,
display: "flex",
}}>
<DataTable<User.UserInfo>
withTableBorder
withRowBorders
fetching={loading}
records={records}
columns={columns}
noRecordsText="暂无数据"
totalRecords={totalItems}
recordsPerPage={pageSize}
page={page}
onPageChange={setPage}
onRecordsPerPageChange={(v) => {
setPageSize(v)
setPage(1)
}}
recordsPerPageOptions={[10, 20, 50, 100]}
scrollAreaProps={{ type: "auto" }}
style={{ width: "100%" }}
/>
</Paper>
<CreateUserModal
opened={createOpened}
onCloseAction={(refresh) => {
setCreateOpened(false)
if (refresh) {
setFlag(true)
load()
}
}}
/>
<ImportModal
opened={importOpened}
onCloseAction={(refresh) => {
setImportOpened(false)
if (refresh) {
setFlag(true)
load()
}
}}
/>
<EditUserModal
opened={editOpened}
data={selectedUser}
onCloseAction={(refresh) => {
setEditOpened(false)
setSelectedUser(null)
if (refresh) {
setFlag(true)
load()
}
}}
/>
</Stack>
)
}

View File

@@ -1,5 +0,0 @@
"use client"
export default function EmployeePage() {
return <></>
}