Files
weiguang-jewelry-ledger/新账系统/test/recovery-changes-ui.test.js
T

995 lines
38 KiB
JavaScript
Raw Normal View History

'use strict';
const { createBrowserContext } = require('./fixtures/browser-context.cjs');
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
path = require('node:path'),
vm = require('node:vm'),
{ randomUUID } = require('node:crypto');
const Calc = require('../public/calculations'),
Card = require('../public/credit-card-fees');
const D = '2026-11-04',
OLD = '2026-11-03',
ID = '11111111-1111-4111-8111-111111111111',
RID = '22222222-2222-4222-8222-222222222222';
function inputs(extra = {}) {
return {
mode: 'exchange',
date: D,
customer: '合成客户',
salesperson: '合成开单人',
member: 'assistant',
note: '原备注',
old_lines: [
{ name: '旧戒指', incoming_weight: '10.000', melted_weight: '10.000', purity: '100.000' },
{ name: '旧手链', incoming_weight: '5.000', melted_weight: '5.000', purity: '99.000' },
],
buy_rate: '0.00',
buy_total: '0.00',
payer: 'owner',
payment_account: '助理微信',
verified: true,
exchange: {
name: '足金999',
quantity: '20.000',
pocket: '现货',
gold_price: '1000.00',
labor_rate: '20.00',
labor_mode: 'gram',
depreciation_weight: '14.950',
depreciation_rate: '10.00',
charges: [
{ id: 'charge-one', name: '第一项收费', amount: '6.50' },
{ id: 'charge-two', name: '第二项收费', amount: '8.25' },
],
discount: '0.00',
rounding_mode: 'cent',
cost_material: { mode: 'gram', rate: '900.00' },
cost_labor: { mode: 'total', amount: '30.00' },
cost_payer: 'owner',
cost_material_payer: 'assistant2',
cost_labor_payer: 'owner',
fee_items: [
{ key: 'first', note: '第一笔费用', amount: '3.20', payer: 'assistant' },
{ key: 'second', note: '第二笔费用', amount: '2.40', payer: 'assistant2' },
],
},
...extra,
};
}
function detail(role = 'owner', extra = {}) {
const input = inputs(extra.inputs);
return {
id: ID,
revision: 3,
status: 'active',
record: {
id: ID,
number: 'HS合成0001',
date: input.date,
mode: input.mode,
member: input.member,
customer: input.customer,
},
permissions: {
canEdit: true,
canCancel: true,
canDirect: role === 'owner' || input.date === D,
requiresApproval: role !== 'owner' && input.date !== D,
reason: '',
},
blockedUsages: [],
pending: null,
history: [],
...extra,
inputs: input,
};
}
function request(extra = {}) {
const before = inputs(),
after = inputs({ customer: '更正客户' });
after.old_lines[1].melted_weight = '4.990';
return {
id: RID,
recoveryId: ID,
revision: 1,
recoveryRevision: 3,
action: 'update',
status: 'pending',
reason: '原重量录错',
before,
after,
summary: {
before: { cashReceipt: 561425, cashPayment: 0, goodsCost: 457500, directCost: 560, profit: 103365 },
after: { cashReceipt: 562525, cashPayment: 0, goodsCost: 458400, directCost: 560, profit: 103565 },
},
requesterName: '娜娜',
requesterMember: 'assistant',
member: 'assistant',
created: D + 'T08:00:00Z',
reviewerName: null,
reviewed: null,
note: '',
stale: false,
canApprove: true,
...extra,
};
}
function node(extra = {}) {
return {
innerHTML: '',
textContent: '',
disabled: false,
hidden: false,
dataset: {},
setAttribute() {},
classList: { toggle() {} },
focus() {},
scrollIntoView() {},
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
...extra,
};
}
function harness(member = 'owner') {
const nodes = new Map(),
saved = new Map(),
calls = [],
handlers = {},
toasts = [],
user = {
id: 'ui-' + member,
role: member === 'owner' ? 'owner' : 'assistant',
member,
name: member === 'owner' ? '麦麦' : member === 'assistant' ? '娜娜' : '小昊',
};
for (const key of [
'#main',
'#pending',
'#recovery-form-error',
'#recovery-change-review-error',
'#recovery-cancel-error',
'#recovery-change-review-actions',
'#recovery-change-list',
'#recovery-changes-entry',
'#recovery-edit-mode',
])
nodes.set(key, node());
for (const key of ['#recovery-dialog', '#recovery-change-dialog']) {
const events = {};
nodes.set(
key,
node({
open: key === '#recovery-dialog',
showModal() {
this.open = true;
},
close() {
if (!this.open) return;
this.open = false;
events.close?.();
},
replaceChildren() {
this.innerHTML = '';
},
addEventListener(type, fn) {
events[type] = fn;
},
}),
);
}
const context = createBrowserContext({
console,
URLSearchParams,
LedgerCalc: Calc,
CreditCardFees: Card,
crypto: { randomUUID },
setTimeout() {},
clearTimeout() {},
setInterval() {},
FormData: class {
constructor(form) {
return Object.entries(form.values || {});
}
},
window: { scrollTo() {}, open() {} },
document: {
querySelector: key => nodes.get(key) || null,
querySelectorAll() {
return [];
},
addEventListener(type, handler) {
(handlers[type] ??= []).push(handler);
},
},
localStorage: {
getItem: key => saved.get(key) ?? null,
setItem: (key, value) => saved.set(key, String(value)),
removeItem: key => saved.delete(key),
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__calls: calls,
__toasts: toasts,
__user: user,
__detail: detail(user.role),
__request: request({ canApprove: user.role === 'owner' }),
__result: {},
__form: null,
__finished: null,
__rendered: 0,
__opened: [],
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of ['material-pools-ui.js', 'recoveries-ui.js', 'recovery-changes-ui.js', 'app.js'])
run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
`session={user:__user};state={user:__user,members:[{member:'owner'},{member:'assistant'},{member:'assistant2'}],today:'${D}',pockets:['现货','金料'],accounts:['麦麦微信','麦麦支付宝','麦麦现金','麦麦信用卡','助理微信','助理支付宝','助理现金','助理2微信','助理2支付宝','助理2现金']};tab='recoveries';api=async function(url,data,key){__calls.push({url,data,key});if(data)return __result;if(url.startsWith('/api/recovery-changes?'))return {requests:[__request],counts:{pending:1,approved:0,rejected:0}};if(url==='/api/recovery-changes/'+__request.id)return __request;return __detail;};toast=function(message,error){__toasts.push({message,error});};renderRecoveryEdit=function(){__rendered++;};renderRecoveries=async function(){__rendered++;};refresh=async function(){};invalidateReport=function(){};invalidateMaterialPools=function(){};openRecovery=async function(id){__opened.push(id);};syncRecoveryForm=function(form){rememberRecoveryDraft(form);return recoveryCalculate(recoveryInput(recoveryFormDraft(form),{quote:true}));};`,
);
async function open(extra = {}) {
context.__detail = detail(user.role, extra);
await run(`openRecoveryEdit('${ID}')`);
}
function editForm(values = {}) {
const draft = json('recoveryEditEntry.draft'),
flat = { ...draft, change_reason: '核对后更正', verified: true, ...values },
fields = Object.fromEntries(
Object.entries(flat)
.filter(([, value]) => typeof value !== 'object')
.map(([name, value]) => [
name,
node({
name,
value: String(value ?? ''),
checked: value === true,
closest() {
return null;
},
}),
]),
);
fields.namedItem = name => fields[name];
const rows = {
old: draft.old_lines.slice(1).map((row, index) =>
extraRow('old', index + 1, {
extra_old_name: row.name,
extra_incoming_weight: row.incoming_weight,
extra_melted_weight: row.melted_weight,
extra_purity: row.purity,
}),
),
charge: draft.charges
.slice(1)
.map((row, index) =>
extraRow('charge', index + 1, { extra_charge_name: row.name, extra_charge_amount: row.amount }),
),
fee: draft.fee_items.slice(1).map((row, index) =>
extraRow('fee', index + 1, {
extra_fee_note: row.note,
extra_fee_amount: row.amount,
extra_fee_payer: row.payer,
}),
),
},
submit = node(),
cancel = node({ dataset: { action: 'recovery-edit-close' } }),
reload = node({ dataset: { action: 'recovery-edit-reload' } }),
controls = [...Object.values(fields).filter(value => typeof value !== 'function'), submit, cancel, reload];
const form = node({
id: 'recovery-form',
elements: fields,
dataset: {
recoveryEdit: 'true',
buy_total_manual: String(draft.buy_total_manual),
depreciation_manual: String(draft.depreciation_manual),
melted_manual: 'true',
},
querySelector(selector) {
return fields[selector.match(/name="([^"]+)"/)?.[1]] || null;
},
querySelectorAll(selector) {
if (selector === '[data-recovery-product]') return [];
const kind = selector.match(/data-recovery-edit-row="([^"]+)"/)?.[1];
return kind ? rows[kind] : controls;
},
});
nodes.set('#recovery-form', form);
nodes.set('#recovery-save', submit);
context.__form = form;
return { form, fields, rows, submit, cancel, reload };
}
function extraRow(kind, index, values) {
const fields = Object.fromEntries(Object.entries(values).map(([name, value]) => [name, node({ name, value })]));
return node({
dataset: { index: String(index), kind },
fields,
querySelector(selector) {
return fields[selector.match(/name="([^"]+)"/)?.[1]] || null;
},
});
}
async function review(extra = {}) {
context.__request = request({ canApprove: user.role === 'owner', ...extra });
await run(`openRecoveryChange('${RID}')`);
}
function reviewForm(kind, values = {}) {
run(`showRecoveryDecision('${kind}')`);
return smallForm('recovery-change-review-form', { note: '', verified: false, ...values }, { kind });
}
function smallForm(id, values, dataset = {}) {
const fields = Object.fromEntries(
Object.entries(values).map(([name, value]) => [
name,
node({ name, value: typeof value === 'boolean' ? 'on' : value, checked: value === true }),
]),
),
submit = node(),
close = node({ dataset: { action: 'recovery-changes-close' } }),
form = node({
id,
dataset,
querySelector(selector) {
return fields[selector.match(/name="([^"]+)"/)?.[1]] || null;
},
querySelectorAll() {
return [...Object.values(fields), submit, close];
},
});
nodes.set('#' + id, form);
for (const [name, field] of Object.entries(fields)) nodes.set('#' + id + ' [name="' + name + '"]', field);
context.__form = form;
return { form, fields, submit, close };
}
async function click(action, attrs = {}) {
const button = node({
dataset: { action, ...attrs },
closest() {
return null;
},
});
for (const handler of handlers.click || [])
await handler({
target: {
closest() {
return button;
},
},
});
}
return {
context,
run,
json,
nodes,
saved,
calls,
toasts,
open,
editForm,
review,
reviewForm,
smallForm,
click,
user,
};
}
test('修改回填旧料去向、独立入库数量并暂存,详情与审批对照区分旧料入库和新货出库', async () => {
const h = harness();
h.run("state.pockets.push('找金');state.pocketCatalog=[{key:'找金',name:'找金',active:true,self:false}];");
await h.open({ inputs: { old_pocket: '找金' } });
assert.equal(h.json('recoveryEditEntry.draft').old_pocket, '找金');
h.editForm({ old_pocket: '金料' });
h.run('rememberRecoveryEditDraft(__form)');
const draft = JSON.parse(h.saved.get('mm-recovery-edit-' + h.user.id + '-' + ID));
assert.equal(draft.draft.old_pocket, '金料');
assert.equal(draft.draft.pocket, '现货');
assert.equal(h.json('recoveryInput(recoveryFormDraft(__form))').old_pocket, '金料');
h.context.__request = request({
before: inputs({ old_pocket: '找金', old_stock_count: 3 }),
after: inputs({ old_pocket: '金料' }),
});
const comparison = h.run('recoveryChangeComparisonHTML(__request)');
assert.match(comparison, /旧料入库货盘/);
assert.match(comparison, /旧料入库数量(对)/);
assert.match(comparison, /3对/);
assert.match(comparison, /找金/);
assert.match(comparison, /金料/);
h.context.__record = {
id: ID,
number: 'HS合成',
mode: 'direct',
date: D,
customer: '合成客户',
salesperson: '合成开单人',
member: 'assistant',
oldPocket: '找金',
old_lines: [],
oldMg: 9900,
buyRate: 90000,
purchaseAmount: 891000,
goldRate: 0,
laborRate: 0,
depreciationRate: 0,
receivable: 0,
netSettlement: -891000,
payer: 'owner',
payment_account: '麦麦微信',
};
const detailHTML = h.run('recoveryDetailHTML(__record)');
assert.match(detailHTML, /折后旧料 9\.900g 入找金库存/);
h.context.__record.status = 'cancelled';
assert.match(h.run('recoveryDetailHTML(__record)'), /原找金旧料入库.*已冲回/);
});
test('编辑沿原表单回填多旧料、多收费多费用,锁定类型归属并保留原开单草稿', async () => {
const h = harness();
h.saved.set('mm-recovery-draft-' + h.user.id, '原开单草稿');
await h.open();
const html = h.run('recoveryEditingFormHTML(recoveryEditEntry)');
for (const text of [
'data-recovery-edit="true"',
'沿用原单号',
'旧手链',
'第二项收费',
'第二笔费用',
'extra_fee_payer',
'修改原因',
'取消修改',
])
assert.ok(html.includes(text), text);
assert.ok(!html.includes('data-action="recovery-mode"'));
assert.ok(!html.includes('<select name="member"'));
assert.equal(h.saved.get('mm-recovery-draft-' + h.user.id), '原开单草稿');
const { rows } = h.editForm();
rows.old[0].fields.extra_melted_weight.value = '4.990';
rows.charge[0].fields.extra_charge_amount.value = '9.75';
rows.fee[0].fields.extra_fee_amount.value = '3.45';
const value = h.json('recoveryInput(recoveryFormDraft(__form))');
assert.equal(value.old_lines.length, 2);
assert.equal(value.old_lines[1].melted_weight, '4.990');
assert.equal(value.exchange.charges[1].id, 'charge-two');
assert.equal(value.exchange.charges[1].amount, '9.75');
assert.equal(value.exchange.fee_items[1].key, 'second');
assert.equal(value.exchange.fee_items[1].amount, '3.45');
assert.equal(value.exchange.cost_payer, 'owner');
assert.equal(value.member, 'assistant');
assert.equal(h.json('recoveryCalculate(recoveryInput(recoveryFormDraft(__form))).oldMg'), 14940);
});
test('修改payload不丢多行和费用,使用专用update与原版本,0费用保留身份', async () => {
const h = harness();
await h.open();
h.editForm({ customer: '更正客户' });
h.run('finishRecoveryChangeSave=async function(url,input,result){__finished={url,input,result};};');
h.calls.length = 0;
await h.run('submitRecoveryEdit(__form)');
assert.equal(h.calls.length, 1);
assert.equal(h.calls[0].url, '/api/recoveries/' + ID + '/update');
const input = JSON.parse(JSON.stringify(h.calls[0].data));
assert.equal(input.revision, 3);
assert.equal(input.reason, '核对后更正');
assert.equal(input.verified, true);
assert.equal(input.old_lines.length, 2);
assert.equal(input.exchange.charges.length, 2);
assert.equal(input.exchange.fee_items.length, 2);
assert.equal(input.exchange.fee_items[1].payer, 'assistant2');
assert.ok(!h.calls.some(call => call.url === '/api/recoveries'));
assert.equal(h.saved.has('mm-pending-' + h.user.id), false);
});
test('助理仅本人,原日与新日均今天为直改,其余显示申请,待审禁止重复处理', async () => {
const h = harness('assistant');
await h.open();
const { fields, submit } = h.editForm();
h.run('syncRecoveryEditMode()');
assert.equal(submit.textContent, '保存修改');
fields.date.value = OLD;
h.run('syncRecoveryEditMode()');
assert.equal(submit.textContent, '提交修改申请');
assert.match(h.nodes.get('#recovery-edit-mode').textContent, /审批前.*不变/);
const denied = harness('assistant2');
await assert.rejects(denied.open(), /不属于当前成员/);
const pending = harness();
await assert.rejects(
pending.open({
pending: request(),
permissions: { canEdit: false, canCancel: false, canDirect: false, requiresApproval: true, reason: '待店主复核' },
}),
/待店主复核/,
);
assert.equal(pending.run('recoveryEditEntry'), null);
});
test('已有用料仍能取消,展示订单锁价与匿名用量,修改约束保留', async () => {
const usages = [
{ orderId: 'own-order', number: 'XS<可见>', mg: 1000 },
{ priceLockId: 'own-lock', number: '锁价可见', mg: 500 },
{ orderId: 'hidden-order', number: '不可泄露订单', mg: 2000, anonymous: true },
];
for (const member of ['owner', 'assistant']) {
const h = harness(member);
h.context.__detail = detail(h.user.role, { blockedUsages: usages });
h.run('recoveryDetailEdit=__detail');
const actions = h.run('recoveryDetailChangeActionsHTML(__detail.record)'),
panel = h.run('recoveryEditPanelHTML(__detail)');
assert.match(actions, /recovery-edit-open/);
assert.match(actions, /recovery-edit-cancel/);
assert.match(panel, /修改时不能更换金料日期,也不能将金料减至低于已用/预留量/);
assert.match(panel, /公共料按可用量补足/);
assert.match(panel, /公共料不足仍可取消/);
assert.match(panel, /料费待补/);
assert.doesNotMatch(panel, /不能取消|不可泄露订单|hidden-order|XS<可见>/);
assert.match(panel, /XS&lt;可见&gt;/);
assert.match(panel, /其他成员用料 · 2\.000g/);
assert.equal((panel.match(/recovery-change-open-order/g) || []).length, 1);
assert.equal((panel.match(/recovery-change-open-lock/g) || []).length, 1);
await h.run(`openRecoveryCancel('${ID}')`);
const html = h.nodes.get('#recovery-change-dialog').innerHTML;
for (const text of [
'XS&lt;可见&gt;',
'锁价可见',
'1.000g',
'0.500g',
'其他成员用料',
'公共料不足仍可取消',
'料费待补',
'关联用料自动重算',
])
assert.ok(html.includes(text), text);
assert.doesNotMatch(html, /不能取消|修改时不能|不可泄露订单|hidden-order/);
h.smallForm('recovery-cancel-form', { reason: '录入重复,核对后取消', verified: true });
h.run('finishRecoveryChangeSave=async function(url,input,result){__finished={url,input,result};};');
h.calls.length = 0;
await h.run('submitRecoveryCancel(__form)');
assert.equal(h.calls[0].url, '/api/recoveries/' + ID + '/cancel');
assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), {
revision: 3,
reason: '录入重复,核对后取消',
verified: true,
});
}
});
test('取消仍遵守服务端权限和待审状态,不能用已有用料放开重复申请', async () => {
for (const extra of [
{
status: 'cancelled',
permissions: {
canEdit: false,
canCancel: false,
canDirect: false,
requiresApproval: false,
reason: '本单已经取消',
},
},
{
pending: request({ action: 'cancel', after: null }),
permissions: {
canEdit: false,
canCancel: false,
canDirect: false,
requiresApproval: true,
reason: '本单有待审批更正',
},
},
]) {
const h = harness();
h.context.__detail = detail('owner', {
blockedUsages: [{ number: 'XS已用', orderId: 'own-order', mg: 1000 }],
...extra,
});
h.run('recoveryDetailEdit=__detail');
assert.doesNotMatch(h.run('recoveryDetailChangeActionsHTML(__detail.record)'), /recovery-edit-cancel/);
await h.run(`openRecoveryCancel('${ID}')`);
assert.equal(h.run('recoveryReviewEntry'), null);
assert.match(h.nodes.get('#recovery-change-dialog').innerHTML, /暂不能取消/);
assert.equal(h.calls.filter(call => call.data).length, 0);
}
});
test('取消须原因与确认,历史助理自动申请,取消响应不会重建新单', async () => {
const h = harness('assistant');
h.context.__detail = detail('assistant', { inputs: { date: OLD } });
await h.run(`openRecoveryCancel('${ID}')`);
assert.match(h.nodes.get('#recovery-change-dialog').innerHTML, /提交取消申请/);
const { fields } = h.smallForm('recovery-cancel-form', { reason: '', verified: false });
await assert.rejects(h.run('submitRecoveryCancel(__form)'), /取消原因/);
fields.reason.value = '录入重复';
await assert.rejects(h.run('submitRecoveryCancel(__form)'), /勾选确认/);
fields.verified.checked = true;
h.calls.length = 0;
h.run('finishRecoveryChangeSave=async function(url,input,result){__finished={url,input,result};};');
await h.run('submitRecoveryCancel(__form)');
assert.equal(h.calls[0].url, '/api/recoveries/' + ID + '/cancel');
assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), { revision: 3, reason: '录入重复', verified: true });
});
test('审批显示完整前后旧料、费用付款人与实际净额,同意须确认,驳回须意见', async () => {
const h = harness();
await h.review();
const html = h.nodes.get('#recovery-change-dialog').innerHTML;
for (const text of [
'旧戒指',
'旧手链',
'4.990',
'第一项收费',
'第二项收费',
'第二笔费用',
'小昊',
'原账利润',
'实际收客户',
])
assert.ok(html.includes(text), text);
const { fields } = h.reviewForm('approve');
await assert.rejects(h.run('submitRecoveryDecision(__form)'), /勾选确认/);
fields.verified.checked = true;
fields.note.value = '已核对';
h.run('finishRecoveryChangeSave=async function(url,input,result){__finished={url,input,result};};');
h.calls.length = 0;
await h.run('submitRecoveryDecision(__form)');
assert.equal(h.calls[0].url, '/api/recovery-changes/' + RID + '/approve');
assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), { revision: 1, note: '已核对', verified: true });
const reject = h.reviewForm('reject');
await assert.rejects(h.run('submitRecoveryDecision(__form)'), /驳回须填写/);
reject.fields.note.value = '请核实实际重量';
await h.run('submitRecoveryDecision(__form)');
assert.equal(h.calls[1].url, '/api/recovery-changes/' + RID + '/reject');
});
test('过期申请只能驳回,助理不能审批;取消对照显示冲正且不把未提供利润当0', async () => {
const h = harness();
await h.review({ stale: true, canApprove: false });
assert.ok(!h.nodes.get('#recovery-change-dialog').innerHTML.includes('data-kind="approve"'));
assert.throws(() => h.run("showRecoveryDecision('approve')"), /已有变动/);
const assistant = harness('assistant');
await assistant.review({ canApprove: false });
assert.throws(() => assistant.run("showRecoveryDecision('reject')"), /店主账号/);
h.context.__request = request({
action: 'cancel',
after: null,
summary: {
...request().summary,
blockedUsages: [
{ orderId: 'visible-order', number: 'XS<已用>', mg: 3000 },
{ number: '不应展示', orderId: 'private-order', anonymous: true, mg: 500 },
],
},
});
const html = h.run('recoveryChangeComparisonHTML(__request)');
assert.match(html, /取消后/);
assert.match(html, /冲正原库存及关联购料/);
assert.match(html, /公共料不足仍可取消/);
assert.match(html, /料费待补/);
assert.match(html, /XS&lt;已用&gt; · 3\.000g/);
assert.match(html, /其他成员用料 · 0\.500g/);
assert.doesNotMatch(html, /不应展示|private-order|不能取消|undefined|NaN/);
});
test('409保留修改草稿并禁旧版本,重新读取与核对前不允许重交', async () => {
const h = harness();
await h.open();
const { fields, submit, reload } = h.editForm({ customer: '未保存客户' });
h.run("api=async function(){const err=new Error('版本已有变动');err.status=409;err.confirmed=true;throw err;};");
await h.run('submitRecoveryEdit(__form)');
assert.equal(h.run('recoveryEditEntry.invalid'), true);
assert.equal(fields.customer.value, '未保存客户');
assert.equal(submit.disabled, true);
assert.equal(reload.disabled, false);
assert.equal(h.saved.has('mm-pending-' + h.user.id), false);
assert.equal(JSON.parse(h.saved.get('mm-recovery-edit-' + h.user.id + '-' + ID)).draft.customer, '未保存客户');
await assert.rejects(h.run('submitRecoveryEdit(__form)'), /重新读取/);
});
test('修改取消及审批断线恢复沿同一操作号与内容,不走新增回收', async () => {
for (const url of [
'/api/recoveries/' + ID + '/update',
'/api/recoveries/' + ID + '/cancel',
'/api/recovery-changes/' + RID + '/approve',
'/api/recovery-changes/' + RID + '/reject',
]) {
const h = harness();
h.context.__input = { revision: 3, reason: '核对', verified: true, note: '备注' };
h.run("api=async function(url,data,key){__calls.push({url,data,key});throw new Error('响应丢失');};");
await assert.rejects(h.run(`mutate('${url}',__input)`), /恢复原操作/);
const saved = JSON.parse(h.saved.get('mm-pending-' + h.user.id));
h.run(
'api=async function(url,data,key){__calls.push({url,data,key});return {};};finishRecoveryChangeSave=async function(url,input,result){__finished={url,input,result};};',
);
await h.click('retry');
assert.equal(h.calls.length, 2);
assert.equal(h.calls[1].key, saved.key);
assert.deepEqual(JSON.parse(JSON.stringify(h.calls[1].data)), saved.data);
assert.equal(h.json('__finished.url'), url);
assert.equal(h.saved.size, 0);
assert.ok(h.calls.every(call => call.url !== '/api/recoveries'));
}
});
test('列表跨日期读取数量,失败不显示0;前后文案与匿名来源转义', async () => {
const h = harness();
h.context.__request = request();
h.context.__request.before.customer = '<img src=x>';
h.context.__request.after.customer = '<script>新客户</script>';
h.context.__request.reason = '<b>原因</b>';
await h.run('loadRecoveryChangeCount()');
assert.equal(h.nodes.get('#recovery-changes-entry').textContent, '回收更正复核(1)');
await h.run('openRecoveryChanges()');
assert.match(h.nodes.get('#recovery-change-list').innerHTML, /&lt;img src=x&gt;/);
await h.review({ reason: '<b>原因</b>', before: inputs({ customer: '<img src=x>' }) });
const html = h.nodes.get('#recovery-change-dialog').innerHTML;
assert.ok(!html.includes('<img src=x>'));
assert.ok(!html.includes('<b>原因</b>'));
h.run("api=async function(){throw new Error('断线');};");
await h.run('loadRecoveryChangeCount()');
assert.equal(h.nodes.get('#recovery-changes-entry').textContent, '回收更正复核(读取失败)');
});
test('迟到读取、换号和关窗不会覆盖当前编辑或复核', async () => {
const h = harness(),
waiting = new Map();
h.context.__api = url => new Promise(resolve => waiting.set(url, resolve));
h.run('api=__api');
const first = h.run(`openRecoveryEdit('${ID}')`);
h.run(
"state={...state,user:{id:'new-user',role:'assistant',member:'assistant2'}};session={user:state.user};invalidateRecoveryChangeViews();",
);
waiting.get('/api/recoveries/' + ID + '/edit')(detail());
await first;
assert.equal(h.run('recoveryEditEntry'), null);
const close = harness();
close.context.__api = url => new Promise(resolve => waiting.set(url, resolve));
close.run('api=__api');
const reading = close.run(`openRecoveryChange('${RID}')`);
close.run('closeRecoveryChanges()');
waiting.get('/api/recovery-changes/' + RID)(request());
await reading;
assert.equal(close.run('recoveryReviewEntry'), null);
assert.equal(close.nodes.get('#recovery-change-dialog').open, false);
const cancel = harness();
cancel.context.__api = url => new Promise(resolve => waiting.set(url, resolve));
cancel.run('api=__api');
const cancelling = cancel.run(`openRecoveryCancel('${ID}')`);
cancel.run('closeRecoveryChanges()');
waiting.get('/api/recoveries/' + ID + '/edit')(detail());
await cancelling;
assert.equal(cancel.run('recoveryReviewEntry'), null);
assert.equal(cancel.nodes.get('#recovery-change-dialog').open, false);
});
test('编辑试算带原版本走专用只读接口,排除原耗用;创建继续原quote且不建待恢复操作', async () => {
const h = harness();
await h.open();
h.editForm({ material_source: 'pool', material_pool_id: OLD });
h.nodes.set('#recovery-quote-status', node());
h.nodes.set('#recovery-material-note', node());
h.run(
'api=async function(url,data,key){__calls.push({url,data,key});return {...recoveryCalculate(data),materialCost:77777};};',
);
h.calls.length = 0;
await h.run('loadRecoveryQuote(__form)');
assert.equal(h.calls[0].url, '/api/recoveries/' + ID + '/quote');
assert.equal(h.calls[0].data.revision, 3);
assert.equal(h.calls[0].data.verified, false);
assert.equal(h.calls[0].data.old_lines.length, 2);
assert.match(h.nodes.get('#recovery-material-note').textContent, /原单耗用已排除/);
assert.match(h.nodes.get('#recovery-material-note').textContent, /¥777\.77/);
assert.match(h.nodes.get('#recovery-quote-status').textContent, /结算已核对/);
assert.equal(h.saved.has('mm-pending-' + h.user.id), false);
h.run("__form.dataset.recoveryEdit='false';recoveryEditEntry=null");
await h.run('loadRecoveryQuote(__form)');
assert.equal(h.calls[1].url, '/api/recoveries/quote');
assert.equal(h.calls[1].data.revision, undefined);
});
test('迟到保存不重开旧单、不覆盖新编辑或当前列表日期,保存成功仍刷新汇总', async () => {
const h = harness();
await h.open();
h.editForm();
h.run(
"__view=captureRecoveryChangeView();recoveryEditEntry={...recoveryEditEntry,id:'another-recovery'};++recoveryEditRequest;Object.assign(recoveryGetFilters(),{from:'2026-11-04',date:'2026-11-04'});__refreshes=0;refresh=async function(){__refreshes++;};",
);
h.context.__result = { id: ID, applied: true, pending: false, recovery: { date: OLD } };
await h.run(`finishRecoveryChangeSave('/api/recoveries/${ID}/update',{date:'${OLD}'},__result,__view)`);
assert.equal(h.run('recoveryEditEntry.id'), 'another-recovery');
assert.equal(h.run('recoveryGetFilters().date'), D);
assert.deepEqual(h.json('__opened'), []);
assert.equal(h.run('__refreshes'), 1);
});
test('置换编辑用原单核对个人先用与公共补足,显示两段成本及余量而不混入公共均价', async () => {
const h = harness();
await h.open();
h.editForm({ material_source: 'pool', material_pool_id: OLD });
h.nodes.set('#recovery-quote-status', node());
h.nodes.set('#recovery-material-note', node());
const own = {
kind: 'personal_recovery',
member: 'assistant',
quantity: 5000,
amount: 450000,
averageRate: 90000,
allocations: [{ payer: 'owner', amount: 450000 }],
},
common = {
kind: 'public',
member: null,
quantity: 50,
amount: 5000,
averageRate: 100000,
allocations: [{ payer: 'assistant2', amount: 5000 }],
};
h.context.__sources = [own, common];
h.context.__balance = {
date: D,
member: 'assistant',
entries: [
{
lineIndex: 0,
poolId: OLD,
mg: 5050,
amount: 455000,
allocations: [...own.allocations, ...common.allocations],
materialSources: [own, common],
},
],
pools: [
{
poolId: OLD,
revision: 'balance-v1',
personalRemainingMg: 0,
personalRemainingAmount: 0,
publicRemainingMg: 1950,
publicRemainingAmount: 195000,
eligibleRemainingMg: 1950,
before: { personalRemainingMg: 5000, publicRemainingMg: 2000, eligibleRemainingMg: 7000 },
},
],
};
h.run(
"recoveryEditEntry.data.record.order_id='original-linked-order';api=async function(url,data){__calls.push({url,data});if(url==='/api/material-pools/quote')return __balance;return {...recoveryCalculate(data),member:data.member,materialCost:455000,exchange:{costMaterial:{materialSources:__sources}}};};",
);
h.calls.length = 0;
await h.run('loadRecoveryQuote(__form)');
assert.equal(h.calls[0].url, '/api/recoveries/' + ID + '/quote');
assert.equal(h.calls[1].url, '/api/material-pools/quote');
assert.equal(h.calls[1].data.orderId, 'original-linked-order');
const text = h.nodes.get('#recovery-material-note').textContent;
assert.match(text, /娜娜个人回收料 5\.000g · ¥4,500\.00/);
assert.match(text, /公共料 0\.050g · ¥50\.00/);
assert.match(text, /公共料 1\.950g/);
assert.match(text, /原单耗用已排除/);
assert.equal(h.saved.has('mm-pending-' + h.user.id), false);
});
test('多商品修改回填第一件与后续明细,外配不回退现货,审批对照含所有商品付款人', () => {
const h = harness(),
x = inputs().exchange,
products = [
{
name: '足金第一件',
quantity: '6',
pocket: '',
labor_mode: 'gram',
labor_rate: '30',
cost_labor: { mode: 'gram', rate: '5' },
cost_labor_payer: 'owner',
},
{
name: '足金第二件',
quantity: '14',
pocket: '金料',
labor_mode: 'total',
labor_rate: '100',
cost_labor: { mode: 'total', amount: '40' },
cost_labor_payer: 'assistant2',
},
];
h.context.__multi = inputs({ exchange: { ...x, products } });
const draft = h.json('recoveryEditDraft(__multi)');
assert.equal(draft.pocket, '');
assert.equal(draft.new_quantity, '6');
assert.equal(draft.labor_rate, '30');
assert.equal(draft.extra_products[0].new_quantity, '14');
assert.equal(draft.extra_products[0].labor_payer, 'assistant2');
h.context.__draft = { ...draft, verified: true };
const input = h.json('recoveryInput(__draft)');
assert.deepEqual(input.exchange.products, products);
h.context.__request = request({ before: inputs(), after: input });
const html = h.run('recoveryChangeComparisonHTML(__request)');
assert.match(html, /逐件置换商品/);
assert.match(html, /足金第二件/);
assert.match(html, /外配/);
assert.match(html, /小昊/);
});
test('逐件完整置换修改回填保留每件旧料、折旧、补金及独立料费来源', () => {
const h = harness(),
original = inputs(),
x = original.exchange;
h.context.__individual = {
...original,
exchange: {
...x,
items: [
{
old_lines: original.old_lines,
old_pocket: '找金',
buy_rate: '850',
buy_total: '0',
exchange: {
...x,
quantity: '15',
gold_price: '1000',
depreciation_weight: '10',
depreciation_rate: '10',
cost_material: { mode: 'pool', poolId: D },
},
},
{
old_lines: [{ name: '第二份旧料', incoming_weight: '20', melted_weight: '20', purity: '99' }],
old_pocket: '回收旧料',
buy_rate: '860',
buy_total: '6708',
exchange: {
...x,
name: '第二件',
quantity: '12',
pocket: '',
gold_price: '1100',
depreciation_weight: '12',
depreciation_rate: '5',
cost_material: { mode: 'gram', rate: '800' },
cost_material_payer: 'assistant2',
},
},
],
},
};
const draft = h.json('recoveryEditDraft(__individual)');
assert.equal(draft.independent_products, true);
assert.equal(draft.old_pocket, '找金');
assert.equal(draft.material_source, 'pool');
assert.equal(draft.extra_products[0].incoming_weight, '20');
assert.equal(draft.extra_products[0].depreciation_rate, '5');
assert.equal(draft.extra_products[0].material_rate, '800');
assert.equal(draft.extra_products[0].material_payer, 'assistant2');
assert.equal(draft.extra_products[0].pocket, '');
});
test('历史单件逐件单编辑转为共用旧料,可添加多件新货且保留原费用和寄存选择', () => {
const h = harness(),
original = inputs(),
item = {
old_lines: [{ name: 'Au旧料', incoming_weight: '10', melted_weight: '10', purity: '100' }],
old_pocket: '回收旧料',
surplus_mode: 'deposit',
surplus_memo: '原寄存备忘',
buy_rate: '0',
buy_total: '0',
exchange: { ...original.exchange, quantity: '8', depreciation_weight: '8' },
};
h.context.__single = { ...original, exchange: { ...original.exchange, items: [item] } };
const draft = h.json('recoveryEditDraft(__single)');
assert.equal(draft.independent_products, false);
assert.equal(draft.incoming_weight, '10');
assert.equal(draft.surplus_mode, 'deposit');
assert.equal(draft.surplus_memo, '原寄存备忘');
assert.equal(draft.extra_products.length, 0);
assert.equal(draft.charges.length, 2);
assert.equal(draft.fee_items.length, 2);
h.context.__draft = { ...draft, verified: true };
const input = h.json('recoveryInput(__draft)');
assert.equal(input.exchange.items, undefined);
assert.equal(input.old_lines.length, 1);
assert.equal(input.exchange.quantity, '8');
assert.equal(input.surplus_mode, 'deposit');
});