store.test.ts 12.3 KB
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { http } from '../../core/http';
import { setToken } from '../../core/token';
import * as signing from '../../core/sign';
import { store } from '../store';

// 业务路径契约独立于本机 .env 的部署前缀;公共 /youjia 前缀由 HTTP 层统一添加。
vi.mock('../../core/config', async (importOriginal) => ({
  ...(await importOriginal<typeof import('../../core/config')>()),
  API_CONTEXT_PATH: '',
}));

const originalAdapter = http.defaults.adapter;
const approvalRecord = {
  listingId: '9007199254740993',
  storeName: '测试门店',
  merchantNo: 'M-001',
  productCategories: ['FILM_ORIGINAL'],
  categoryCount: 1,
  businessScene: 'AFTER_SALE_MEMBER',
  costTotal: '90071992547409.91',
  currentLevel: 1,
  totalLevel: 2,
  submitUserName: '运营人员',
  submitTime: '2026-10-09T09:00:00',
  pendingHours: 1,
  timeoutLevel: 'NORMAL',
  status: 'PENDING',
  statusLabel: '待审批',
  rejectReason: null,
  myAction: null,
  myActionLabel: null,
  handleTime: null,
  handleOpinion: null,
  actionable: true,
};
const page = { records: [approvalRecord], total: 41, current: 2, size: 20, pages: 3 };

function serve(
  handler: (config: InternalAxiosRequestConfig) => {
    data: unknown;
    headers?: Record<string, string>;
  },
) {
  const adapter: AxiosAdapter = async (config) => {
    const result = handler(config);
    return {
      config,
      data: result.data,
      headers: result.headers ?? { 'content-type': 'application/json' },
      status: 200,
      statusText: 'OK',
    };
  };
  http.defaults.adapter = adapter;
}

function result(data: unknown) {
  return JSON.stringify({
    code: 200,
    message: '操作成功',
    data,
    timestamp: 1791514515716,
    success: true,
  });
}

beforeEach(() => {
  localStorage.clear();
  vi.spyOn(console, 'log').mockImplementation(() => undefined);
});

afterEach(() => {
  http.defaults.adapter = originalAdapter;
  vi.restoreAllMocks();
  vi.unstubAllGlobals();
  vi.useRealTimers();
});

describe('store API contract', () => {
  it('loads scene options with flat paging and search parameters and preserves scene names', async () => {
    serve((config) => {
      expect(config.method).toBe('get');
      expect(config.url).toBe('/store/category/scenes');
      expect(config.params).toEqual({ current: 2, size: 20, name: '售后', status: 1 });
      return {
        data: result([
          { id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
          { id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
        ]),
      };
    });

    expect(await store.listScenes({ current: 2, size: 20, name: '售后', status: 1 })).toEqual([
      { id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
      { id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
    ]);
  });

  it('loads only the requested goods category page and preserves its category hierarchy', async () => {
    let requestCount = 0;
    serve((config) => {
      requestCount += 1;
      expect(config.method).toBe('get');
      expect(config.url).toBe('/store/category/goods/page');
      expect(config.params).toEqual({ current: 3, size: 20, categoryName: '太阳膜' });
      return {
        data: result({
          records: [
            {
              id: 51,
              categoryType: 6,
              categoryName: '太阳膜',
              children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
            },
          ],
          current: 3,
          size: 20,
          total: 81,
          pages: 5,
        }),
      };
    });

    expect(
      await store.listGoodsCategories({ current: 3, size: 20, categoryName: '太阳膜' }),
    ).toEqual({
      records: [
        {
          id: 51,
          categoryType: 6,
          categoryName: '太阳膜',
          children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
        },
      ],
      current: 3,
      size: 20,
      total: 81,
      pages: 5,
    });
    expect(requestCount).toBe(1);
  });

  it.each([
    ['todo', '/store/approval/pending'],
    ['done', '/store/approval/done'],
    ['mine', '/store/approval/mine'],
  ] as const)('loads %s with server pagination and untouched monetary values', async (tab, url) => {
    serve((config) => {
      expect(config.method).toBe('get');
      expect(config.url).toBe(url);
      expect(config.params).toEqual({ current: 2, size: 20, keyword: 'M-001' });
      return { data: result(page) };
    });
    expect(await store.listApprovals(tab, { current: 2, size: 20, keyword: 'M-001' })).toEqual(
      page,
    );
  });

  it('defaults approvals to the pending endpoint', async () => {
    serve((config) => {
      expect(config.url).toBe('/store/approval/pending');
      return { data: result({ records: [], total: 0, current: 1, size: 20, pages: 0 }) };
    });
    expect((await store.listApprovals()).records).toEqual([]);
  });

  it('forwards listing filters and server sort keys without adding status or region', async () => {
    const params = {
      current: 3,
      size: 10,
      storeName: '门店',
      merchantNo: 'M',
      businessScene: 'AFTER_SALE_MEMBER',
      startDate: '2026-10-01',
      endDate: '2026-10-09',
      sortField: 'effectiveDate' as const,
      sortOrder: 'desc' as const,
    };
    serve((config) => {
      expect(config.url).toBe('/store/listing/page');
      expect(config.params).toEqual(params);
      return { data: result({ records: [], total: 0, current: 3, size: 10, pages: 0 }) };
    });
    expect((await store.listStores(params)).current).toBe(3);
  });

  it('uses listing IDs for detail and history and unwraps column responses', async () => {
    const responses: Record<string, unknown> = {
      '/store/approval/9007199254740993': {
        ...approvalRecord,
        items: [],
        approvalLogs: [],
        changeHistory: [],
      },
      '/store/listing/9007199254740993': {
        ...approvalRecord,
        items: [],
        approvalLogs: [],
        changeHistory: [],
      },
      '/store/listing/9007199254740993/changes': [
        { changeId: 4, beforeValue: '0', afterValue: '5' },
      ],
      '/store/listing/column-config': { columns: ['storeName', 'businessScene'] },
    };
    serve((config) => {
      expect(config.method).toBe('get');
      expect(responses).toHaveProperty(config.url!);
      return { data: result(responses[config.url!]) };
    });
    expect((await store.getApproval('9007199254740993')).listingId).toBe('9007199254740993');
    expect((await store.getStore('9007199254740993')).costTotal).toBe('90071992547409.91');
    expect(await store.getChanges('9007199254740993')).toEqual([
      { changeId: '4', beforeValue: '0', afterValue: '5' },
    ]);
    expect(await store.getColumnConfig()).toEqual({ columns: ['storeName', 'businessScene'] });
  });

  it('sends exact approval action bodies and revokes the record without a body', async () => {
    const requests: { url: string; data: unknown }[] = [];
    serve((config) => {
      expect(config.method).toBe('post');
      requests.push({ url: config.url!, data: config.data ? JSON.parse(config.data) : undefined });
      return { data: result(null) };
    });
    await store.passApproval('9007199254740993');
    await store.rejectApproval(21, '政策有误');
    await store.batchPassApproval([21, 22]);
    await store.revokeApproval(21);
    await store.saveColumnConfig(['merchantNo', 'storeName']);
    expect(requests).toEqual([
      { url: '/store/approval/pass', data: { listingId: '9007199254740993' } },
      { url: '/store/approval/reject', data: { listingId: 21, reason: '政策有误' } },
      { url: '/store/approval/batch-pass', data: { listingIds: [21, 22] } },
      { url: '/store/approval/21/revoke', data: undefined },
      { url: '/store/listing/column-config', data: { columns: ['merchantNo', 'storeName'] } },
    ]);
  });

  it('does not submit an empty batch and exposes backend business failures', async () => {
    let calls = 0;
    serve(() => {
      calls += 1;
      return { data: JSON.stringify({ code: 10003, message: '无审批权限', data: null }) };
    });
    await expect(store.batchPassApproval([])).rejects.toThrow();
    expect(calls).toBe(0);
    await expect(store.passApproval(21)).rejects.toMatchObject({
      message: '无审批权限',
      code: 10003,
    });
  });

  it.each([undefined, '补充门店上架资料'])(
    'uploads the file and optional remark (%s), then submits listing IDs',
    async (remark) => {
      const file = new File(['example'], 'import.xlsx');
      const payload = { listingIds: [1001, 1002] };
      const checked = { ...payload, submitted: false };
      const submitted = { ...payload, submitted: true };
      serve((config) => {
        if (config.url === '/store/import/check') {
          expect(config.method).toBe('post');
          expect(config.data).toBeInstanceOf(FormData);
          expect(config.data.get('file')).toBe(file);
          expect(config.data.get('remark')).toBe(remark ?? null);
          expect([...config.data.keys()]).toEqual(
            remark === undefined ? ['file'] : ['file', 'remark'],
          );
          return { data: result(checked) };
        }
        expect(config.url).toBe('/store/import/submit');
        expect(JSON.parse(config.data)).toEqual(payload);
        return { data: result(submitted) };
      });
      expect(await store.uploadImport({ file, remark })).toEqual(checked);
      expect(await store.submitImport(payload)).toEqual(submitted);
    },
  );
});

describe('direct store export', () => {
  function watchDownloads() {
    const createObjectURL = vi.fn((_blob: Blob) => 'blob:store-export');
    const revokeObjectURL = vi.fn();
    vi.stubGlobal(
      'URL',
      class extends URL {
        static createObjectURL = createObjectURL;
        static revokeObjectURL = revokeObjectURL;
      },
    );
    const downloads: { filename: string; href: string }[] = [];
    vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
      this: HTMLAnchorElement,
    ) {
      downloads.push({ filename: this.download, href: this.href });
    });
    return { downloads, createObjectURL, revokeObjectURL };
  }

  it('downloads with the current token, filters and UTF-8 filename even when signing is unavailable', async () => {
    vi.useFakeTimers();
    vi.spyOn(signing, 'isSignReady').mockReturnValue(false);
    setToken('test-token');
    const watched = watchDownloads();
    serve((config) => {
      expect(config.url).toBe('/store/listing/export');
      expect(config.responseType).toBe('arraybuffer');
      expect(config.headers.get('Authorization')).toBe('Bearer test-token');
      expect(config.headers.get('X-Sign')).toBeUndefined();
      expect(config.params).toEqual({
        businessScene: 'AFTER_SALE_MEMBER',
        startDate: '2026-10-01',
      });
      return {
        data: new Uint8Array([80, 75, 3, 4]).buffer,
        headers: {
          'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'content-disposition':
            "attachment; filename*=UTF-8''%E9%97%A8%E5%BA%97%E6%98%8E%E7%BB%86.xlsx",
        },
      };
    });
    await store.exportStores({ businessScene: 'AFTER_SALE_MEMBER', startDate: '2026-10-01' });
    expect(watched.downloads).toEqual([{ filename: '门店明细.xlsx', href: 'blob:store-export' }]);
    expect(watched.createObjectURL.mock.calls[0][0]).toBeInstanceOf(Blob);
    expect(watched.createObjectURL.mock.calls[0][0].size).toBe(4);
    expect(document.querySelector('a[download]')).toBeNull();
    await vi.runAllTimersAsync();
    expect(watched.revokeObjectURL).toHaveBeenCalledWith('blob:store-export');
  });

  it('rejects JSON business errors received as arraybuffer without downloading them', async () => {
    const watched = watchDownloads();
    serve(() => ({
      data: new TextEncoder().encode(
        JSON.stringify({ code: 10003, message: '无导出权限', data: null }),
      ).buffer,
      headers: { 'content-type': 'application/json;charset=UTF-8' },
    }));
    await expect(store.exportStores({})).rejects.toMatchObject({
      message: '无导出权限',
      code: 10003,
    });
    expect(watched.downloads).toEqual([]);
    expect(watched.createObjectURL).not.toHaveBeenCalled();
  });
});