StoreDetailDrawer.test.tsx 15.2 KB
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { StoreListingDetail } from '@/api';
import { STORE_DICTIONARIES, type StoreDictionaries } from './dictionaries';
import { StoreDetailDrawer } from './StoreDetailDrawer';

afterEach(cleanup);

// Swagger-shaped fixtures: live endpoints contain no records, so these are not real money samples.
const spec: StoreDictionaries = {
  businessScenes: [
    { value: 'AFTER_SALES', label: '售后会员权益升级' },
    { value: 'PRE_SALES', label: '售前延保' },
  ],
  productCategories: [
    { value: 'FILM', label: '太阳膜-原厂' },
    { value: 'WRAP', label: '车衣-原厂' },
  ],
  calcModes: [{ value: 'CATEGORY', label: '按品类计算' }],
  calcWays: [
    { value: 'INCOME', label: '收入' },
    { value: 'FIXED', label: '固定' },
  ],
  onlinePointFlags: [
    { value: '1', label: '是' },
    { value: '0', label: '否' },
  ],
};

const detail: StoreListingDetail = {
  listingId: '9007199254740993',
  storeName: '当前门店',
  merchantNo: 'SQ001',
  businessScene: 'AFTER_SALES',
  status: 'PENDING',
  currentLevel: 1,
  totalLevel: 2,
  submitUserName: '运营甲',
  submitTime: '2026-10-09T10:00:00',
  costDecoration: '500',
  costMonthly: '500',
  costLabor: '500',
  costTotal: '90071992547409.91',
  items: [
    {
      itemId: '1',
      productCategory: 'FILM',
      marketFee1CalcMode: 'CATEGORY',
      marketFee1CalcWay: 'INCOME',
      marketFee1Value: '5',
      marketFee1Unit: 'RATIO',
      sunshine1OnlinePoint: 0,
      sunshine1Value: '0',
      sunshine1Unit: 'RATIO',
    },
    {
      itemId: '2',
      productCategory: 'WRAP',
      marketFee1CalcMode: 'CATEGORY',
      marketFee1CalcWay: 'FIXED',
      marketFee1Value: '123.45',
      marketFee1Unit: 'AMOUNT',
    },
    ...Array.from({ length: 9 }, (_, index) => ({
      itemId: `extra-${index}`,
      productCategory: `分类${index}`,
    })),
  ],
  approvalLogs: [
    {
      logId: '1',
      action: 'REJECT',
      operatorName: '商务甲',
      operatorRole: 'YJ_BUSINESS_MGR',
      preStatus: 'PENDING',
      postStatus: 'REJECTED',
      reason: '请核对政策',
      operateTime: '2026-10-09T11:00:00',
      operateIp: '192.0.2.1',
    },
  ],
  changeHistory: [
    {
      changeId: 'old',
      versionNo: 1,
      changeField: '运营成本',
      beforeValue: '0',
      afterValue: '100',
      changeUserName: '运营甲',
      effectiveTime: '2026-09-01T10:00:00',
    },
    {
      changeId: 'new',
      versionNo: 2,
      changeField: '管理层市场费',
      beforeValue: '3%',
      afterValue: '5%',
      changeUserName: '运营乙',
      effectiveTime: '2026-10-01T10:00:00',
    },
  ],
};

function show(overrides: Partial<React.ComponentProps<typeof StoreDetailDrawer>> = {}) {
  return render(
    <StoreDetailDrawer
      open
      mode="approval"
      detail={detail}
      spec={spec}
      onClose={() => undefined}
      {...overrides}
    />,
  );
}

describe('store detail presentation', () => {
  it('renders the approval prototype header and audit cards without inventing a single-stage flow', () => {
    show();
    const header = within(screen.getByLabelText('审批概览'));
    expect(header.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
    expect(header.getByText('待审批')).toBeInTheDocument();
    expect(header.getByText('90,071,992,547,409.91 元')).toBeInTheDocument();
    const flow = within(screen.getByLabelText('审批流程'));
    expect(flow.getByText('两级审批')).toBeInTheDocument();
    expect(flow.getByText('优加商务经理')).toBeInTheDocument();
    expect(flow.getByText('优加财务经理')).toBeInTheDocument();
    fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
    const trail = within(screen.getByLabelText('审批留痕列表'));
    expect(trail.getByText(/商务甲/)).toBeInTheDocument();
    expect(trail.getByText('请核对政策')).toBeInTheDocument();
    expect(trail.getByText(/192\.0\.2\.1/)).toBeInTheDocument();
  });

  it('renders the listing prototype overview and store information using real record fields', () => {
    const onClose = vi.fn();
    show({
      mode: 'listing',
      onClose,
      detail: {
        ...detail,
        status: 'APPROVED',
        categoryCount: 6,
        effectiveTime: '2026-10-09T15:03:37',
        changeHistory: [
          { versionNo: 3, effectiveTime: '2026-10-01T10:00:00' },
          { versionNo: 1, effectiveTime: '2026-10-09T10:00:00' },
        ],
      },
    });
    const overview = within(screen.getByLabelText('门店概览'));
    expect(overview.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
    for (const text of ['SQ001', '1 个', '6 个', '2026-10-09', 'v3', '已生效']) {
      expect(overview.getByText(text)).toBeInTheDocument();
    }
    expect(overview.queryByText('提交人')).not.toBeInTheDocument();
    expect(overview.queryByText('运营成本合计')).not.toBeInTheDocument();
    const panel = within(screen.getByRole('tabpanel', { name: '门店信息' }));
    expect(panel.queryByRole('table')).not.toBeInTheDocument();
    expect(panel.getByRole('heading', { name: '门店信息' })).toBeInTheDocument();
    expect(panel.getByText('售后会员权益升级')).toBeInTheDocument();
    expect(panel.queryByText('售前延保')).not.toBeInTheDocument();
    expect(panel.getByText('完整清单见「产品与场景」页签')).toBeInTheDocument();
    expect(panel.getByText('2026-10-09 15:03')).toBeInTheDocument();
    fireEvent.click(overview.getByRole('button', { name: '关闭' }));
    expect(onClose).toHaveBeenCalledOnce();
  });

  it('does not invent a version or scene count when listing fields are missing', () => {
    show({
      mode: 'listing',
      detail: {
        ...detail,
        businessScene: '',
        items: undefined,
        categoryCount: undefined,
        changeHistory: [{ changeField: 'status' }],
      },
    });
    const overview = within(screen.getByLabelText('门店概览'));
    expect(overview.getByText('当前版本')).toBeInTheDocument();
    expect(overview.queryByText(/^v\d/)).not.toBeInTheDocument();
    expect(overview.queryByText('1 个')).not.toBeInTheDocument();
    expect(overview.queryByText('0 个')).not.toBeInTheDocument();
  });

  it('uses local dictionaries for real Chinese policy values and numeric point flags', () => {
    show({
      spec: STORE_DICTIONARIES,
      detail: {
        ...detail,
        businessScene: '精品升级',
        items: [
          {
            productCategory: '车辆美容',
            sunshine1CalcMode: '按品类计算',
            sunshine1CalcWay: '收入',
            sunshine1OnlinePoint: 1,
            sunshine2CalcMode: '按整单计算',
            sunshine2CalcWay: '毛利',
            sunshine2OnlinePoint: 0,
          },
          { productCategory: '后续新增分类' },
        ],
      },
    });
    expect(screen.getByText('精品升级')).toBeInTheDocument();
    fireEvent.click(screen.getByRole('tab', { name: '一线阳光激励' }));
    const panel = within(screen.getByRole('tabpanel', { name: '一线阳光激励' }));
    for (const label of [
      '车辆美容',
      '后续新增分类',
      '按品类计算',
      '按整单计算',
      '收入',
      '毛利',
      '是',
      '否',
    ]) {
      expect(panel.getByText(label)).toBeInTheDocument();
    }
  });

  it('shows only the current scene, every category and the policy value unit', () => {
    show();
    expect(screen.getByText('当前门店')).toBeInTheDocument();
    expect(screen.getByText('售后会员权益升级')).toBeInTheDocument();
    expect(screen.queryByText('售前延保')).not.toBeInTheDocument();
    expect(screen.getByText('分类8')).toBeInTheDocument();
    expect(screen.getByText('5%')).toBeInTheDocument();
    expect(screen.getByText('¥123.45')).toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument();
  });

  it.each(['approval', 'listing'] as const)(
    'displays the authoritative %s total even when the cost components differ',
    (mode) => {
      show({ mode });
      fireEvent.click(screen.getByRole('tab', { name: '运营成本' }));
      const panel = within(screen.getByRole('tabpanel', { name: '运营成本' }));
      const currency = mode === 'listing' ? '¥' : '';
      expect(panel.getByText(`${currency}90,071,992,547,409.91`)).toBeInTheDocument();
      expect(panel.queryByText(`${currency}1,500.00`)).not.toBeInTheDocument();
      expect(panel.getAllByText(`${currency}500.00`)).toHaveLength(3);
      if (mode === 'listing') {
        expect(panel.getByRole('heading', { name: '运营成本(门店维度)' })).toBeInTheDocument();
        expect(panel.queryByRole('table')).not.toBeInTheDocument();
        expect(panel.getByText('当月产生费用')).toBeInTheDocument();
        expect(panel.getByText('房租、水电、耗材等')).toBeInTheDocument();
      }
    },
  );

  it('renders zero point flags and zero policy values without treating them as missing', () => {
    show();
    fireEvent.click(screen.getByRole('tab', { name: '一线阳光激励' }));
    expect(screen.getByText('否')).toBeInTheDocument();
    expect(screen.getByText('0%')).toBeInTheDocument();
  });

  it('shows two approval stages by default and the returned single finance stage', () => {
    const view = show({ detail: { ...detail, totalLevel: undefined } });
    expect(within(screen.getByLabelText('审批流程')).getByText('优加商务经理')).toBeInTheDocument();
    view.rerender(
      <StoreDetailDrawer
        open
        mode="approval"
        detail={{ ...detail, totalLevel: 1 }}
        onClose={() => undefined}
      />,
    );
    const flow = within(screen.getByLabelText('审批流程'));
    expect(flow.queryByText('优加商务经理')).not.toBeInTheDocument();
    expect(flow.getByText('优加财务经理')).toBeInTheDocument();
  });

  it('does not describe a rejected record as awaiting approval and preserves the audit reason', () => {
    show({ detail: { ...detail, status: 'REJECTED', rejectReason: '请核对政策' } });
    expect(
      within(screen.getByLabelText('审批流程')).queryByText('当前审批节点'),
    ).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
    expect(screen.getByText('商务甲')).toBeInTheDocument();
    expect(screen.getAllByText('请核对政策').length).toBeGreaterThan(0);
    expect(screen.getByText(/192\.0\.2\.1/)).toBeInTheDocument();
  });

  it('opens listing history directly and shows newest changes first', () => {
    show({ mode: 'listing', initialTab: 'history', detail: { ...detail, status: 'APPROVED' } });
    expect(screen.getByRole('tab', { name: '变更历史' })).toHaveAttribute('aria-selected', 'true');
    const panel = screen.getByRole('tabpanel');
    expect(panel.textContent?.indexOf('管理层市场费')).toBeLessThan(
      panel.textContent?.indexOf('运营成本') ?? -1,
    );
    expect(within(panel).getByText('3% → 5%')).toBeInTheDocument();
    expect(screen.queryByRole('tab', { name: '审批留痕' })).not.toBeInTheDocument();
  });

  it('renders the real first-launch history in the prototype layout with readable status values', () => {
    show({
      mode: 'listing',
      initialTab: 'history',
      detail: {
        ...detail,
        status: 'APPROVED',
        changeHistory: [
          {
            changeId: 9,
            listingId: 1,
            versionNo: 1,
            changeField: 'status',
            beforeValue: 'PENDING',
            afterValue: 'APPROVED',
            changeUserName: '优加财务',
            effectiveTime: '2026-10-09T15:03:37',
          },
        ],
      },
    });
    const panel = within(screen.getByRole('tabpanel', { name: '变更历史' }));
    expect(panel.getByRole('heading', { name: '变更历史(只读)' })).toBeInTheDocument();
    expect(panel.getByText('首次上架')).toBeInTheDocument();
    expect(panel.getByText('门店在系统中完成首次上架并生效。')).toBeInTheDocument();
    expect(panel.getByText('待审批 → 已生效')).toBeInTheDocument();
    expect(panel.getByText('2026-10-09')).toBeInTheDocument();
    expect(panel.getByText(/变更人:.*优加财务.*生效时间.*2026-10-09 15:03/)).toBeInTheDocument();
    expect(panel.queryByText(/PENDING|APPROVED/)).not.toBeInTheDocument();
  });

  it('groups history by version and preserves cost values, zero values and policy units', () => {
    show({
      mode: 'listing',
      initialTab: 'history',
      detail: {
        ...detail,
        changeHistory: [
          {
            versionNo: 2,
            changeField: 'businessScene',
            beforeValue: 'AFTER_SALES',
            afterValue: 'PRE_SALES',
          },
          { versionNo: 3, changeField: 'costDecoration', beforeValue: '800', afterValue: '500' },
          { versionNo: 3, changeField: 'costLabor', beforeValue: null, afterValue: '0' },
          { versionNo: 3, changeField: 'sunshine1Value', beforeValue: '3%', afterValue: '5%' },
        ],
      },
    });
    const panel = within(screen.getByRole('tabpanel', { name: '变更历史' }));
    const versions = panel.getAllByRole('article');
    expect(versions).toHaveLength(2);
    expect(within(versions[0]).getByText('v3')).toBeInTheDocument();
    expect(within(versions[0]).getByText('¥800.00 → ¥500.00')).toBeInTheDocument();
    expect(within(versions[0]).getByText('— → ¥0.00')).toBeInTheDocument();
    expect(within(versions[0]).getByText('3% → 5%')).toBeInTheDocument();
    expect(within(versions[1]).getByText('v2')).toBeInTheDocument();
    expect(within(versions[1]).getByText('售后会员权益升级 → 售前延保')).toBeInTheDocument();
  });

  it('renders the batch-pass audit action as a readable business action', () => {
    show({ detail: { ...detail, approvalLogs: [{ logId: 'batch', action: 'BATCH_PASS' }] } });
    fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
    expect(screen.getByText('批量通过')).toBeInTheDocument();
    expect(screen.queryByText('BATCH_PASS')).not.toBeInTheDocument();
  });

  it.each(['approval', 'listing'] as const)(
    'uses approveTime for the %s effective date when effectiveTime is absent',
    (mode) => {
      show({ mode, detail: { ...detail, status: 'APPROVED', approveTime: '2026-10-09T12:30:45' } });
      expect(
        screen.getByText(mode === 'listing' ? '2026-10-09 12:30' : '2026-10-09 12:30:45'),
      ).toBeInTheDocument();
    },
  );

  it('keeps effectiveTime authoritative when both timestamp fields are present', () => {
    show({
      mode: 'listing',
      detail: {
        ...detail,
        status: 'APPROVED',
        effectiveTime: '2026-10-09T12:45:00',
        approveTime: '2026-10-09T12:30:45',
      },
    });
    expect(screen.getByText('2026-10-09 12:45')).toBeInTheDocument();
    expect(screen.queryByText('2026-10-09 12:30:45')).not.toBeInTheDocument();
  });

  it('replaces stale detail with a retryable error', () => {
    const retry = vi.fn();
    show({ error: new Error('请求失败'), onRetry: retry });
    expect(screen.queryByText('太阳膜-原厂')).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole('button', { name: /重\s*试/ }));
    expect(retry).toHaveBeenCalledOnce();
  });
});