Sfoglia il codice sorgente

✨ feat(client): 实现客户管理功能模块化与状态分类

- 重构客户菜单结构,将"客户管理"拆分为"全部客户"、"待审核"、"已审核"和"已拒绝"四个子菜单
- 创建通用ClientList组件,支持按审核状态筛选客户数据
- 新增PendingClients、ApprovedClients和RejectedClients页面,分别对应不同审核状态的客户列表
- 添加客户列表路由配置,实现不同状态客户页面的访问
- 实现客户列表的搜索、分页、详情查看、编辑和删除功能
- 优化客户数据展示,包括项目名称、地区信息、审核状态等关键信息的表格展示
yourname 8 mesi fa
parent
commit
7c5828e6a8

+ 20 - 2
src/client/admin/menu.tsx

@@ -101,11 +101,29 @@ export const useMenu = () => {
       icon: <CustomerServiceOutlined />,
       icon: <CustomerServiceOutlined />,
       children: [
       children: [
         {
         {
-          key: 'customers',
-          label: '客户管理',
+          key: 'customers-all',
+          label: '全部客户',
           path: '/admin/clients',
           path: '/admin/clients',
           permission: 'client:manage'
           permission: 'client:manage'
         },
         },
+        {
+          key: 'customers-pending',
+          label: '待审核',
+          path: '/admin/clients/pending',
+          permission: 'client:manage'
+        },
+        {
+          key: 'customers-approved',
+          label: '已审核',
+          path: '/admin/clients/approved',
+          permission: 'client:manage'
+        },
+        {
+          key: 'customers-rejected',
+          label: '已拒绝',
+          path: '/admin/clients/rejected',
+          permission: 'client:manage'
+        },
         {
         {
           key: 'contacts',
           key: 'contacts',
           label: '联系人管理',
           label: '联系人管理',

+ 8 - 0
src/client/admin/pages/clients/ApprovedClients.tsx

@@ -0,0 +1,8 @@
+import React from 'react';
+import ClientList from './ClientList';
+
+const ApprovedClients: React.FC = () => {
+  return <ClientList auditStatus={1} pageTitle="已审核客户" />;
+};
+
+export default ApprovedClients;

+ 606 - 0
src/client/admin/pages/clients/ClientList.tsx

@@ -0,0 +1,606 @@
+import React, { useState, useEffect } from 'react';
+import { Table, Button, Space, Input, Modal, Form, Select } from 'antd';
+import { App } from 'antd';
+import AreaTreeSelect from '@/client/admin/components/AreaTreeSelect';
+import UserSelect from '@/client/admin/components/UserSelect';
+import AuditButtons from '@/client/admin/components/AuditButtons';
+import ClientDetailModal from '@/client/admin/components/ClientDetailModal';
+import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, EyeOutlined } from '@ant-design/icons';
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
+import { clientClient, areaClient } from '@/client/api';
+import type { InferResponseType } from 'hono/client';
+
+// 定义类型
+type ClientItem = InferResponseType<typeof clientClient.$get, 200>['data'][0];
+type ClientListResponse = InferResponseType<typeof clientClient.$get, 200>;
+type AreaItem = InferResponseType<typeof areaClient.$get, 200>['data'][0];
+
+interface ClientListProps {
+  auditStatus: number;
+  pageTitle: string;
+}
+
+const ClientList: React.FC<ClientListProps> = ({ auditStatus, pageTitle }) => {
+  const { message } = App.useApp();
+  const [form] = Form.useForm();
+  const [modalVisible, setModalVisible] = useState(false);
+  const [detailModalVisible, setDetailModalVisible] = useState(false);
+  const [selectedClientId, setSelectedClientId] = useState<number | null>(null);
+  const [editingKey, setEditingKey] = useState<string | null>(null);
+  const [searchText, setSearchText] = useState('');
+  const [areas, setAreas] = useState<AreaItem[]>([]);
+  const queryClient = useQueryClient();
+  
+  const [pagination, setPagination] = useState({
+    current: 1,
+    pageSize: 10,
+  });
+
+  // 获取区域列表
+  const { data: areasData } = useQuery({
+    queryKey: ['areas'],
+    queryFn: async (): Promise<InferResponseType<typeof areaClient.$get, 200>> => {
+      const res = await areaClient.$get({ query: { page: 1, pageSize: 1000 } });
+      if (!res.ok) {
+        throw new Error('获取区域列表失败');
+      }
+      return res.json();
+    }
+  });
+
+  // 处理区域数据
+  useEffect(() => {
+    if (areasData?.data) {
+      setAreas(areasData.data);
+    }
+  }, [areasData]);
+
+  // 获取区域显示名称
+  const getAreaDisplay = (areaId: number | null, type: 'province' | 'region') => {
+    if (!areaId) return '-';
+    
+    const area = areas.find(a => a.id === areaId);
+    if (!area) return '-';
+    
+    if (type === 'province') {
+      if (!area.parentId) {
+        return area.name;
+      }
+      const parentArea = areas.find(a => a.id === area.parentId);
+      return parentArea ? parentArea.name : area.name;
+    }
+    
+    if (type === 'region') {
+      if (area.parentId) {
+        return area.name;
+      }
+      return '-';
+    }
+    
+    return '-';
+  };
+
+  // 获取客户列表数据
+  const { data: clientsData, isLoading: clientsLoading, error: clientsError } = useQuery({
+    queryKey: ['clients', pagination.current, pagination.pageSize, searchText, auditStatus],
+    queryFn: async () => {
+      const filters: Record<string, any> = {};
+      filters.auditStatus = auditStatus;
+
+      const query: any = {
+        page: pagination.current,
+        pageSize: pagination.pageSize,
+        keyword: searchText,
+        filters: JSON.stringify(filters)
+      };
+      
+      const res = await clientClient.$get({ query });
+      if (!res.ok) {
+        throw new Error('获取客户列表失败');
+      }
+      return res.json() as Promise<ClientListResponse>;
+    }
+  });
+
+  // 错误处理
+  useEffect(() => {
+    if (clientsError) {
+      message.error('获取客户列表失败');
+    }
+  }, [clientsError, message]);
+
+  // 搜索
+  const handleSearch = () => {
+    setPagination({ ...pagination, current: 1 });
+  };
+
+  // 分页变化
+  const handleTableChange = (newPagination: any) => {
+    setPagination(newPagination);
+  };
+
+  // 显示添加/编辑弹窗
+  const showModal = (record?: ClientItem) => {
+    setModalVisible(true);
+    if (record) {
+      setEditingKey(record.id.toString());
+      form.setFieldsValue({
+        companyName: record.companyName,
+        areaId: record.areaId,
+        square: record.square,
+        address: record.address,
+        contactPerson: record.contactPerson,
+        position: record.position,
+        mobile: record.mobile,
+        zipCode: record.zipCode,
+        telephone: record.telephone,
+        fax: record.fax,
+        homepage: record.homepage,
+        email: record.email,
+        industry: record.industry,
+        subIndustry: record.subIndustry,
+        customerType: record.customerType,
+        startDate: record.startDate ? new Date(record.startDate) : null,
+        source: record.source,
+        description: record.description,
+        responsibleUserId: record.responsibleUserId,
+        salesPersonId: record.salesPersonId,
+        operatorId: record.operatorId,
+        groupId: record.groupId,
+        remarks: record.remarks,
+        status: record.status,
+        auditStatus: record.auditStatus,
+      });
+    } else {
+      setEditingKey(null);
+      form.resetFields();
+      form.setFieldsValue({ auditStatus });
+    }
+  };
+
+  // 关闭弹窗
+  const handleCancel = () => {
+    setModalVisible(false);
+    form.resetFields();
+  };
+
+  // 查看客户详情
+  const showDetailModal = (record: ClientItem) => {
+    setSelectedClientId(record.id);
+    setDetailModalVisible(true);
+  };
+
+  // 关闭详情弹窗
+  const handleDetailModalClose = () => {
+    setDetailModalVisible(false);
+    setSelectedClientId(null);
+  };
+
+  // 创建客户
+  const createClient = useMutation({
+    mutationFn: async (data: any) => {
+      const res = await clientClient.$post({ json: data as any });
+      if (!res.ok) {
+        throw new Error('创建客户失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('客户创建成功');
+      queryClient.invalidateQueries({ queryKey: ['clients'] });
+    }
+  });
+
+  // 更新客户
+  const updateClient = useMutation({
+    mutationFn: async ({ id, data }: { id: string; data: any }) => {
+      const res = await clientClient[':id'].$put({
+        param: { id: Number(id) },
+        json: data,
+      });
+      if (!res.ok) {
+        throw new Error('更新客户失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('客户更新成功');
+      queryClient.invalidateQueries({ queryKey: ['clients'] });
+    }
+  });
+
+  const handleSubmit = async () => {
+    try {
+      const values = await form.validateFields();
+      
+      if (values.startDate) {
+        values.startDate = values.startDate.format('YYYY-MM-DD');
+      }
+      
+      if (editingKey) {
+        await updateClient.mutateAsync({ id: editingKey, data: values });
+      } else {
+        await createClient.mutateAsync(values);
+      }
+      
+      setModalVisible(false);
+    } catch (error) {
+      message.error('操作失败,请重试');
+    }
+  };
+
+  // 删除客户
+  const deleteClient = useMutation({
+    mutationFn: async (id: number) => {
+      const res = await clientClient[':id'].$delete({ param: { id } });
+      if (!res.ok) {
+        throw new Error('删除客户失败');
+      }
+      return res.json();
+    },
+    onSuccess: () => {
+      message.success('客户删除成功');
+      queryClient.invalidateQueries({ queryKey: ['clients'] });
+    }
+  });
+
+  const handleDelete = async (id: number) => {
+    try {
+      await deleteClient.mutateAsync(id);
+    } catch (error) {
+      message.error('删除失败,请重试');
+    }
+  };
+
+  // 表格列定义
+  const columns = [
+    {
+      title: '项目名称',
+      dataIndex: 'companyName',
+      key: 'companyName',
+      width: 200,
+      ellipsis: true,
+    },
+    {
+      title: '省份',
+      dataIndex: 'areaId',
+      key: 'province',
+      width: 100,
+      render: (areaId: number) => getAreaDisplay(areaId, 'province'),
+    },
+    {
+      title: '地区',
+      dataIndex: 'areaId',
+      key: 'region',
+      width: 100,
+      render: (areaId: number) => getAreaDisplay(areaId, 'region'),
+    },
+    {
+      title: '登记审核',
+      dataIndex: 'auditStatus',
+      key: 'auditStatus',
+      width: 150,
+      render: (status: number, record: ClientItem) => (
+        <AuditButtons
+          recordId={record.id}
+          currentStatus={status}
+        />
+      ),
+    },
+    {
+      title: '主产品/合同估额',
+      dataIndex: 'description',
+      key: 'productAmount',
+      width: 180,
+      ellipsis: true,
+      render: (description: string) => description || '-',
+    },
+    {
+      title: '投资方',
+      dataIndex: 'industry',
+      key: 'investor',
+      width: 150,
+      ellipsis: true,
+      render: (industry: string) => industry || '-',
+    },
+    {
+      title: '产品大类',
+      dataIndex: 'customerType',
+      key: 'productCategory',
+      width: 120,
+      ellipsis: true,
+      render: (customerType: string) => customerType || '-',
+    },
+    {
+      title: '业务员',
+      dataIndex: 'salesPerson',
+      key: 'salesperson',
+      width: 120,
+      render: (salesPerson: ClientItem['salesPerson']) => {
+        return salesPerson?.name || salesPerson?.username || '-';
+      },
+    },
+    {
+      title: '联系人/电话',
+      key: 'contactPhone',
+      width: 180,
+      render: (_: any, record: ClientItem) => (
+        <div>
+          <div>{record.contactPerson || '-'}</div>
+          <div className="text-gray-500 text-sm">{record.mobile || record.telephone || '-'}</div>
+        </div>
+      ),
+    },
+    {
+      title: '预计投标时间',
+      dataIndex: 'oeDate',
+      key: 'bidTime',
+      width: 120,
+      render: (date: string) => {
+        return date ? new Date(date).toLocaleDateString() : '-';
+      },
+    },
+    {
+      title: '更新时间',
+      dataIndex: 'updatedAt',
+      key: 'updatedAt',
+      width: 150,
+      render: (date: string) => new Date(date).toLocaleDateString(),
+    },
+    {
+      title: '操作员',
+      dataIndex: 'operator',
+      key: 'operator',
+      width: 100,
+      render: (operator: ClientItem['operator']) => {
+        return operator?.name || operator?.username || '-';
+      },
+    },
+    {
+      title: '操作',
+      key: 'action',
+      width: 180,
+      fixed: 'right' as const,
+      render: (_: any, record: ClientItem) => (
+        <Space size="small">
+          <Button
+            size="small"
+            type="link"
+            icon={<EyeOutlined />}
+            onClick={() => showDetailModal(record)}
+          >
+            详情
+          </Button>
+          <Button
+            size="small"
+            type="link"
+            icon={<EditOutlined />}
+            onClick={() => showModal(record)}
+          >
+            编辑
+          </Button>
+          <Button
+            size="small"
+            type="text"
+            danger
+            icon={<DeleteOutlined />}
+            onClick={() => handleDelete(record.id)}
+          >
+            删除
+          </Button>
+        </Space>
+      ),
+    },
+  ];
+
+  return (
+    <div className="p-6">
+      <div className="mb-6 flex justify-between items-center">
+        <h2 className="text-2xl font-bold text-gray-800">{pageTitle}</h2>
+        <Button
+          type="primary"
+          icon={<PlusOutlined />}
+          onClick={() => showModal()}
+          className="shadow-sm hover:shadow-md transition-all duration-200"
+        >
+          添加客户
+        </Button>
+      </div>
+      
+      <div className="mb-6 p-4 bg-white rounded-lg shadow-sm">
+        <div className="flex items-center space-x-4">
+          <Input
+            placeholder="搜索项目名称、联系人或电话"
+            prefix={<SearchOutlined />}
+            value={searchText}
+            onChange={(e) => setSearchText(e.target.value)}
+            onPressEnter={handleSearch}
+            className="max-w-md"
+            allowClear
+          />
+          <Button
+            type="primary"
+            onClick={handleSearch}
+            className="hover:shadow-md transition-all duration-200"
+          >
+            搜索
+          </Button>
+          <Button onClick={() => {
+            setSearchText('');
+            setPagination({ ...pagination, current: 1 });
+          }}>
+            重置
+          </Button>
+        </div>
+      </div>
+      
+      <div className="bg-white rounded-lg shadow-sm overflow-hidden">
+        <Table
+          columns={columns}
+          dataSource={clientsData?.data || []}
+          rowKey="id"
+          loading={clientsLoading}
+          pagination={{
+            ...pagination,
+            total: clientsData?.pagination.total || 0,
+            showSizeChanger: true,
+            showQuickJumper: true,
+            showTotal: (total, range) =>
+              `显示 ${range[0]}-${range[1]} 条,共 ${total} 条`,
+            pageSizeOptions: [10, 20, 50, 100],
+            responsive: true,
+          }}
+          onChange={handleTableChange}
+          bordered={false}
+          scroll={{ x: 1500 }}
+          className="w-full"
+          rowClassName={(record, index) =>
+            index % 2 === 0 ? 'bg-white hover:bg-gray-50' : 'bg-gray-50 hover:bg-gray-100'
+          }
+        />
+      </div>
+      
+      <Modal
+        title={editingKey ? "编辑项目" : "添加项目"}
+        open={modalVisible}
+        onCancel={handleCancel}
+        footer={[
+          <Button key="cancel" onClick={handleCancel}>
+            取消
+          </Button>,
+          <Button key="submit" type="primary" onClick={handleSubmit} loading={editingKey ? updateClient.isPending : createClient.isPending}>
+            确定
+          </Button>,
+        ]}
+        width={800}
+      >
+        <Form form={form} layout="vertical">
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="companyName"
+              label="项目名称"
+              rules={[{ required: true, message: '请输入项目名称' }]}
+            >
+              <Input placeholder="请输入项目名称" />
+            </Form.Item>
+            
+            <Form.Item
+              name="auditStatus"
+              label="登记审核"
+              initialValue={auditStatus}
+            >
+              <Select>
+                <Select.Option value={0}>待审核</Select.Option>
+                <Select.Option value={1}>已审核</Select.Option>
+                <Select.Option value={2}>已拒绝</Select.Option>
+              </Select>
+            </Form.Item>
+          </div>
+          
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="areaId"
+              label="省份/地区"
+            >
+              <AreaTreeSelect
+                placeholder="请选择省份/地区"
+                value={form.getFieldValue('areaId') || undefined}
+                onChange={(value) => form.setFieldValue('areaId', value)}
+              />
+            </Form.Item>
+          </div>
+          
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="description"
+              label="主产品/合同估额"
+            >
+              <Input.TextArea rows={2} placeholder="请输入主产品或合同金额" />
+            </Form.Item>
+            
+            <Form.Item
+              name="industry"
+              label="投资方"
+            >
+              <Input placeholder="请输入投资方信息" />
+            </Form.Item>
+          </div>
+          
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="customerType"
+              label="产品大类"
+            >
+              <Input placeholder="请输入产品大类" />
+            </Form.Item>
+            
+            <Form.Item
+              name="salesPersonId"
+              label="业务员"
+            >
+              <UserSelect placeholder="请选择业务员" />
+            </Form.Item>
+          </div>
+          
+          <Form.Item
+            name="address"
+            label="地址"
+          >
+            <Input placeholder="请输入详细地址" />
+          </Form.Item>
+          
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="contactPerson"
+              label="联系人"
+            >
+              <Input placeholder="请输入联系人姓名" />
+            </Form.Item>
+            
+            <Form.Item
+              name="mobile"
+              label="联系电话"
+            >
+              <Input placeholder="请输入联系电话" />
+            </Form.Item>
+          </div>
+          
+          <div className="grid grid-cols-2 gap-4">
+            <Form.Item
+              name="oeDate"
+              label="预计投标时间"
+            >
+              <Input placeholder="请输入预计投标时间" />
+            </Form.Item>
+            
+            <Form.Item
+              name="status"
+              label="项目状态"
+              initialValue={1}
+            >
+              <Select>
+                <Select.Option value={0}>无效</Select.Option>
+                <Select.Option value={1}>有效</Select.Option>
+              </Select>
+            </Form.Item>
+          </div>
+          
+          <Form.Item
+            name="remarks"
+            label="备注信息"
+          >
+            <Input.TextArea rows={3} placeholder="请输入备注信息" />
+          </Form.Item>
+        </Form>
+      </Modal>
+
+      <ClientDetailModal
+        clientId={selectedClientId}
+        visible={detailModalVisible}
+        onClose={handleDetailModalClose}
+      />
+    </div>
+  );
+};
+
+export default ClientList;

+ 8 - 0
src/client/admin/pages/clients/PendingClients.tsx

@@ -0,0 +1,8 @@
+import React from 'react';
+import ClientList from './ClientList';
+
+const PendingClients: React.FC = () => {
+  return <ClientList auditStatus={0} pageTitle="待审核客户" />;
+};
+
+export default PendingClients;

+ 8 - 0
src/client/admin/pages/clients/RejectedClients.tsx

@@ -0,0 +1,8 @@
+import React from 'react';
+import ClientList from './ClientList';
+
+const RejectedClients: React.FC = () => {
+  return <ClientList auditStatus={2} pageTitle="已拒绝客户" />;
+};
+
+export default RejectedClients;

+ 18 - 0
src/client/admin/routes.tsx

@@ -8,6 +8,9 @@ import { DashboardPage } from './pages/Dashboard';
 import { UsersPage } from './pages/Users';
 import { UsersPage } from './pages/Users';
 import AreasPage from './pages/Areas';
 import AreasPage from './pages/Areas';
 import ClientsPage from './pages/Clients';
 import ClientsPage from './pages/Clients';
+import PendingClients from './pages/clients/PendingClients';
+import ApprovedClients from './pages/clients/ApprovedClients';
+import RejectedClients from './pages/clients/RejectedClients';
 import ExpensesPage from './pages/Expenses';
 import ExpensesPage from './pages/Expenses';
 import FilesPage from './pages/Files';
 import FilesPage from './pages/Files';
 import ContractsPage from './pages/Contracts';
 import ContractsPage from './pages/Contracts';
@@ -59,6 +62,21 @@ export const router = createBrowserRouter([
         element: <ClientsPage />,
         element: <ClientsPage />,
         errorElement: <ErrorPage />
         errorElement: <ErrorPage />
       },
       },
+      {
+        path: 'clients/pending',
+        element: <PendingClients />,
+        errorElement: <ErrorPage />
+      },
+      {
+        path: 'clients/approved',
+        element: <ApprovedClients />,
+        errorElement: <ErrorPage />
+      },
+      {
+        path: 'clients/rejected',
+        element: <RejectedClients />,
+        errorElement: <ErrorPage />
+      },
       {
       {
         path: 'expenses',
         path: 'expenses',
         element: <ExpensesPage />,
         element: <ExpensesPage />,