Files
weiguang-jewelry-ledger/新账系统/e2e/writes/issue.mjs
T

350 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict';
import { newUi, oldUi } from '../parity-create-order.mjs';
async function seedReturnedLot(session, day) {
const post = async (path, params) => {
const result = await session.postRaw('owner', path, params);
assert.equal(result.status, 200, path + ' ' + JSON.stringify(result.body));
return result.body;
};
await post('/api/stock', { date: day, kind: 'opening', pocket: '现货', grams: '60', note: '真实开单对照库存' });
// 真实售后生成完好现货批次,取消选择应恢复普通开单输入,实际再售应继承原工费与付款人。
const sale = await post('/api/orders/issue', {
date: day,
customer: '供退回现货的原单',
member: 'owner',
customer_type: 'new',
salesperson: '麦麦',
internal_note: '退回现货对照',
payment_account: '麦麦微信',
rounding_mode: 'cent',
fee_items: [],
lines: [
{
name: '足金999',
code: 'A031',
unit: 'g',
quantity: '2',
pocket: '现货',
payer: 'owner',
sale: '1420',
costParts: { material: '1200', labor: '50', accessories: '0', other: '0' },
costPayers: { material: 'owner', labor: 'assistant' },
},
],
});
const original = await session.get('owner', '/api/orders/' + sale.id);
await post('/api/orders/' + sale.id + '/return', {
date: day,
revision: original.revision,
reason: '按实物退回整件',
verified: true,
afterSale: {
lines: [{ lineIndex: 0, quantity: '2', pocket: '现货', disposition: 'stock' }],
refund: { account: '麦麦微信', payer: 'owner', amount: '1420', reference: '' },
deductionReason: '',
expenses: [],
},
});
const lots = () => session.get('owner', '/api/returned-stock-lots?member=owner&date=' + day);
const lot = (await lots()).lots[0];
assert.ok(lot?.id);
assert.equal(lot.laborCost, 5000);
return { lot, lots };
}
export default async function issue({ version, base, day, pageFor, session, step }) {
const ui = version === 'old' ? oldUi : newUi;
const page = await pageFor('owner');
const line = () => ui.line(page, 0);
const control = name =>
line()
.locator(version === 'old' ? '[name="' + name + '"]' : '[data-field="' + name + '"] input')
.first();
const selectLot = () => line().locator('[name=returnedStockId]');
const clickSubmit = () =>
page.locator(version === 'old' ? '#order-form button[type=submit]' : 'button[data-action=issue]').click();
const isIssue = r => r.method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue';
async function steps(items) {
for (const item of items) await ui.step(page, item);
}
let issued = false;
async function start(customer) {
if (issued) {
if (version === 'new') {
await page.locator('[data-action=new-order]').click();
} else {
await page.locator('#order-dialog[open] [data-action=close-dialog]').click();
await page.locator('nav [data-tab=create]').click();
}
await page.locator('#order-form').waitFor();
} else await ui.open(page, base);
await page.locator('#order-form').waitFor();
await steps([
['customer', customer],
['customerType', 'new'],
]);
}
async function issueSale(label) {
let result;
await step(label, async () => {
const [response, shown] = await Promise.all([page.waitForResponse(r => isIssue(r.request())), ui.submit(page)]);
assert.equal(response.status(), 200, await response.text());
assert.ok(shown.paper);
const saved = await response.json();
result = {
payload: response.request().postDataJSON(),
order: await session.get('owner', '/api/orders/' + saved.id),
};
assert.equal(result.order.paper_number, shown.paper);
});
issued = true;
return result;
}
async function rejected(label) {
const issues = [];
const watch = r => {
if (isIssue(r)) issues.push(r.postDataJSON());
};
page.on('request', watch);
try {
await step(label, async () => {
await clickSubmit();
await page.waitForLoadState('networkidle');
assert.deepEqual(issues, [], '本应被表单拦截的开单已发送请求');
assert.ok(await page.locator('#order-form').isVisible());
});
} finally {
page.off('request', watch);
}
}
const { lot, lots } = await seedReturnedLot(session, day);
await start('公式两件开单');
await steps([
['formula', '0.79×822+120=769\n0.58×(822+45)+55=558\n769+558=1327'],
['line', 0, 'cost-materialRate', '800'],
['line', 0, 'cost-labor', '10'],
['line', 1, 'cost-materialRate', '800'],
['line', 1, 'cost-labor', '10'],
['fee', '附加费', 'amount', '0'],
['internalNote', '按公式核对两件商品'],
]);
const formula = await issueSale('多件公式识别后实际开单');
assert.equal(formula.order.lines.length, 2);
assert.equal(formula.order.total, 132700);
await start('金额和克重精度');
await steps([
['line', 0, 'quantity', '0.0001'],
['line', 0, 'goldPrice', '999.50'],
['line', 0, 'laborRate', '0.00'],
['line', 0, 'cost-materialRate', '860.20'],
['line', 0, 'cost-labor', '0.00'],
['internalNote', '精度边界'],
]);
await rejected('拒绝四位小数克重且保留表单');
await steps([
['line', 0, 'quantity', '0.001'],
['line', 0, 'goldPrice', '999.501'],
]);
await rejected('拒绝三位小数金额且保留表单');
await steps([['line', 0, 'goldPrice', '1e3']]);
await rejected('拒绝科学计数法金额且保留表单');
await steps([
['line', 0, 'goldPrice', '999.50'],
['line', 0, 'quantity', '0'],
]);
await rejected('拒绝零克重且保留表单');
await steps([['line', 0, 'quantity', '0.001']]);
await steps([
['line', 0, 'goldPrice', '00999.50'],
['line', 0, 'cost-materialRate', '00860.20'],
]);
const precision = await issueSale('毫克克重与含前导零的分位金额实际开单');
assert.equal(precision.order.lines[0].quantity, 1);
assert.equal(precision.order.total, 100);
assert.equal(typeof precision.payload.lines[0].quantity, 'string');
const ordinary = [
['line', 0, 'quantity', '1.250'],
['line', 0, 'goldPrice', '971.25'],
['line', 0, 'laborRate', '8.50'],
['line', 0, 'cost-materialRate', '832.25'],
['line', 0, 'cost-labor', '3.25'],
];
await start('取消选用退回现货');
await steps([...ordinary, ['internalNote', '改回普通开单']]);
const originalQuantity = await control('quantity').inputValue();
await selectLot().selectOption(lot.id);
assert.equal(await control('quantity').inputValue(), '2.000');
assert.equal(await control('cost-labor').inputValue(), '50.00');
await selectLot().selectOption('');
assert.equal(await control('quantity').inputValue(), originalQuantity);
assert.equal(await control('cost-labor').inputValue(), '3.25');
const ordinarySale = await issueSale('取消退回现货选择后按原输入开单');
assert.ok(!ordinarySale.order.lines[0].returnedStockId);
assert.equal(ordinarySale.order.lines[0].costParts.labor, 325);
assert.equal((await lots()).lots[0].id, lot.id);
await start('完好退回现货再次销售');
await selectLot().selectOption(lot.id);
await steps([
['line', 0, 'goldPrice', '988.75'],
['line', 0, 'laborRate', '3.50'],
['internalNote', '整批原工费再售'],
]);
const resale = await issueSale('整批退回现货沿用原工费再次销售');
assert.equal(resale.payload.lines[0].returnedStockId, lot.id);
assert.equal(resale.order.lines[0].quantity, 2000);
assert.equal(resale.order.lines[0].costParts.labor, 5000);
assert.equal(resale.order.lines[0].costPayers.labor, 'assistant');
assert.ok(!(await lots()).lots.some(item => item.id === lot.id));
}
// 使用同一个账号的两个真实标签页,验证首单成交后重新进入首页的草稿和下一张订单。
export async function exerciseIssueReopen({ version, base, day, session, pageFor, step }) {
const ui = version === 'old' ? oldUi : newUi;
const first = await pageFor('owner');
await session.post('owner', '/api/stock', {
date: day,
kind: 'opening',
pocket: '现货',
grams: '20',
note: '两笔独立销售',
});
const fill = async (page, items) => {
for (const item of items) await ui.step(page, item);
};
const line = (idx, quantity, price) => [
['line', idx, 'quantity', quantity],
['line', idx, 'goldPrice', price],
['line', idx, 'laborRate', '0'],
['line', idx, 'cost-materialRate', '850'],
['line', idx, 'cost-labor', '0'],
];
const issue = async page => {
const [response, shown] = await Promise.all([
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'),
ui.submit(page),
]);
assert.equal(response.status(), 200);
const { id } = await response.json(),
saved = await session.get('owner', '/api/orders/' + id);
assert.equal(saved.paper_number, shown.paper);
await page.waitForLoadState('networkidle');
return saved;
};
await ui.open(first, base);
await fill(first, [
['customer', '上一笔两件商品'],
['customerType', 'new'],
...line(0, '1', '899'),
['addLine'],
...line(1, '2', '900'),
['internalNote', '上一笔普通开单'],
]);
await step('首笔普通两件商品完成销售', async () => {
const saved = await issue(first);
assert.equal(saved.lines.length, 2);
assert.equal(saved.total, 269900);
});
const { user } = await session.get('owner', '/api/session');
const draftKey = (version === 'old' ? 'mm-draft-' : 'mm-next-draft-') + user.id;
const persisted = await first.evaluate(key => {
const raw = localStorage.getItem(key);
if (!raw) return null;
const d = JSON.parse(raw);
return { customer: d.customer, lines: d.lines.map(row => ({ quantity: row.quantity, sale: row.sale })) };
}, draftKey);
const next = await pageFor('owner', { fresh: true });
await next.locator('#order-form').waitFor();
const initialRows = await next
.locator(version === 'old' ? '#order-form .line-item' : '#order-form [data-line]')
.count();
await fill(next, [
['customer', '新标签页第二笔'],
['customerType', 'new'],
...line(0, '0.001', '999.50'),
['internalNote', '第二笔应只收一元'],
]);
await step('新标签页从首页录入第二笔销售', async () => {
const saved = await issue(next);
const evidence = JSON.stringify({
persisted,
initialRows,
total: saved.total,
lines: saved.lines.map(l => ({ quantity: l.quantity, sale: l.sale })),
});
assert.equal(saved.total, 100, '第二单沿用了已成交订单的商品:' + evidence);
assert.equal(saved.lines.length, 1, evidence);
assert.equal(initialRows, 1, evidence);
assert.ok(!persisted || (!persisted.customer && persisted.lines.every(l => !l.quantity)), evidence);
});
}
// 非滚动料池同时存在两天料价时,业务日期往返会实际改变所选批次的成本和利润。
export async function exerciseIssuePoolDate({ version, base, day, session, pageFor, step }) {
const yesterday = '2026-11-19',
ui = version === 'old' ? oldUi : newUi;
const { lot } = await seedReturnedLot(session, day);
await session.post('owner', '/api/material-purchases', {
date: yesterday,
grams: '8',
total: '4000',
payer: 'owner',
note: '昨日购料',
});
await session.post('owner', '/api/material-purchases', {
date: day,
grams: '5',
total: '4500',
payer: 'owner',
note: '当日购料',
});
const page = await pageFor('owner');
await ui.open(page, base);
for (const input of [
['customer', '退回现货切换日期'],
['customerType', 'new'],
['internalNote', '核实重新选用料池'],
['line', 0, 'quantity', '1.250'],
['line', 0, 'goldPrice', '971.25'],
['line', 0, 'laborRate', '8.50'],
['line', 0, 'cost-materialRate', '832.25'],
['line', 0, 'cost-labor', '3.25'],
])
await ui.step(page, input);
const select = ui.line(page, 0).locator('[name=returnedStockId]');
await select.selectOption(lot.id);
await select.selectOption('');
await ui.step(page, ['line', 0, 'materialSource', 'pool']);
const date = page
.locator(version === 'old' ? '#order-form [name=date]' : '#order-form [data-field=date] input')
.first();
for (const d of [yesterday, day]) {
await date.fill(d);
await date.blur();
await page.waitForLoadState('networkidle');
}
await step('撤销退回现货选择并切换日期后按料池实际开单', async () => {
const [response, shown] = await Promise.all([
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'),
ui.submit(page),
]);
assert.equal(response.status(), 200);
const { id } = await response.json(),
order = await session.get('owner', '/api/orders/' + id);
assert.equal(order.paper_number, shown.paper);
const evidence = JSON.stringify({
sale: order.total,
pool: response.request().postDataJSON().lines[0].costMaterial,
material: order.lines[0].costParts.material,
profit: order.profit,
});
assert.equal(order.lines[0].costMaterial.poolId, yesterday, '原选料池随业务日期切换:' + evidence);
assert.equal(order.lines[0].costParts.material, 62500, evidence);
assert.equal(order.profit, 59675, evidence);
});
}