新版界面(React + TypeScript + Vite + Ant Design):登录页与开单页
共用计算经构建插件直接导入 public/ 下的 UMD 源文件;请求客户端沿用旧界面的重试、 同一操作号自动确认、恢复原操作与账号切换约定;附 vitest 单元与组件测试。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bdffbcab85
commit
ec5889075f
39 files changed
+8772
No files matched your search
@@ -0,0 +1,145 @@
|
||||
// 请求客户端约定:与旧界面 test/request-retry.test.js 相同的重试、恢复与账号切换行为。
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { LedgerClient, retryableMutation, type ClientEnv } from '../src/lib/api';
|
||||
|
||||
const ok = (value: unknown) =>
|
||||
new Response(JSON.stringify(value), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||
const httpError = (status: number, error: string, extra = {}) =>
|
||||
new Response(JSON.stringify({ error, ...extra }), { status, headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
function harness(fetcher: (url: string, init: RequestInit, attempt: number) => Promise<Response> | Response) {
|
||||
const saved = new Map<string, string>(),
|
||||
calls: (RequestInit & { url: string })[] = [],
|
||||
delays: number[] = [];
|
||||
let id = 0;
|
||||
const env: ClientEnv = {
|
||||
fetch: async (url, init) => {
|
||||
calls.push({ url, ...init });
|
||||
return fetcher(url, init, calls.length);
|
||||
},
|
||||
storage: {
|
||||
getItem: k => saved.get(k) ?? null,
|
||||
setItem: (k, v) => void saved.set(k, String(v)),
|
||||
removeItem: k => void saved.delete(k),
|
||||
},
|
||||
setTimeout: (fn, ms) => {
|
||||
if (ms === 25000) return 0;
|
||||
delays.push(ms);
|
||||
return setTimeout(fn, 0);
|
||||
},
|
||||
clearTimeout: () => {},
|
||||
randomUUID: () => 'operation-key-' + String(++id).padStart(8, '0'),
|
||||
};
|
||||
const client = new LedgerClient(env);
|
||||
client.setUser('user-1');
|
||||
const headers = (i: number) => calls[i].headers as Record<string, string>;
|
||||
return { client, saved, calls, delays, headers, key: 'mm-pending-user-1' };
|
||||
}
|
||||
|
||||
describe('读请求', () => {
|
||||
it('502/503/504 与网络中断按 400ms、1200ms 最多重试 2 次,并带 X-Ledger-User', async () => {
|
||||
const h = harness((_url, _init, attempt) => (attempt === 1 ? new Response('<html>网关</html>', { status: 502 }) : ok({ ready: true })));
|
||||
await expect(h.client.api('/api/state')).resolves.toEqual({ ready: true });
|
||||
expect(h.calls).toHaveLength(2);
|
||||
expect(h.delays).toEqual([400]);
|
||||
expect(h.headers(0)['X-Ledger-User']).toBe('user-1');
|
||||
const down = harness(() => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
});
|
||||
await expect(down.client.api('/api/state')).rejects.toThrow('Failed to fetch');
|
||||
expect(down.calls).toHaveLength(3);
|
||||
expect(down.delays).toEqual([400, 1200]);
|
||||
});
|
||||
it('明确业务拒绝不重试,保留服务端文字;登录类接口不带 X-Ledger-User', async () => {
|
||||
for (const status of [400, 401, 403, 404, 409, 500]) {
|
||||
const h = harness(() => httpError(status, '具体业务错误'));
|
||||
await expect(h.client.api('/api/state')).rejects.toMatchObject({ status, message: '具体业务错误', confirmed: true });
|
||||
expect(h.calls).toHaveLength(1);
|
||||
}
|
||||
const h = harness(() => ok({ user: null }));
|
||||
await h.client.api('/api/session');
|
||||
await h.client.api('/api/login', { member: 'owner', password: 'x' });
|
||||
expect(h.headers(0)['X-Ledger-User']).toBeUndefined();
|
||||
expect(h.headers(1)['X-Ledger-User']).toBeUndefined();
|
||||
expect(h.headers(1)['Idempotency-Key']).toBeUndefined();
|
||||
expect(h.headers(1)['X-Requested-With']).toBe('maimai-ledger');
|
||||
expect(h.headers(1)['Content-Type']).toBe('application/json');
|
||||
});
|
||||
});
|
||||
|
||||
describe('写入 mutate', () => {
|
||||
it('白名单写入断线后用同一操作号、同一请求体自动确认,最多 2 次;成功后清除待恢复', async () => {
|
||||
const h = harness((_url, _init, attempt) => {
|
||||
if (attempt === 1) throw new TypeError('响应丢失');
|
||||
return ok({ id: 'order-1' });
|
||||
});
|
||||
const data = { customer: '甲', lines: [] as unknown[] };
|
||||
const saving = h.client.mutate('/api/orders/issue', data);
|
||||
expect(h.client.busy).toBe(true);
|
||||
await expect(h.client.mutate('/api/orders/issue', data)).rejects.toThrow('正在保存');
|
||||
data.customer = '改过';
|
||||
await expect(saving).resolves.toEqual({ id: 'order-1' });
|
||||
expect(h.calls).toHaveLength(2);
|
||||
expect(h.calls[0].body).toBe(h.calls[1].body);
|
||||
expect(JSON.parse(String(h.calls[1].body)).customer).toBe('甲');
|
||||
expect(h.headers(0)['Idempotency-Key']).toBe(h.headers(1)['Idempotency-Key']);
|
||||
expect(h.headers(0)['X-Ledger-User']).toBe('user-1');
|
||||
expect(h.saved.size).toBe(0);
|
||||
expect(h.client.busy).toBe(false);
|
||||
});
|
||||
it('非白名单写入不自动重试', async () => {
|
||||
expect(retryableMutation('/api/orders/issue')).toBe(true);
|
||||
expect(retryableMutation('/api/password')).toBe(false);
|
||||
const h = harness(() => {
|
||||
throw new TypeError('断线');
|
||||
});
|
||||
await expect(h.client.mutate('/api/password', { value: 1 })).rejects.toThrow();
|
||||
expect(h.calls).toHaveLength(1);
|
||||
});
|
||||
it('自动确认用尽保留待恢复;“恢复原操作”原样重发同一请求与操作号', async () => {
|
||||
let connected = false;
|
||||
const h = harness(() => {
|
||||
if (!connected) throw new TypeError('断线');
|
||||
return ok({ id: 'order-9' });
|
||||
});
|
||||
await expect(h.client.mutate('/api/orders/issue', { customer: '乙' })).rejects.toThrow(/提交结果待确认/);
|
||||
expect(h.calls).toHaveLength(3);
|
||||
const job = JSON.parse(h.saved.get(h.key)!);
|
||||
expect(job).toMatchObject({ url: '/api/orders/issue', userId: 'user-1' });
|
||||
await expect(h.client.mutate('/api/orders/issue', { customer: '丙' })).rejects.toThrow('恢复原操作');
|
||||
connected = true;
|
||||
const recovered = await h.client.retryPending();
|
||||
expect(recovered?.result).toEqual({ id: 'order-9' });
|
||||
expect(h.calls).toHaveLength(4);
|
||||
expect(h.headers(3)['Idempotency-Key']).toBe(job.key);
|
||||
expect(h.calls[3].body).toBe(h.calls[0].body);
|
||||
expect(h.saved.size).toBe(0);
|
||||
});
|
||||
it('已确认的 400/403/404/409/413 清除待恢复;HTML 拒绝保留待恢复', async () => {
|
||||
for (const status of [400, 403, 404, 409, 413]) {
|
||||
const h = harness(() => httpError(status, '请核对'));
|
||||
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ status, message: '请核对' });
|
||||
expect(h.saved.size).toBe(0);
|
||||
}
|
||||
const h = harness(() => new Response('<html>拒绝</html>', { status: 403 }));
|
||||
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toThrow(/403.*仍待确认/);
|
||||
expect(h.saved.has(h.key)).toBe(true);
|
||||
});
|
||||
it('服务端 409 ACCOUNT_CHANGED 不清除待恢复、保留原提示;本页账号在退避期间变化立即停止', async () => {
|
||||
const h = harness(() => httpError(409, '登录账号已在其他页面切换,请刷新后继续;原操作已暂停。', { code: 'ACCOUNT_CHANGED' }));
|
||||
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ code: 'ACCOUNT_CHANGED', status: 409 });
|
||||
expect(h.saved.has(h.key)).toBe(true);
|
||||
const s = harness(() => {
|
||||
s.client.setUser('user-2');
|
||||
throw new TypeError('断线');
|
||||
});
|
||||
await expect(s.client.mutate('/api/orders/issue', {})).rejects.toMatchObject({ code: 'ACCOUNT_CHANGED' });
|
||||
expect(s.calls).toHaveLength(1);
|
||||
expect(s.saved.has('mm-pending-user-1')).toBe(true);
|
||||
expect(s.saved.has('mm-pending-user-2')).toBe(false);
|
||||
});
|
||||
it('401 改为提示重新登录后恢复', async () => {
|
||||
const h = harness(() => httpError(401, '请先登录'));
|
||||
await expect(h.client.mutate('/api/orders/issue', {})).rejects.toThrow('登录已过期,请刷新并登录,再恢复原操作。');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
// 开单页:填写、校验提示、提交请求体与开单成功页。
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import { App as AntApp } from 'antd';
|
||||
import { CreateOrderPage } from '../src/pages/CreateOrder/CreateOrderPage';
|
||||
import type { LedgerState, SessionInfo } from '../src/shared';
|
||||
import { fakeClient } from './helpers';
|
||||
|
||||
const state: LedgerState = {
|
||||
today: '2026-11-20',
|
||||
mode: 'trial',
|
||||
user: { id: 'owner-id', name: '麦麦', role: 'owner', member: 'owner', operatorName: '麦麦' },
|
||||
members: [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
],
|
||||
accounts: ['麦麦微信', '助理微信', '麦麦信用卡'],
|
||||
shopSettings: {},
|
||||
pockets: ['现货', '金料'],
|
||||
};
|
||||
const session: SessionInfo = { user: state.user, setup: false, mode: 'trial', today: '2026-11-20' };
|
||||
const field = (root: HTMLElement, name: string) => root.querySelector(`[data-field="${name}"] input,[data-field="${name}"] textarea`) as HTMLInputElement;
|
||||
const type = (root: HTMLElement, name: string, value: string) => fireEvent.change(field(root, name), { target: { value } });
|
||||
|
||||
function setup() {
|
||||
const fake = fakeClient({
|
||||
'/api/material-pools': () => ({ rows: [] }),
|
||||
'/api/paper-number': () => ({ number: '20261120005' }),
|
||||
'/api/order-note-tags': () => ({ tags: ['#补货', '#客户自提'] }),
|
||||
'/api/order-templates': () => ({ rows: [] }),
|
||||
'/api/orders/issue': () => ({ id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' }),
|
||||
'/api/orders/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee': () => ({
|
||||
id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',
|
||||
paper_number: '20261120005',
|
||||
total: 245000,
|
||||
rounding_mode: 'yuan',
|
||||
}),
|
||||
});
|
||||
fake.client.setUser('owner-id');
|
||||
const view = render(
|
||||
<AntApp>
|
||||
<CreateOrderPage client={fake.client} state={state} session={session} refreshState={async () => state} onAccountChanged={() => {}} />
|
||||
</AntApp>,
|
||||
);
|
||||
return { ...fake, view };
|
||||
}
|
||||
|
||||
describe('开单页', () => {
|
||||
beforeEach(() => window.localStorage.clear());
|
||||
it('缺客户类型时提示;填写完整后以与旧界面相同结构提交并显示纸单号与合计', async () => {
|
||||
const { calls, view } = setup();
|
||||
const root = view.container;
|
||||
type(root, 'customer', '测试客户');
|
||||
const line = root.querySelector('[data-line="0"]') as HTMLElement;
|
||||
type(line, 'quantity', '2.5');
|
||||
type(line, 'goldPrice', '950');
|
||||
type(line, 'laborRate', '30');
|
||||
type(line, 'cost-materialRate', '880');
|
||||
type(line, 'cost-labor', '25');
|
||||
expect(screen.getByTestId('create-total')).toHaveTextContent('¥2,450');
|
||||
fireEvent.click(await screen.findByRole('button', { name: '#补货' }));
|
||||
expect(field(root, 'internal_note').value).toBe('#补货 ');
|
||||
fireEvent.click(screen.getByRole('button', { name: /生成销售单据/ }));
|
||||
expect(await screen.findByTestId('order-error')).toHaveTextContent('请选择客户类型');
|
||||
fireEvent.click(within(root.querySelector('[data-field="customer_type"]') as HTMLElement).getByText('新客户'));
|
||||
fireEvent.click(screen.getByRole('button', { name: /生成销售单据/ }));
|
||||
await waitFor(() => expect(screen.getByTestId('issued-paper-number')).toHaveTextContent('20261120005'));
|
||||
expect(screen.getByTestId('issued-total')).toHaveTextContent('¥2,450');
|
||||
const issue = calls.find(call => call.url === '/api/orders/issue')!;
|
||||
expect(issue.headers['Idempotency-Key']).toBe('test-operation-key-0001');
|
||||
expect(issue.body).toMatchObject({
|
||||
customer: '测试客户',
|
||||
customer_type: 'new',
|
||||
salesperson: '麦麦',
|
||||
member: 'owner',
|
||||
payment_account: '麦麦微信',
|
||||
rounding_mode: 'yuan',
|
||||
fee_cost_mode: 'checkboxes',
|
||||
internal_note: '#补货',
|
||||
fee_items: [],
|
||||
lines: [
|
||||
{
|
||||
name: '足金999',
|
||||
pricingMode: 'auto',
|
||||
quantity: '2.5',
|
||||
sale: '2450.00',
|
||||
pocket: '现货',
|
||||
costMaterial: { mode: 'gram', rate: '880' },
|
||||
costLabor: { mode: 'total' },
|
||||
costPayers: { material: 'owner', labor: 'owner' },
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(screen.getByRole('link', { name: /打开打印预览/ })).toHaveAttribute(
|
||||
'href',
|
||||
'/print/aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',
|
||||
);
|
||||
expect(window.localStorage.getItem('mm-next-draft-owner-id')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { LedgerClient } from '../src/lib/api';
|
||||
|
||||
export function fakeClient(routes: Record<string, (body: unknown) => unknown>) {
|
||||
const calls: { url: string; method: string; body: unknown; headers: Record<string, string> }[] = [];
|
||||
const client = new LedgerClient({
|
||||
fetch: async (url, init) => {
|
||||
const body = init.body ? JSON.parse(String(init.body)) : undefined;
|
||||
calls.push({ url, method: String(init.method), body, headers: init.headers as Record<string, string> });
|
||||
const handler = routes[url.split('?')[0]];
|
||||
if (!handler) return new Response(JSON.stringify({ error: '地址不存在' }), { status: 404 });
|
||||
try {
|
||||
return new Response(JSON.stringify(handler(body)), { status: 200 });
|
||||
} catch (err) {
|
||||
return new Response(JSON.stringify({ error: (err as Error).message }), { status: 401 });
|
||||
}
|
||||
},
|
||||
storage: window.localStorage,
|
||||
setTimeout: (fn, ms) => (ms === 25000 ? 0 : setTimeout(fn, 0)),
|
||||
clearTimeout: () => {},
|
||||
randomUUID: () => 'test-operation-key-0001',
|
||||
});
|
||||
return { client, calls };
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// 登录页三种入口:演示一键进入、员工下拉加密码、试用空库初始化。
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { App as AntApp } from 'antd';
|
||||
import { LoginPage } from '../src/pages/Login/LoginPage';
|
||||
import type { SessionInfo } from '../src/shared';
|
||||
import { fakeClient } from './helpers';
|
||||
|
||||
const base: SessionInfo = { user: null, setup: false, mode: 'trial', today: '2026-11-20', brand: { storeName: '对照珠宝' } };
|
||||
const show = (session: SessionInfo, client: ReturnType<typeof fakeClient>['client'], onLoggedIn = vi.fn()) =>
|
||||
render(
|
||||
<AntApp>
|
||||
<LoginPage client={client} session={session} onLoggedIn={onLoggedIn} />
|
||||
</AntApp>,
|
||||
);
|
||||
|
||||
describe('登录页', () => {
|
||||
it('演示模式:每位成员一个进入按钮,点击后 POST /api/demo-login', async () => {
|
||||
const { client, calls } = fakeClient({ '/api/demo-login': () => ({ user: {} }) });
|
||||
const onLoggedIn = vi.fn();
|
||||
show(
|
||||
{ ...base, mode: 'demo', loginOptions: [{ member: 'owner', label: '麦麦' }, { member: 'assistant', label: '娜娜' }] },
|
||||
client,
|
||||
onLoggedIn,
|
||||
);
|
||||
expect(screen.getByText('对照珠宝 · 新账系统')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: '以娜娜身份进入演示' }));
|
||||
await waitFor(() => expect(onLoggedIn).toHaveBeenCalled());
|
||||
expect(calls[0]).toMatchObject({ url: '/api/demo-login', method: 'POST', body: { member: 'assistant' } });
|
||||
expect(calls[0].headers['Idempotency-Key']).toBeUndefined();
|
||||
expect(screen.getByRole('link', { name: '返回旧版界面' })).toHaveAttribute('href', '/');
|
||||
});
|
||||
it('密码登录:选择账号与密码后提交;错误密码显示服务端提示', async () => {
|
||||
let attempts = 0;
|
||||
const { client, calls } = fakeClient({
|
||||
'/api/login': () => {
|
||||
if (++attempts === 1) throw new Error('账号或密码不正确');
|
||||
return { user: {} };
|
||||
},
|
||||
});
|
||||
const onLoggedIn = vi.fn();
|
||||
const { container } = show({ ...base, loginOptions: [{ member: 'owner', label: '麦麦' }] }, client, onLoggedIn);
|
||||
fireEvent.click(screen.getByRole('button', { name: /登\s*录/ }));
|
||||
expect(await screen.findByText('请选择登录账号')).toBeInTheDocument();
|
||||
fireEvent.mouseDown(container.querySelector('.ant-select-selector')!);
|
||||
fireEvent.click(await screen.findByTitle('麦麦'));
|
||||
fireEvent.change(screen.getByLabelText('密码'), { target: { value: 'wrong-password-1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /登\s*录/ }));
|
||||
expect(await screen.findByText('账号或密码不正确')).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText('密码'), { target: { value: 'right-password-1' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /登\s*录/ }));
|
||||
await waitFor(() => expect(onLoggedIn).toHaveBeenCalledTimes(1));
|
||||
expect(calls.at(-1)?.body).toEqual({ member: 'owner', password: 'right-password-1' });
|
||||
});
|
||||
it('试用空库:初始化表单校验密码长度,提交店铺与店主资料', async () => {
|
||||
const { client, calls } = fakeClient({ '/api/setup': () => ({ user: {} }) });
|
||||
const onLoggedIn = vi.fn();
|
||||
show({ ...base, setup: true }, client, onLoggedIn);
|
||||
fireEvent.change(screen.getByLabelText('店铺名称'), { target: { value: '新店' } });
|
||||
fireEvent.change(screen.getByLabelText('店主密码'), { target: { value: 'short' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /建立试用账号/ }));
|
||||
expect(await screen.findByText('店主密码至少12个字符')).toBeInTheDocument();
|
||||
expect(calls).toHaveLength(0);
|
||||
fireEvent.change(screen.getByLabelText('店主密码'), { target: { value: 'long-enough-pass' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /建立试用账号/ }));
|
||||
await waitFor(() => expect(onLoggedIn).toHaveBeenCalled());
|
||||
expect(calls[0].body).toEqual({
|
||||
storeName: '新店',
|
||||
ownerLabel: '店主',
|
||||
ownerLoginName: 'owner',
|
||||
ownerPassword: 'long-enough-pass',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { afterEach } from 'vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
|
||||
afterEach(() => cleanup());
|
||||
// antd 的响应式组件依赖 matchMedia;jsdom 未实现。
|
||||
if (!window.matchMedia)
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: (query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener() {},
|
||||
removeListener() {},
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
dispatchEvent: () => false,
|
||||
}),
|
||||
});
|
||||
if (!window.ResizeObserver)
|
||||
window.ResizeObserver = class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
} as unknown as typeof ResizeObserver;
|
||||
// jsdom 的 getComputedStyle 不支持伪元素参数,antd 会调用并打印告警。
|
||||
const original = window.getComputedStyle;
|
||||
window.getComputedStyle = (element: Element) => original(element);
|
||||
@@ -0,0 +1,75 @@
|
||||
// 经 sharedUmd 插件导入的共用计算:与服务端 require 的是同一份源文件。
|
||||
import { createRequire } from 'node:module';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { Calc, Cards, Fees, Model } from '../src/shared';
|
||||
import type { LedgerState } from '../src/shared';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const serverCalc = require('../../public/calculations.js');
|
||||
|
||||
const st: LedgerState = {
|
||||
today: '2026-11-20',
|
||||
mode: 'trial',
|
||||
user: { id: 'u', name: '娜娜', role: 'assistant', member: 'assistant', operatorName: '娜娜' },
|
||||
members: [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
],
|
||||
accounts: ['麦麦微信', '助理微信', '麦麦信用卡'],
|
||||
shopSettings: {},
|
||||
};
|
||||
let n = 0;
|
||||
const uuid = () => '00000000-0000-4000-8000-' + String(++n).padStart(12, '0');
|
||||
const ctx = { st, uuid };
|
||||
|
||||
describe('共用模块', () => {
|
||||
it('浏览器构建与服务端得到相同的计算结果', () => {
|
||||
const line = { pricingMode: 'auto', unit: 'g', quantity: '1.234', goldPrice: '888.88', laborMode: 'gram', laborRate: '35' };
|
||||
expect(Calc.sale(line)).toEqual(serverCalc.sale(line));
|
||||
expect(Calc.orderTotal([123449], 0, 'yuan').total).toBe(123400);
|
||||
expect(Calc.orderTotal([123450], 0, 'yuan').total).toBe(123500);
|
||||
expect(Cards.amount(100000, 6)).toBe(600);
|
||||
expect(Fees.checkboxCategory('快递')).toBe('shipping');
|
||||
});
|
||||
it('店员开单:订单归属固定为本人,收款默认本人微信,付款人默认本人', () => {
|
||||
const form = Model.newForm(ctx);
|
||||
expect(form.memberLocked).toBe(true);
|
||||
expect(Model.readPaymentAccount(form)).toBe('助理微信');
|
||||
expect(form.lines[0].purchase?.materialPayer).toBe('assistant');
|
||||
const r = Model.syncForm(form, ctx);
|
||||
expect(r.draft.member).toBe('assistant');
|
||||
});
|
||||
it('行与合计:克重×(金价+克工费)+附加项目,整单取整到元', () => {
|
||||
let form = Model.newForm(ctx);
|
||||
form = Model.addCharge(form, 0, uuid);
|
||||
form = Model.updateLine(form, 0, { ...form.lines[0], quantity: '1.5', goldPrice: '900', laborRate: '20' });
|
||||
const r = Model.syncForm(form, ctx);
|
||||
expect(r.form.lines[0].sale).toBe('1435.00');
|
||||
expect(r.summary.totalText).toBe('¥1,435');
|
||||
expect(r.form.lines[0].view.calculation).toBe('1.5 ×(900 + 20) + 附加 55.00 = 1,435.00 元');
|
||||
});
|
||||
it('附加项目默认报价不覆盖手改、0 与清空', () => {
|
||||
let c = Model.newCharge({}, uuid);
|
||||
c = Model.setChargeAmount(c, '0');
|
||||
c = Model.changeChargeType(Model.changeChargeType(c, '快递'), '编绳');
|
||||
expect(c.amount).toBe('0');
|
||||
expect(Model.changeChargeType(c, '快递').amount).toBe('8');
|
||||
});
|
||||
it('校验:必填项与内部备注最少 3 个字符(# 计入)', () => {
|
||||
const form = { ...Model.newForm(ctx), customer_type: 'new' as const };
|
||||
let r = Model.syncForm(Model.updateLine(form, 0, { ...form.lines[0], quantity: '1', goldPrice: '900', laborRate: '20' }), ctx);
|
||||
r = Model.syncForm(
|
||||
Model.updateLine(r.form, 0, {
|
||||
...r.form.lines[0],
|
||||
purchase: { ...r.form.lines[0].purchase!, materialRate: '800', labor: '10' },
|
||||
}),
|
||||
ctx,
|
||||
);
|
||||
const draft = { ...r.draft, customer: '客户', internal_note: '#ab' };
|
||||
expect(() => Model.validateIssueDraft(draft, st)).not.toThrow();
|
||||
expect(() => Model.validateIssueDraft({ ...draft, internal_note: '# a' }, st)).toThrow(/至少填写3个字符/);
|
||||
expect(() => Model.validateIssueDraft({ ...draft, customer: '' }, st)).toThrow(/客户称呼/);
|
||||
expect(() => Model.validateIssueDraft({ ...draft, salesperson: ' ' }, st)).toThrow(/开单人/);
|
||||
expect(() => Model.validateFormFields({ ...r.form, customer_type: '' }, st)).toThrow(/客户类型/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user