StoreApprove.test.tsx 17.7 KB
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { App, ConfigProvider } from 'antd';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AccessProvider, saveUserInfo } from '@/access';
import type { ApprovalRow } from '@/api';
import StoreApprove from '../index';

const api = vi.hoisted(() => ({
  listApprovals: vi.fn(),
  getApproval: vi.fn(),
  passApproval: vi.fn(),
  rejectApproval: vi.fn(),
  batchPassApproval: vi.fn(),
  revokeApproval: vi.fn(),
}));
vi.mock('@/api', () => ({ store: api }));

const row = {
  listingId: '101',
  storeName: '测试门店',
  merchantNo: 'SQ001',
  businessScene: '售后众筹',
  productCategories: ['太阳膜-原厂'],
  categoryCount: 1,
  costTotal: '1500.00',
  status: 'PENDING',
  statusLabel: '待审批',
  actionable: true,
  submitUserName: '张三',
  submitTime: '2026-10-08T10:00:00',
  pendingHours: 25,
  currentLevel: 1,
  totalLevel: 2,
};
let pending: ApprovalRow[] = [row];
let mine = [
  { ...row, listingId: '202', status: 'REJECTED', statusLabel: '已打回', actionable: false },
];
let detail = {
  ...row,
  costDecoration: '1.00',
  costMonthly: '2.00',
  costLabor: '3.00',
  items: [{ productCategory: '太阳膜-原厂', marketFee1Value: '5', marketFee1Unit: 'RATIO' }],
  approvalLogs: [],
  changeHistory: [],
};

beforeEach(() => {
  vi.resetAllMocks();
  pending = [{ ...row }];
  mine = [
    { ...row, listingId: '202', status: 'REJECTED', statusLabel: '已打回', actionable: false },
  ];
  detail = { ...detail, ...row };
  api.getApproval.mockImplementation(async () => ({ ...detail }));
  api.listApprovals.mockImplementation(
    async (tab: string, params: { current: number; size: number; keyword?: string }) => {
      const records =
        tab === 'todo' ? (params.keyword === '不存在' ? [] : pending) : tab === 'mine' ? mine : [];
      return {
        records: records.slice((params.current - 1) * params.size, params.current * params.size),
        total: records.length,
        current: params.current,
        size: params.size,
        pages: Math.ceil(records.length / params.size),
      };
    },
  );
  saveUserInfo({ permCodes: ['store:approve:view', 'store:approve:pass', 'store:approve:reject'] });
});

function mount() {
  const client = new QueryClient({
    defaultOptions: { queries: { retry: false, staleTime: 30_000 }, mutations: { retry: false } },
  });
  return {
    client,
    ...render(
      <ConfigProvider button={{ autoInsertSpace: false }}>
        <App>
          <QueryClientProvider client={client}>
            <AccessProvider>
              <StoreApprove />
            </AccessProvider>
          </QueryClientProvider>
        </App>
      </ConfigProvider>,
    ),
  };
}

// rc-util 在 test 环境把所有 aria-labelledby ID 固定为 test-id;以弹窗内确认按钮定位。
function actionDialog(confirmLabel: string) {
  const dialog = screen
    .getAllByRole('dialog')
    .find((element) => within(element).queryByRole('button', { name: confirmLabel }));
  if (!dialog) throw new Error(`未找到确认弹窗:${confirmLabel}`);
  return dialog;
}

describe('门店审批页面', () => {
  it('按原型展示分类摘要、无币种前缀的权威成本、提交时间和停留时长', async () => {
    pending = [
      {
        ...row,
        categoryCount: 6,
        productCategories: ['太阳膜-原厂', '车衣-原厂'],
        costTotal: '90071992547409.91',
        submitTime: '2026-10-09T15:03:37',
        pendingHours: 49,
      },
    ];
    mount();
    await screen.findByText('测试门店');
    expect(screen.getByRole('columnheader', { name: '提交人 / 时间' })).toBeInTheDocument();
    expect(screen.getByText('等 6 个分类')).toBeInTheDocument();
    expect(screen.queryByText('车衣-原厂')).not.toBeInTheDocument();
    expect(screen.getByText('90,071,992,547,409.91')).toBeInTheDocument();
    expect(screen.getByText('10-09 15:03')).toBeInTheDocument();
    expect(screen.getByText('49 小时')).toBeInTheDocument();
  });

  it('使用本地字典按实际中文业务场景和产品分类筛选', async () => {
    mount();
    await screen.findByText('测试门店');
    fireEvent.mouseDown(screen.getByLabelText('业务场景'));
    fireEvent.click(
      await screen.findByText('精品升级', { selector: '.ant-select-item-option-content' }),
    );
    fireEvent.mouseDown(screen.getByLabelText('产品分类'));
    fireEvent.click(
      await screen.findByText('车辆美容', { selector: '.ant-select-item-option-content' }),
    );
    fireEvent.click(screen.getByRole('button', { name: '查询' }));
    await waitFor(() =>
      expect(api.listApprovals).toHaveBeenCalledWith(
        'todo',
        expect.objectContaining({ businessScene: '精品升级', productCategory: '车辆美容' }),
      ),
    );
    expect(screen.queryByText('筛选字典加载失败')).not.toBeInTheDocument();
  });

  it('请求真实待办、展示权威金额,查询和重置作用于服务端', async () => {
    mount();
    expect(await screen.findByText('测试门店')).toBeInTheDocument();
    expect(screen.getByText('1,500')).toBeInTheDocument();
    fireEvent.change(screen.getByLabelText('门店名称 / 商户号'), { target: { value: '不存在' } });
    fireEvent.click(screen.getByRole('button', { name: '查询' }));
    await waitFor(() =>
      expect(api.listApprovals).toHaveBeenCalledWith(
        'todo',
        expect.objectContaining({ keyword: '不存在', current: 1 }),
      ),
    );
    await waitFor(() => expect(screen.queryByText('测试门店')).not.toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: '重置' }));
    expect(await screen.findByText('测试门店')).toBeInTheDocument();
    expect(screen.getByLabelText('门店名称 / 商户号')).toHaveValue('');
  });

  it('商务通过需确认范围,调用正确记录并读取下一节点而非前端直接生效', async () => {
    api.passApproval.mockImplementation(async () => {
      pending = [];
      detail = { ...detail, currentLevel: 2 };
    });
    mount();
    fireEvent.click(await screen.findByRole('button', { name: '审核' }));
    await screen.findByText('优加商务经理');
    fireEvent.click(screen.getByRole('button', { name: '通过' }));
    const modal = actionDialog('确认通过');
    expect(within(modal).getByRole('button', { name: '确认通过' })).toBeDisabled();
    fireEvent.click(within(modal).getByRole('checkbox'));
    fireEvent.click(within(modal).getByRole('button', { name: '确认通过' }));
    await waitFor(() => expect(api.passApproval).toHaveBeenCalledWith('101'));
    await waitFor(() => expect(api.getApproval.mock.calls.length).toBeGreaterThan(1));
    expect(screen.queryByText('门店已生效')).not.toBeInTheDocument();
    fireEvent.click(await screen.findByRole('tab', { name: '审批留痕' }));
    expect(await screen.findByText(/优加财务经理 · 第 2 级审批节点/)).toBeInTheDocument();
    expect(screen.queryByText(/已停留25小时/)).not.toBeInTheDocument();
  });

  it('打回拒绝空白原因,失败保留原因和弹窗', async () => {
    api.rejectApproval.mockRejectedValue(new Error('记录已被其他人处理'));
    mount();
    fireEvent.click(await screen.findByRole('button', { name: '审核' }));
    fireEvent.click(await screen.findByRole('button', { name: '打回' }));
    const modal = actionDialog('确认打回');
    const input = within(modal).getByLabelText('打回原因');
    fireEvent.change(input, { target: { value: '   ' } });
    fireEvent.click(within(modal).getByRole('button', { name: '确认打回' }));
    expect(api.rejectApproval).not.toHaveBeenCalled();
    fireEvent.change(input, { target: { value: '政策不合理' } });
    fireEvent.click(within(modal).getByRole('button', { name: '确认打回' }));
    await waitFor(() => expect(api.rejectApproval).toHaveBeenCalledWith('101', '政策不合理'));
    expect(await screen.findByText('记录已被其他人处理')).toBeInTheDocument();
    expect(within(modal).getByLabelText('打回原因')).toHaveValue('政策不合理');
  });

  it.each([
    { status: 'REJECTED', statusLabel: '已打回' },
    { status: 'REVOKED', statusLabel: '已撤回' },
  ])('我发起的 $status 记录仅可查看,无重新提交入口', async ({ status, statusLabel }) => {
    mine = [{ ...row, listingId: '202', status, statusLabel, actionable: false }];
    detail = { ...detail, ...mine[0] };
    mount();
    await screen.findByText('测试门店');
    fireEvent.click(screen.getByRole('tab', { name: /我发起的/ }));
    expect(await screen.findByText(statusLabel)).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '重新提交' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '撤回' })).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: '查看' }));
    await screen.findByText('优加商务经理');
    expect(screen.queryByRole('button', { name: '重新提交' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '打回' })).not.toBeInTheDocument();
  });

  it('选中记录只调用一次批量接口', async () => {
    api.batchPassApproval.mockResolvedValue(undefined);
    mount();
    await screen.findByText('测试门店');
    expect(screen.getByRole('button', { name: '批量审批' })).toBeDisabled();
    fireEvent.click(screen.getAllByRole('checkbox')[1]);
    fireEvent.click(screen.getByRole('button', { name: '批量审批' }));
    const modal = actionDialog('确认批量通过');
    fireEvent.click(within(modal).getByRole('checkbox'));
    fireEvent.click(within(modal).getByRole('button', { name: '确认批量通过' }));
    await waitFor(() => expect(api.batchPassApproval).toHaveBeenCalledWith(['101']));
    expect(api.batchPassApproval).toHaveBeenCalledTimes(1);
    expect(api.passApproval).not.toHaveBeenCalled();
  });

  it('全选只提交可审核记录,请求期间冻结选择,成功后清空仍在列表中的勾选', async () => {
    pending = [
      row,
      { ...row, listingId: '102', storeName: '可审核乙' },
      { ...row, listingId: '103', storeName: '不可审核', actionable: false },
      { ...row, listingId: '104', storeName: '未授权', actionable: undefined },
      { ...row, listingId: '105', storeName: '已处理', status: 'APPROVED' },
    ];
    let complete!: () => void;
    api.batchPassApproval.mockImplementation(
      () =>
        new Promise<void>((resolve) => {
          complete = resolve;
        }),
    );
    mount();
    await screen.findByText('可审核乙');
    const table = screen.getByRole('table');
    fireEvent.click(within(table).getByRole('checkbox', { name: 'Select all' }));
    for (const name of ['不可审核', '未授权', '已处理']) {
      const checkbox = within(screen.getByRole('row', { name: new RegExp(name) })).getByRole(
        'checkbox',
      );
      expect(checkbox).toBeDisabled();
      expect(checkbox).not.toBeChecked();
    }
    fireEvent.click(screen.getByRole('button', { name: '批量审批' }));
    const modal = actionDialog('确认批量通过');
    expect(within(modal).queryByText('不可审核')).not.toBeInTheDocument();
    fireEvent.click(within(modal).getByRole('checkbox'));
    const confirm = within(modal).getByRole('button', { name: '确认批量通过' });
    fireEvent.click(confirm);
    fireEvent.click(confirm);
    await waitFor(() => expect(api.batchPassApproval).toHaveBeenCalledWith(['101', '102']));
    for (const checkbox of within(table).getAllByRole('checkbox', { hidden: true })) {
      expect(checkbox).toBeDisabled();
    }
    expect(api.batchPassApproval).toHaveBeenCalledTimes(1);
    complete();
    await waitFor(() => expect(screen.getByRole('button', { name: '批量审批' })).toBeDisabled());
    await waitFor(() => expect(screen.getByText(/已选 0 条/)).toBeInTheDocument());
    expect(within(table).getByText('可审核乙')).toBeInTheDocument();
    expect(
      within(screen.getByRole('table')).getByRole('checkbox', { name: 'Select all' }),
    ).not.toBeChecked();
  });

  it.each(['查询', '重置'])('%s后清空选择,不能沿用之前的批量操作范围', async (action) => {
    mount();
    await screen.findByText('测试门店');
    fireEvent.click(screen.getAllByRole('checkbox')[1]);
    expect(screen.getByRole('button', { name: '批量审批' })).toBeEnabled();
    fireEvent.click(screen.getByRole('button', { name: action }));
    await waitFor(() => expect(screen.getByText(/已选 0 条/)).toBeInTheDocument());
    expect(screen.getAllByRole('checkbox')[1]).not.toBeChecked();
    expect(screen.getByRole('button', { name: '批量审批' })).toBeDisabled();
  });

  it('翻页和切换页签后不保留之前的选择', async () => {
    pending = Array.from({ length: 11 }, (_, index) => ({
      ...row,
      listingId: String(index + 1),
      storeName: `门店${index + 1}`,
    }));
    mount();
    await screen.findByText('门店1');
    fireEvent.click(screen.getAllByRole('checkbox')[1]);
    fireEvent.click(screen.getByTitle('2'));
    await screen.findByText('门店11');
    expect(screen.getByText(/已选 0 条/)).toBeInTheDocument();
    expect(screen.getAllByRole('checkbox')[1]).not.toBeChecked();
    fireEvent.click(screen.getAllByRole('checkbox')[1]);
    fireEvent.click(screen.getByRole('tab', { name: /我已办/ }));
    expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('tab', { name: /待我审批/ }));
    await screen.findByText('门店1');
    expect(screen.getByText(/已选 0 条/)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: '批量审批' })).toBeDisabled();
  });

  it('仅打回权限保留审核入口,但不显示多选与批量审批', async () => {
    saveUserInfo({ permCodes: ['store:approve:view', 'store:approve:reject'] });
    mount();
    await screen.findByText('测试门店');
    expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument();
    expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '批量审批' })).not.toBeInTheDocument();
  });

  it('无审批查看权限时不加载业务数据', async () => {
    saveUserInfo({ permCodes: [] });
    mount();
    expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument();
    expect(api.listApprovals).not.toHaveBeenCalled();
  });

  it('重复查询同一条件仍刷新服务端', async () => {
    mount();
    await screen.findByText('测试门店');
    fireEvent.click(screen.getByRole('button', { name: '查询' }));
    await waitFor(() =>
      expect(api.listApprovals.mock.calls.filter(([tab]) => tab === 'todo')).toHaveLength(2),
    );
    fireEvent.click(screen.getByRole('button', { name: '查询' }));
    await waitFor(() =>
      expect(api.listApprovals.mock.calls.filter(([tab]) => tab === 'todo')).toHaveLength(3),
    );
  });

  it('刷新后已处理的选中记录不再可批量审批', async () => {
    const { client } = mount();
    await screen.findByText('测试门店');
    fireEvent.click(screen.getAllByRole('checkbox')[1]);
    expect(screen.getByRole('button', { name: '批量审批' })).toBeEnabled();
    pending = [{ ...row, actionable: false }];
    await client.invalidateQueries({ queryKey: ['store', 'approvals'] });
    await waitFor(() => expect(screen.getByRole('button', { name: '批量审批' })).toBeDisabled());
    expect(api.batchPassApproval).not.toHaveBeenCalled();
  });

  it('只读查看无通过或打回入口,非本人列表无撤回入口', async () => {
    mount();
    fireEvent.click(await screen.findByRole('button', { name: '查看' }));
    await screen.findByText('优加商务经理');
    expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '打回' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '撤回' })).not.toBeInTheDocument();
  });

  it('本人待办撤回需确认并刷新状态与操作区', async () => {
    mine = [
      { ...row, listingId: '202', status: 'PENDING', statusLabel: '待审批', actionable: false },
    ];
    api.revokeApproval.mockImplementation(async () => {
      mine = [{ ...mine[0], status: 'REVOKED', statusLabel: '已撤回' }];
    });
    mount();
    await screen.findByText('测试门店');
    fireEvent.click(screen.getByRole('tab', { name: /我发起的/ }));
    fireEvent.click(await screen.findByRole('button', { name: '撤回' }));
    expect(api.revokeApproval).not.toHaveBeenCalled();
    const modal = actionDialog('确认撤回');
    expect(within(modal).getByText(/SQ001/)).toBeInTheDocument();
    fireEvent.click(within(modal).getByRole('button', { name: '确认撤回' }));
    await waitFor(() => expect(api.revokeApproval).toHaveBeenCalledWith('202'));
    expect(await screen.findByRole('cell', { name: '已撤回' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '重新提交' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '撤回' })).not.toBeInTheDocument();
  });

  it('没有处置权限只显示查看,不渲染批量入口和选择框', async () => {
    saveUserInfo({ permCodes: ['store:approve:view'] });
    mount();
    await screen.findByText('测试门店');
    expect(screen.getByRole('button', { name: '查看' })).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '审核' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '批量审批' })).not.toBeInTheDocument();
    expect(screen.queryByRole('checkbox')).not.toBeInTheDocument();
  });
});