wsj
5 days ago 4a7848a4bec14542b8574d250684dd631a388c1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  DownloadOutlined,
  InboxOutlined,
  PlusOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import type { ActionType } from '@ant-design/pro-components';
import {
  App as AntdApp,
  Button,
  Descriptions,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Tag,
  Upload,
} from 'antd';
import type { UploadFile } from 'antd';
import { createUserColumns, getEmployeeStatusMeta } from './columns';
import {
  createEmployee,
  deleteEmployee,
  exportEmployees,
  getEmployeeDetail,
  getEmployeeList,
  getOrgTree,
  getRoleOptions,
  importEmployees,
  updateEmployee,
} from './server';
import type {
  EmployeeFormValues,
  EmployeeListQuery,
  EmployeeVO,
  OrgTreeNode,
  SelectOption,
  TenantEmployeeListRequest,
} from './types';
import './Users.scss';
 
const flattenOrgOptions = (nodes: OrgTreeNode[]): SelectOption[] =>
  nodes.flatMap((node) => [
    { label: node.orgName, value: node.id },
    ...flattenOrgOptions(node.children ?? []),
  ]);
 
const Users = () => {
  const actionRef = useRef<ActionType>();
  const lastQueryRef = useRef<TenantEmployeeListRequest>({});
  const { message, modal } = AntdApp.useApp();
  const [form] = Form.useForm<EmployeeFormValues>();
  const [orgOptions, setOrgOptions] = useState<SelectOption[]>([]);
  const [roleOptions, setRoleOptions] = useState<SelectOption[]>([]);
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<EmployeeVO | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [detail, setDetail] = useState<EmployeeVO | null>(null);
  const [detailOpen, setDetailOpen] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [importFileList, setImportFileList] = useState<UploadFile[]>([]);
  const [importing, setImporting] = useState(false);
  const [exporting, setExporting] = useState(false);
 
  useEffect(() => {
    let active = true;
 
    const loadOptions = async () => {
      try {
        const [orgs, roles] = await Promise.all([getOrgTree(), getRoleOptions()]);
        if (!active) return;
 
        setOrgOptions(flattenOrgOptions(orgs));
        setRoleOptions(roles.map((role) => ({ label: role.roleName, value: role.id })));
      } catch {
        // 错误已由 request 统一提示
      }
    };
 
    void loadOptions();
 
    return () => {
      active = false;
    };
  }, []);
 
  const orgNameMap = useMemo(
    () => new Map(orgOptions.map((option) => [option.value, option.label])),
    [orgOptions],
  );
 
  const roleNameMap = useMemo(
    () => new Map(roleOptions.map((option) => [option.value, option.label])),
    [roleOptions],
  );
 
  const openCreate = useCallback(() => {
    setEditing(null);
    form.resetFields();
    setFormOpen(true);
  }, [form]);
 
  const closeForm = useCallback(() => {
    setFormOpen(false);
    setEditing(null);
  }, []);
 
  const openEdit = useCallback(
    (record: EmployeeVO) => {
      setEditing(record);
      form.setFieldsValue({
        name: record.name,
        phone: record.phone,
        orgId: record.orgId,
        roleId: record.roleId,
        position: record.position,
        email: record.email,
        holdLimit: record.holdLimit,
        region: record.region,
      });
      setFormOpen(true);
    },
    [form],
  );
 
  const handleDetail = useCallback(async (record: EmployeeVO) => {
    setDetail(null);
    setDetailOpen(true);
    setDetailLoading(true);
 
    try {
      const data = await getEmployeeDetail({ id: record.id });
      setDetail(data);
    } catch {
      // 错误已由 request 统一提示
      setDetailOpen(false);
    } finally {
      setDetailLoading(false);
    }
  }, []);
 
  const handleDelete = useCallback(
    (record: EmployeeVO) => {
      modal.confirm({
        title: '删除员工',
        content: `确定要删除员工「${record.name}」吗?删除后不可恢复。`,
        okText: '删除',
        cancelText: '取消',
        okButtonProps: { danger: true },
        onOk: async () => {
          await deleteEmployee({ id: record.id });
          message.success('员工已删除');
          actionRef.current?.reload();
        },
      });
    },
    [message, modal],
  );
 
  const handleSubmit = useCallback(async () => {
    let values: EmployeeFormValues;
    try {
      values = await form.validateFields();
    } catch {
      return;
    }
 
    setSubmitting(true);
    try {
      if (editing) {
        await updateEmployee({ id: editing.id, ...values });
        message.success('员工信息已更新');
      } else {
        await createEmployee(values);
        message.success('员工创建成功');
      }
 
      setFormOpen(false);
      setEditing(null);
      form.resetFields();
      actionRef.current?.reload();
    } catch {
      // 错误已由 request 统一提示
    } finally {
      setSubmitting(false);
    }
  }, [editing, form, message]);
 
  const handleExport = useCallback(async () => {
    setExporting(true);
    try {
      const blob = await exportEmployees({ orgId: lastQueryRef.current.orgId });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'employees.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.setTimeout(() => URL.revokeObjectURL(url), 0);
      message.success('导出成功');
    } catch {
      // 错误已由 request 统一提示
    } finally {
      setExporting(false);
    }
  }, [message]);
 
  const handleImport = useCallback(async () => {
    const file = importFileList[0]?.originFileObj;
    if (!file) {
      message.warning('请先选择要导入的 Excel 文件');
      return;
    }
 
    setImporting(true);
    try {
      const count = await importEmployees({ file });
      message.success(`成功导入 ${count} 条员工`);
      setImportOpen(false);
      setImportFileList([]);
      actionRef.current?.reload();
    } catch {
      // 错误已由 request 统一提示
    } finally {
      setImporting(false);
    }
  }, [importFileList, message]);
 
  const columns = useMemo(
    () =>
      createUserColumns({
        orgOptions,
        roleOptions,
        orgNameMap,
        roleNameMap,
        onDetail: handleDetail,
        onEdit: openEdit,
        onDelete: handleDelete,
      }),
    [orgOptions, roleOptions, orgNameMap, roleNameMap, handleDetail, openEdit, handleDelete],
  );
 
  return (
    <div className="users-page">
      <ProTable<EmployeeVO, EmployeeListQuery>
        rowKey="id"
        actionRef={actionRef}
        columns={columns}
        cardProps={{ className: 'table-card' }}
        search={{ labelWidth: 'auto', defaultCollapsed: false }}
        scroll={{ x: 1290 }}
        options={false}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          hideOnSinglePage: false,
          showTotal: (total) => `共 ${total} 条`,
        }}
        toolBarRender={() => [
          <Button
            key="import"
            icon={<UploadOutlined />}
            onClick={() => {
              setImportFileList([]);
              setImportOpen(true);
            }}
          >
            导入
          </Button>,
          <Button
            key="export"
            icon={<DownloadOutlined />}
            loading={exporting}
            onClick={handleExport}
          >
            导出
          </Button>,
          <Button key="create" type="primary" icon={<PlusOutlined />} onClick={openCreate}>
            新增员工
          </Button>,
        ]}
        request={async (params) => {
          const query: TenantEmployeeListRequest = {
            page: params.current,
            size: params.pageSize,
            keyword: params.keyword?.trim() || undefined,
            status: params.status,
            orgId: params.orgId,
            roleId: params.roleId,
          };
          lastQueryRef.current = query;
 
          const result = await getEmployeeList(query);
 
          return {
            data: result.records ?? [],
            total: result.total ?? 0,
            success: true,
          };
        }}
      />
 
      <Drawer
        title={editing ? '编辑员工' : '新增员工'}
        width={420}
        open={formOpen}
        forceRender
        onClose={closeForm}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={closeForm}>取消</Button>
            <Button type="primary" loading={submitting} onClick={handleSubmit}>
              {editing ? '保存' : '创建'}
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入员工姓名" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
            ]}
          >
            <Input placeholder="请输入手机号" maxLength={11} />
          </Form.Item>
          <Form.Item
            name="orgId"
            label="所属组织"
            rules={[{ required: true, message: '请选择所属组织' }]}
          >
            <Select
              showSearch
              optionFilterProp="label"
              options={orgOptions}
              placeholder="请选择所属组织"
            />
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              showSearch
              optionFilterProp="label"
              options={roleOptions}
              placeholder="请选择角色"
            />
          </Form.Item>
          <Form.Item name="position" label="职位">
            <Input placeholder="请输入职位" />
          </Form.Item>
          <Form.Item name="region" label="负责区域">
            <Input placeholder="请输入负责区域" />
          </Form.Item>
          <Form.Item name="holdLimit" label="客户持有上限">
            <InputNumber min={0} precision={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ type: 'email', message: '请输入正确的邮箱' }]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
        </Form>
      </Drawer>
 
      <Drawer
        title="员工详情"
        width={480}
        open={detailOpen}
        loading={detailLoading}
        onClose={() => {
          setDetailOpen(false);
          setDetail(null);
        }}
      >
        {detail && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="姓名">{detail.name}</Descriptions.Item>
            <Descriptions.Item label="手机号">{detail.phone}</Descriptions.Item>
            <Descriptions.Item label="所属组织">
              {orgNameMap.get(detail.orgId) ?? `#${detail.orgId}`}
            </Descriptions.Item>
            <Descriptions.Item label="角色">
              {roleNameMap.get(detail.roleId) ?? `#${detail.roleId}`}
            </Descriptions.Item>
            <Descriptions.Item label="职位">{detail.position || '-'}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{detail.email || '-'}</Descriptions.Item>
            <Descriptions.Item label="负责区域">{detail.region || '-'}</Descriptions.Item>
            <Descriptions.Item label="客户持有上限">
              {detail.holdLimit ?? '-'}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getEmployeeStatusMeta(detail.status).color} bordered={false}>
                {getEmployeeStatusMeta(detail.status).text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="入职日期">{detail.hireDate || '-'}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{detail.createdAt || '-'}</Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
 
      <Modal
        title="导入员工"
        open={importOpen}
        onOk={handleImport}
        onCancel={() => {
          setImportOpen(false);
          setImportFileList([]);
        }}
        confirmLoading={importing}
        okText="导入"
        cancelText="取消"
      >
        <Upload.Dragger
          accept=".xlsx,.xls"
          maxCount={1}
          fileList={importFileList}
          beforeUpload={() => false}
          onChange={({ fileList }) => setImportFileList(fileList)}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽 Excel 文件到此处</p>
          <p className="ant-upload-hint">仅支持 .xlsx / .xls 格式</p>
        </Upload.Dragger>
      </Modal>
    </div>
  );
};
 
export default Users;