'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path'), vm = require('node:vm'); const { randomUUID } = require('node:crypto'), Calc = require('../public/calculations'), Fees = require('../public/fee-estimates'), Copy = require('../public/order-copy'); const D = '2026-10-22', ID = '11111111-1111-4111-8111-111111111111', CHARGE = '22222222-2222-4222-8222-222222222222', EXPENSE = '33333333-3333-4333-8333-333333333333'; function response(extra = {}) { const order = { id: ID, revision: 7, number: 'XS20261022001', paper_number: '20261022001', paper_date: D, date: D, customer: '原客户', internal_note: '测试内部备注', salesperson: '原开单人', status: 'delivered', payment_account: '助理微信', rounding_mode: 'yuan', total: 200000, directCost: 600, discount: 0, note: '原备注', payments: [], corrections: [], fee_items: [], lines: [ { name: '足金999', unit: 'g', quantity: 2000, sale: 200000, cost: 180000, costMaterial: { mode: 'gram', rate: 90000 }, charges: [{ id: CHARGE, name: '包装', amount: 0 }], }, ], }; const inputs = { id: ID, revision: 7, date: D, fees_date: D, customer: order.customer, internal_note: '测试内部备注', salesperson: order.salesperson, payment_account: '助理微信', rounding_mode: 'yuan', discount: '0', note: order.note, fee_auto_initialized: true, fee_items: [ { key: 'manual:' + EXPENSE, expense_id: EXPENSE, date: '2026-10-21', note: '快递费', amount: '6.00', payer: 'assistant', status: 'estimated', edited: true, }, ], lines: [ { name: '足金999', unit: 'g', quantity: '2.000', pocket: '现货', payer: 'owner', pricingMode: 'auto', goldPrice: '980.00', laborRate: '20.00', laborMode: 'gram', pieces: '1', costParts: { material: '1800.00', labor: '0', accessories: '0', other: '0' }, costMaterial: { mode: 'gram', rate: '900.00' }, costLabor: { mode: 'total' }, costPayers: { material: 'owner', labor: 'assistant' }, charges: [{ id: CHARGE, name: '包装', amount: '0' }], }, ], }; return { eligible: true, financialEditable: true, revision: 7, inputs, order, ...extra }; } function harness(initial = response()) { const saved = new Map(), calls = [], handlers = {}, nodes = new Map(), toasts = []; const dialog = { open: true, close() { this.open = false; }, showModal() { this.open = true; }, }; nodes.set('#order-dialog', dialog); nodes.set('#main', { innerHTML: '' }); nodes.set('#pending', { hidden: true, innerHTML: '' }); nodes.set('#order-error', { innerHTML: '' }); const context = vm.createContext({ LedgerCalc: Calc, FeeEstimates: Fees, OrderCopy: Copy, crypto: { randomUUID }, setInterval() {}, setTimeout() {}, clearTimeout() {}, console, document: { addEventListener(type, handler) { (handlers[type] ??= []).push(handler); }, querySelector(selector) { return nodes.get(selector) || null; }, querySelectorAll() { return []; }, }, window: { confirm() { return context.__confirm; }, scrollTo() {}, }, 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() {}, }, __response: initial, __calls: calls, __confirm: true, __toasts: toasts, __rendered: 0, __form: null, __draft: null, __finished: null, __originalRender: null, __originalMutate: null, }); vm.runInContext("let createMode='direct';", context); for (const file of [ 'order-templates-ui.js', 'material-pools-ui.js', 'order-edit-ui.js', 'order-changes-ui.js', 'app.js', ]) vm.runInContext( fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, ''), context, ); vm.runInContext( `session={user:{id:'edit-user',name:'麦麦',role:'owner'}};state={user:session.user,today:'${D}',pockets:['现货','金料']};tab='orders';api=async function(url,data,key){__calls.push({url,data,key});return __response;};toast=function(message,error){__toasts.push({message,error});};refresh=async function(){__calls.push({refresh:true});};openOrder=async function(id){__calls.push({open:id});};__originalRender=renderOrderEditForm;renderOrderEditForm=function(){__rendered++;if(__form)__form.querySelector('[name="edit_verified"]').checked=orderEditEntry.verified;rememberOrderEditDraft(orderEditEntry.inputs);};`, context, ); const run = code => vm.runInContext(code, context), json = code => JSON.parse(JSON.stringify(run(code))); function form(kind = 'full', values = {}) { const fieldValues = { customer: '修改客户', internal_note: '测试内部备注', salesperson: '张', note: '修改后的备注', edit_reason: '核对实物后更正', edit_verified: true, ...values, }; const fields = Object.fromEntries( Object.entries(fieldValues).map(([name, value]) => [ name, { name, value: typeof value === 'boolean' ? 'on' : value, checked: value === true, disabled: false, dataset: {}, }, ]), ); const controls = Object.values(fields), submit = { disabled: false, dataset: {} }, retry = { disabled: false, dataset: { action: 'retry' } }, f = { id: kind === 'full' ? 'order-form' : 'order-edit-meta-form', dataset: kind === 'full' ? { orderEdit: 'true' } : kind === 'lock' ? { priceLockEdit: 'true' } : {}, querySelector(selector) { if (selector === '[data-order-edit-submit]') return submit; const name = selector.match(/\[name="([^"]+)"\]/)?.[1]; return fields[name] || null; }, querySelectorAll(selector) { if (selector === '[name="lock_extra_source"]') return []; if (selector.startsWith('button[')) return [retry]; return selector.includes('button') ? [...controls, submit, retry] : controls; }, }; nodes.delete('#order-form[data-order-edit="true"]'); nodes.delete('#order-form'); nodes.delete('#order-edit-meta-form'); if (kind === 'full') nodes.set('#order-form', f); nodes.set(kind === 'full' ? '#order-form[data-order-edit="true"]' : '#order-edit-meta-form', f); context.__form = f; return { f, fields, submit, retry }; } return { context, saved, calls, handlers, nodes, toasts, run, json, form, key: 'mm-order-edit-edit-user-' + ID, normal: 'mm-draft-edit-user', active: 'mm-order-edit-active-edit-user', }; } function prepare(h, result = response()) { h.context.__response = result; h.run(`useOrderEditResponse('${ID}',__response,null);tab='order-edit';`); h.context.__draft = JSON.parse(JSON.stringify(result.inputs)); h.run('collectDraft=function(){return __draft;};updateTotal=function(){};loadMaterialPoolChoices=function(){};'); } function lockResponse(source = 'pool') { const result = response({ requiresApproval: false, directEditDate: D }); result.order.price_lock_id = '44444444-4444-4444-8444-444444444444'; result.order.total = 300000; result.order.delivered_date = D; Object.assign(result.order.lines[0], { quantity: 2500, goldPrice: 110000, laborRate: 10000, unit: 'g', sale: 300000, costParts: { material: 215001, labor: 2500, accessories: 200, other: 0 }, }); Object.assign(result.inputs.lines[0], { quantity: '2.500', sale: '3000.00', goldPrice: '1100.00', laborRate: '100.00', costParts: { material: '2150.01', labor: '25.00', accessories: '2.00', other: '0.00' }, costMaterial: { mode: 'total' }, costLabor: { mode: 'gram', rate: '10.00' }, costPayers: { material: 'owner', labor: 'assistant' }, payer: 'owner', }); result.inputs.price_lock_material = { source, rate: '850.00', payer: 'owner', verified: true }; result.inputs.price_lock_extra_material = { rate: '900.00', payer: 'assistant2', verified: true }; result.priceLock = { id: result.order.price_lock_id, date: '2026-10-20', materialSource: source, canSwitchToManual: source === 'pool', extraMg: 500, financeRequiresApproval: true, approvalReason: '涉及历史锁价购料或料池,请提交店主复核。', }; return result; } function lockForm(h, values = {}) { const input = h.context.__response.inputs, line = input.lines[0], material = input.price_lock_material, extra = input.price_lock_extra_material; return h.form('lock', { date: input.date, fees_date: input.fees_date, lock_material_source: material.source, lock_material_rate: material.rate, lock_material_payer: material.payer, lock_material_verified: material.verified, lock_extra_rate: extra?.rate || '', lock_extra_payer: extra?.payer || '', lock_extra_verified: extra?.verified || false, lock_cost_labor_mode: line.costLabor.mode, lock_cost_labor_rate: line.costLabor.rate || '', lock_cost_labor_total: line.costParts.labor, lock_cost_labor_payer: line.costPayers.labor, lock_cost_accessories: line.costParts.accessories, lock_cost_other: line.costParts.other, lock_cost_payer: line.payer, ...values, }); } test('修改沿用原客户日期单号与收费身份,独立草稿保留实际费用日期和普通开单草稿', () => { const h = harness(); prepare(h); h.saved.set(h.normal, '{"customer":"普通开单仍在填写"}'); const { fields } = h.form(); h.context.__draft.lines[0].quantity = '3.125'; h.run('rememberOrderEditDraft(__draft)'); const saved = JSON.parse(h.saved.get(h.key)); assert.equal(saved.id, ID); assert.equal(saved.revision, 7); assert.equal(saved.inputs.customer, '原客户'); assert.equal(saved.inputs.date, D); assert.equal(saved.inputs.paper_number, '20261022001'); assert.equal(saved.inputs.lines[0].quantity, '3.125'); assert.equal(saved.inputs.lines[0].charges[0].id, CHARGE); assert.equal(saved.inputs.fee_items[0].expense_id, EXPENSE); assert.equal(saved.inputs.fee_items[0].date, '2026-10-21'); assert.equal(saved.reason, fields.edit_reason.value); assert.equal(saved.verified, true); assert.equal(h.saved.get(h.normal), '{"customer":"普通开单仍在填写"}'); assert.equal(h.saved.get(h.active), ID); }); test('锁价交付修改有独立日期成本区,销售条件只读,接口缺原锁成本信息禁止进入', () => { const result = lockResponse(), h = harness(result); prepare(h, result); h.context.__lock = result; assert.doesNotThrow(() => h.run(`validateOrderEditResponse('${ID}',__lock)`)); const html = h.run('priceLockOrderEditHTML(orderEditEntry)'); for (const text of [ 'data-price-lock-edit="true"', '交付日期', '2026-10-20', 'lock_material_source', '改为手填原锁料价', 'lock_cost_labor_rate', 'lock_cost_labor_payer', 'lock_extra_rate', 'lock_extra_payer', '更正后成本预览', ]) assert.ok(html.includes(text), text); for (const name of ['quantity', 'goldPrice', 'laborRate', 'payment_method', 'discount']) assert.ok(!html.includes('name="' + name + '"'), name); assert.ok(!html.includes('data-action="add-line"')); h.context.__lock = { ...result, priceLock: { ...result.priceLock, extraMg: undefined } }; assert.throws(() => h.run(`validateOrderEditResponse('${ID}',__lock)`), /未完整/); }); test('锁价单只改交付日保留原锁料池分币、补重、售价与收付款,成本预览不换新日料池', async () => { const result = lockResponse(), h = harness(result); prepare(h, result); lockForm(h, { date: '2026-10-21' }); const value = h.json('collectPriceLockOrderEdit(__form)'), preview = h.json('priceLockOrderEditPreview(collectPriceLockOrderEdit(__form))'); assert.equal(preview.material, 215001); assert.equal(preview.total, 218301); assert.equal(preview.profit, 81699); assert.equal(value.price_lock_material.source, 'pool'); assert.equal(value.lines[0].costParts.material, '2150.01'); for (const key of ['quantity', 'sale', 'goldPrice', 'laborRate', 'pocket']) assert.equal(value.lines[0][key], result.inputs.lines[0][key]); assert.equal(value.payment_account, result.inputs.payment_account); assert.deepEqual(value.fee_items, result.inputs.fee_items); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/edit'); assert.equal(h.calls[0].data.date, '2026-10-21'); assert.equal(h.calls[0].data.price_lock_extra_material.payer, 'assistant2'); assert.equal(h.calls[0].data.lines[0].quantity, '2.500'); }); test('池料改手填清付款人与确认,重新核实后释放来源结构随草稿和payload保留', async () => { const result = lockResponse(), h = harness(result); prepare(h, result); const { fields } = lockForm(h, { lock_material_source: 'manual' }); h.run("syncPriceLockOrderEdit('lock_material_source')"); assert.equal(fields.lock_material_payer.value, ''); assert.equal(fields.lock_material_verified.checked, false); assert.equal(fields.edit_verified.checked, false); fields.edit_verified.checked = true; await assert.rejects(h.run('submitOrderEdit(__form)'), /请选择原锁料费/); fields.lock_material_payer.value = 'assistant2'; fields.lock_material_rate.value = '860.00'; await assert.rejects(h.run('submitOrderEdit(__form)'), /勾选确认/); fields.lock_material_verified.checked = true; h.run('rememberOrderEditDraft()'); assert.equal(JSON.parse(h.saved.get(h.key)).inputs.price_lock_material.source, 'manual'); assert.equal(h.run('priceLockOrderEditPreview(collectPriceLockOrderEdit(__form)).material'), 217000); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data.price_lock_material)), { source: 'manual', rate: '860.00', payer: 'assistant2', verified: true, }); assert.equal( h.calls[0].data.lines[0].costParts.material, '2150.01', '原行料费由服务端专用结构覆盖,前端不伪造池分摊', ); }); test('助理同日纯资料仍可直存,实际改历史锁料相关日期或成本才切申请,格式化金额不误触', async () => { const result = lockResponse(), h = harness(result); prepare(h, result); h.run("session.user.role='assistant';state.user.role='assistant';"); const { fields } = lockForm(h); h.run('updateOrderEditApprovalMode()'); assert.equal(h.run('orderEditEntry.requiresApproval'), false); assert.equal(h.run('priceLockEditFinancialChanged(orderEditEntry,collectPriceLockOrderEdit(__form))'), false); fields.lock_cost_other.value = '0'; h.run('updateOrderEditApprovalMode()'); assert.equal(h.run('orderEditEntry.requiresApproval'), false); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(){};finishOrderChangeSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/edit'); fields.lock_cost_labor_mode.value = 'total'; fields.lock_cost_labor_total.value = '26.00'; h.run('updateOrderEditApprovalMode()'); assert.equal(h.run('orderEditEntry.requiresApproval'), true); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[1].url, '/api/orders/' + ID + '/change'); assert.equal(h.calls[1].data.lines[0].costParts.labor, '26.00'); }); test('原手填锁料不能改任意料池;原锁日前、未来日期、超精度料价或漏付款人不得提交', async () => { const result = lockResponse('manual'), h = harness(result); prepare(h, result); const { fields } = lockForm(h); fields.lock_material_source.value = 'pool'; await assert.rejects(h.run('submitOrderEdit(__form)'), /来源已变化/); fields.lock_material_source.value = 'manual'; for (const date of ['2026-10-19', '2026-10-23', '2026-02-30']) { fields.date.value = date; await assert.rejects(h.run('submitOrderEdit(__form)'), /交付日期/); } fields.date.value = D; fields.lock_material_rate.value = '850.001'; await assert.rejects(h.run('submitOrderEdit(__form)'), /小数|格式|两位/); fields.lock_material_rate.value = '850.00'; fields.lock_cost_labor_payer.value = ''; await assert.rejects(h.run('submitOrderEdit(__form)'), /实际付款人/); assert.equal(h.calls.length, 0); }); test('锁价补重和克工费预览按整数分舍入,改变补重付款信息清核实', () => { const result = lockResponse(), h = harness(result); prepare(h, result); const { fields } = lockForm(h, { lock_extra_rate: '901.01', lock_cost_labor_rate: '12.34' }); const preview = h.json('priceLockOrderEditPreview(collectPriceLockOrderEdit(__form))'); assert.equal(preview.material, 215052); assert.equal(preview.labor, 3085); assert.equal(preview.total, 218937); h.run("syncPriceLockOrderEdit('lock_extra_rate')"); assert.equal(fields.lock_extra_verified.checked, false); assert.equal(fields.edit_verified.checked, false); }); test('锁价成本409保留手填草稿并禁旧版本,审批差异显示原锁来源料价付款人与补重', async () => { const result = lockResponse(), h = harness(result); prepare(h, result); lockForm(h, { lock_material_source: 'manual', lock_material_rate: '860.00', lock_material_payer: 'assistant2', lock_material_verified: true, }); h.run("mutate=async function(){const err=new Error('订单有新变动');err.status=409;throw err;};"); await h.run('submitOrderEdit(__form)'); assert.equal(h.run('orderEditEntry.conflicted'), true); const saved = JSON.parse(h.saved.get(h.key)); assert.equal(saved.inputs.price_lock_material.source, 'manual'); assert.equal(saved.inputs.price_lock_material.payer, 'assistant2'); assert.equal(saved.verified, false); h.context.__before = { priceLockCosts: { date: '2026-10-20', materialSource: 'pool', buyRate: 85000, buyPayer: 'owner', materialAmount: 170001, extraRate: 90000, extraPayer: 'assistant2', }, }; h.context.__after = { priceLockCosts: { date: '2026-10-20', materialSource: 'manual', buyRate: 86000, buyPayer: 'assistant2', materialAmount: 172000, extraRate: 90101, extraPayer: 'owner', }, }; const html = h.run('orderChangePriceLockCostsHTML(__before,__after)'); for (const text of [ '锁价购料成本', '原锁料池', '手填原锁料价', '850.00', '860.00', '原锁料费付款人', '小昊', '补重进货料价', '901.01', ]) assert.ok(html.includes(text), text); }); test('打开修改只读GET,刷新恢复同一份修改草稿;提交未确认时阻止新修改', async () => { const h = harness(), saved = { id: ID, revision: 7, inputs: response().inputs, reason: '之前填写原因', verified: true }; saved.inputs.customer = '未保存的客户'; h.saved.set(h.key, JSON.stringify(saved)); h.saved.set(h.normal, '保留普通草稿'); await h.run(`startOrderEdit('${ID}')`); assert.deepEqual( h.calls.map(row => row.url), ['/api/orders/' + ID + '/edit'], ); assert.equal(h.json('orderEditEntry.inputs.customer'), '未保存的客户'); assert.equal(h.run('tab'), 'order-edit'); assert.equal(h.saved.get(h.normal), '保留普通草稿'); h.run("orderEditEntry=null;tab='create';restoreOrderEditTab()"); assert.equal(h.run('tab'), 'order-edit'); await h.run('renderOrderEdit()'); assert.equal(h.json('orderEditEntry.reason'), '之前填写原因'); h.saved.set('mm-pending-edit-user', '{"url":"/api/orders/issue"}'); const before = h.calls.length; await assert.rejects(h.run(`startOrderEdit('${ID}')`), /恢复原操作/); assert.equal(h.calls.length, before); }); test('修改页加载期间换页或账户改变不覆盖草稿,读取失败不清草稿', async () => { const h = harness(); h.saved.set(h.normal, '普通草稿'); h.run("api=async function(){tab='stock';return __response;}"); await h.run(`startOrderEdit('${ID}')`); assert.equal(h.run('orderEditEntry'), null); assert.equal(h.saved.get(h.normal), '普通草稿'); h.run("api=async function(){throw new Error('读取失败');}"); await assert.rejects(h.run(`startOrderEdit('${ID}')`), /读取失败/); assert.equal(h.run('orderEditLoading'), false); assert.equal(h.saved.get(h.normal), '普通草稿'); }); test('取消修改只回原单详情,已填修改仍可再次打开且不发mutation', async () => { const h = harness(); prepare(h); h.form(); h.saved.set(h.normal, '保留普通草稿'); h.context.__draft.lines[0].quantity = '3.000'; await h.run('cancelOrderEdit()'); assert.equal(h.saved.get(h.active), undefined); assert.equal(JSON.parse(h.saved.get(h.key)).inputs.lines[0].quantity, '3.000'); assert.equal(h.saved.get(h.normal), '保留普通草稿'); assert.equal( h.calls.some(row => row.data), false, ); assert.equal(h.calls.at(-1).open, ID); }); test('修改原因与核实为必填;普通整单提交edit接口及原revision,金额联动沿用开单', async () => { const h = harness(); prepare(h); const { fields } = h.form(); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(input,result,id){__finished={input,result,id};};', ); fields.edit_reason.value = ''; await assert.rejects(h.run('submitOrderEdit(__form)'), /修改原因/); fields.edit_reason.value = '实称克重改为3.125g'; fields.edit_verified.checked = false; await assert.rejects(h.run('submitOrderEdit(__form)'), /核实/); assert.equal(h.calls.length, 0); fields.edit_verified.checked = true; h.context.__draft.lines[0].quantity = '3.125'; await h.run('submitOrderEdit(__form)'); assert.equal(h.calls.length, 1); const call = h.calls[0]; assert.equal(call.url, '/api/orders/' + ID + '/edit'); assert.equal(call.data.id, ID); assert.equal(call.data.revision, 7); assert.equal(call.data.verified, true); assert.equal(call.data.reason, '实称克重改为3.125g'); assert.equal(Calc.sale(call.data.lines[0]).sale, 312500); assert.equal(Calc.purchaseCosts(call.data.lines[0]).parts.material, 281250); assert.equal(h.json('__finished.id'), ID); }); test('锁价、取消、退货订单仅提交资料,简洁表单不出现财务输入或模板入口', async () => { for (const status of ['delivered', 'returned', 'cancelled', 'confirmed']) { const result = response({ financialEditable: false }); result.order.status = status; result.reason = status === 'delivered' ? '锁价单本次仅支持修改客户、开单人和备注' : '仅修改基本资料'; const h = harness(result); prepare(h, result); h.form('meta'); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.deepEqual(Object.keys(h.calls[0].data).sort(), [ 'customer', 'internal_note', 'note', 'reason', 'revision', 'salesperson', 'verified', ]); assert.equal(h.calls[0].data.customer, '修改客户'); h.nodes.delete('#order-edit-meta-form'); h.run('rememberOrderEditDraft=function(){};__originalRender()'); const html = h.nodes.get('#main').innerHTML; assert.ok(html.includes('id="order-edit-meta-form"')); assert.ok(html.includes('name="customer"')); assert.ok(html.includes('name="edit_reason"')); assert.ok(!html.includes('name="quantity"')); assert.ok(!html.includes('name="payment_method"')); assert.ok(!html.includes('order-template')); } }); test('版本冲突和重新打开均保留用户输入;核对当前订单后才使用新版本,复核框重新清空', async () => { const h = harness(); prepare(h); h.form(); h.context.__draft.customer = '我的修改'; h.context.__draft.lines[0].quantity = '3.000'; h.run("mutate=async function(){const err=new Error('订单已有新记录');err.status=409;throw err;};"); await h.run('submitOrderEdit(__form)'); assert.equal(h.run('orderEditEntry.conflicted'), true); assert.equal(h.run('orderEditEntry.revision'), 7); assert.equal(JSON.parse(h.saved.get(h.key)).inputs.lines[0].quantity, '3.000'); h.context.__response = { ...response(), revision: 8, order: { ...response().order, revision: 8, customer: '他人修改' }, }; await h.run(`reloadOrderEdit('${ID}')`); assert.equal(h.run('orderEditEntry.conflicted'), true); assert.equal(h.run('orderEditEntry.revision'), 7); assert.equal(h.run('orderEditEntry.inputs.customer'), '我的修改'); assert.equal(h.run('orderEditEntry.latest.order.customer'), '他人修改'); await h.run(`reloadOrderEdit('${ID}','keep')`); assert.equal(h.run('orderEditEntry.conflicted'), false); assert.equal(h.run('orderEditEntry.revision'), 8); assert.equal(h.run('orderEditEntry.inputs.customer'), '我的修改'); assert.equal(h.run('orderEditEntry.verified'), false); }); test('多人变更会再次要求核对;取消改用当前内容不丢草稿', async () => { const h = harness(); prepare(h); h.form(); h.context.__draft.customer = '我的草稿'; h.run('rememberOrderEditDraft(__draft);orderEditEntry.conflicted=true;orderEditEntry.latest={revision:8};'); h.context.__response = { ...response(), revision: 9, order: { ...response().order, revision: 9 } }; await h.run(`reloadOrderEdit('${ID}','keep')`); assert.equal(h.run('orderEditEntry.conflicted'), true); assert.equal(h.run('orderEditEntry.revision'), 7); assert.equal(h.run('orderEditEntry.latest.revision'), 9); h.context.__confirm = false; await h.run(`reloadOrderEdit('${ID}','reset')`); assert.equal(h.run('orderEditEntry.inputs.customer'), '我的草稿'); assert.equal(JSON.parse(h.saved.get(h.key)).inputs.customer, '我的草稿'); }); test('断线恢复复用原修改操作号,路由到修改成功处理,不开第二张单', async () => { const h = harness(); h.run( "__originalMutate=mutate;api=async function(url,data,key){__calls.push({url,data,key});throw new Error('断线');};", ); const input = { revision: 7, reason: '更正', verified: true }; h.context.__input = input; await assert.rejects(h.run(`mutate('/api/orders/${ID}/edit',__input)`), /恢复原操作/); const pending = JSON.parse(h.saved.get('mm-pending-edit-user')); assert.equal(pending.url, '/api/orders/' + ID + '/edit'); h.run( "api=async function(url,data,key){__calls.push({url,data,key});return {id:'" + ID + "'};};finishOrderEditSave=async function(input,result,id){__finished={input,result,id};};", ); const b = { dataset: { action: 'retry' }, closest() { return null; }, }; for (const handler of h.handlers.click) await handler({ target: { closest() { return b; }, }, }); assert.equal(h.calls.length, 2); assert.equal(h.calls[1].key, pending.key); assert.equal(JSON.stringify(h.calls[1].data), JSON.stringify(h.calls[0].data)); assert.equal(h.json('__finished.id'), ID); assert.equal(h.saved.get('mm-pending-edit-user'), undefined); assert.ok(h.calls.every(row => row.url !== '/api/orders/issue')); }); test('每日料价编辑预览抵扣原单耗用,普通开单不抵扣', () => { const result = response(); result.order.lines[0].costMaterial = { mode: 'pool', poolId: D }; const h = harness(result); prepare(h, result); assert.equal(h.run(`orderEditPoolUsedMg({id:'${D}',usedMg:5000})`), 3000); assert.equal(h.run("orderEditPoolUsedMg({id:'2026-10-21',usedMg:5000})"), 5000); h.run("tab='create'"); assert.equal(h.run(`orderEditPoolUsedMg({id:'${D}',usedMg:5000})`), 5000); }); test('完整修改页沿用原号,保存与取消文案明确,模板不能覆盖编辑表单', async () => { const h = harness(); prepare(h); h.run('rememberOrderEditDraft=function(){};__originalRender()'); const html = h.nodes.get('#main').innerHTML; assert.ok(html.includes('data-order-edit="true"')); assert.ok(html.includes('保存修改')); assert.ok(html.includes('取消修改')); assert.ok(html.includes('原纸单编号')); assert.ok(html.includes('name="quantity"')); assert.ok(html.includes('name="cost-materialRate"')); assert.ok(!html.includes('生成销售单据')); assert.ok(!html.includes('order-template-panel')); h.form(); h.context.__select = {}; await assert.rejects(h.run("applyOrderTemplate('template',__select)"), /不能套用模板/); assert.throws(() => h.run('showOrderTemplateDialog("new")'), /不能保存开单模板/); }); test('助理完整编辑走修改申请接口,保留整单payload且页面明确原单未生效', async () => { const h = harness(); h.run("session.user.role='assistant';state.user.role='assistant'"); prepare(h, response({ requiresApproval: true })); h.form(); h.context.__draft.lines[0].quantity = '3.125'; h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderChangeSave=async function(url,input,result){__finished={url,input,result};};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/change'); assert.equal(h.calls[0].data.revision, 7); assert.equal(h.calls[0].data.lines[0].quantity, '3.125'); assert.equal(h.calls[0].data.verified, true); assert.equal(h.json('__finished.url'), '/api/orders/' + ID + '/change'); h.run('rememberOrderEditDraft=function(){};__originalRender()'); const html = h.nodes.get('#main').innerHTML; for (const text of ['申请修改订单', '提交修改申请', '待批期间仍按原订单计账']) assert.ok(html.includes(text), text); assert.ok(!html.includes('>保存修改<')); }); test('助理锁价退货作废与旧单metadata也只提交申请,原财务字段不混入payload', async () => { for (const status of ['delivered', 'returned', 'cancelled', 'draft', 'confirmed']) { const h = harness(); h.run("session.user.role='assistant';state.user.role='assistant'"); const result = response({ requiresApproval: true, financialEditable: false }); result.order.status = status; prepare(h, result); h.form('meta'); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderChangeSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/change'); assert.deepEqual(Object.keys(h.calls[0].data).sort(), [ 'customer', 'internal_note', 'note', 'reason', 'revision', 'salesperson', 'verified', ]); } }); test('助理当天编辑根据服务器新权限与目标日期切换,旧版或不一致响应保守走审批', async () => { const h = harness(); h.run("session.user.role='assistant';state.user.role='assistant'"); const result = response({ directEditDate: D, requiresApproval: false }); prepare(h, result); const { fields, f } = h.form('full', { date: D }); h.run('updateOrderEditApprovalMode()'); assert.equal(h.run('orderEditEntry.requiresApproval'), false); assert.match(h.run('orderEditReviewHTML(orderEditEntry)'), />保存修改 { for (const [source, target, financialEditable, route] of [ [D, '2026-10-21', true, 'change'], ['2026-10-21', D, true, 'change'], [D, D, false, 'edit'], ]) { const result = response({ directEditDate: D, requiresApproval: source !== D, financialEditable }); result.order.date = source; result.inputs.date = target; const h = harness(result); h.run("session.user.role='assistant';state.user.role='assistant'"); prepare(h, result); h.form(financialEditable ? 'full' : 'meta', { date: target }); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderChangeSave=async function(){};finishOrderEditSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/' + route); } }); test('跨午夜直存403保留完整草稿清核实,转申请按钮后重新确认才提交审批', async () => { const h = harness(); h.run("session.user.role='assistant';state.user.role='assistant'"); prepare(h, response({ directEditDate: D, requiresApproval: false })); const { fields } = h.form('full', { date: D }); h.context.__draft.customer = '跨夜仍保留客户'; h.context.__draft.lines[0].quantity = '3.125'; h.run( "mutate=async function(url,data){__calls.push({url,data});const err=new Error('其他日期请提交修改申请');err.status=403;throw err;};", ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls.length, 1); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/edit'); assert.equal(h.run('orderEditEntry.requiresApproval'), true); assert.equal(fields.edit_verified.checked, false); assert.equal(fields.customer.disabled, false); const saved = JSON.parse(h.saved.get(h.key)); assert.equal(saved.inputs.customer, '跨夜仍保留客户'); assert.equal(saved.inputs.lines[0].quantity, '3.125'); assert.equal(saved.inputs.date, D); assert.equal(saved.verified, false); assert.match(h.nodes.get('#order-error').innerHTML, /填写内容已保留/); assert.match(h.run('orderEditReviewHTML(orderEditEntry)'), />提交修改申请 { for (const financialEditable of [true, false]) { const result = response({ financialEditable }); result.inputs.internal_note = '内部跟进\n<尺寸>'; result.order.internal_note = '内部跟进\n<尺寸>'; const h = harness(result); prepare(h, result); h.run('rememberOrderEditDraft=function(){};__originalRender()'); const html = h.nodes.get('#main').innerHTML; assert.match(html, /内部备注(客户不可见)/); assert.match( html, /name="internal_note" maxlength="500" rows="3"[^>]*>内部跟进\n<尺寸><\/textarea>|name="internal_note" maxlength="500" rows="3"[^>]*>内部跟进\n<尺寸><\/textarea>/, ); h.form(financialEditable ? 'full' : 'meta', { internal_note: '内部跟进\n<尺寸>' }); h.run( 'mutate=async function(url,data){__calls.push({url,data});return {id:orderEditEntry.id};};finishOrderEditSave=async function(){};', ); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls[0].data.internal_note, '内部跟进\n<尺寸>'); assert.notEqual(h.calls[0].data.internal_note, h.calls[0].data.note); h.context.__saved = { id: ID, revision: 7, inputs: { ...result.inputs, internal_note: '未保存内部记录' } }; h.run(`useOrderEditResponse('${ID}',__response,__saved)`); assert.equal(h.run('orderEditEntry.inputs.internal_note'), '未保存内部记录'); delete h.context.__saved.inputs.internal_note; h.run(`useOrderEditResponse('${ID}',__response,__saved)`); assert.equal(h.run('orderEditEntry.inputs.internal_note'), '内部跟进\n<尺寸>', '旧草稿缺字段时沿用当前备注'); } }); function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } function prepareSavedView(h) { const status = { textContent: '修改已经保存,可以查看修改后的订单。' }; h.nodes.set('#order-edit-saved-status', status); h.context.__filters = {}; h.run( 'invalidateMaterialPools=invalidateReport=invalidatePriceLockViews=function(){};getOrderBookFilters=function(){return __filters;};saveOrderBookFilters=function(){};', ); return status; } test('成功回执立即结束保存,后台读取悬挂也保留成功页,不串行读取列表或详情', async () => { const h = harness(); prepare(h); h.form(); prepareSavedView(h); const read = deferred(); h.context.__read = read.promise; h.run( 'mutate=async function(){return {id:orderEditEntry.id};};refresh=async function(renderPage){__calls.push({refresh:true,renderPage});await __read;};', ); let finished = false; const saving = h.run('submitOrderEdit(__form)').then(() => { finished = true; }); await new Promise(setImmediate); try { assert.equal(finished, true, '确认写入后应结束保存,不等待后续GET'); assert.match(h.nodes.get('#main').innerHTML, /订单修改已保存/); assert.match(h.nodes.get('#main').innerHTML, /view-saved-order-edit/); assert.doesNotMatch(h.nodes.get('#main').innerHTML, /正在读取/); assert.deepEqual(JSON.parse(JSON.stringify(h.calls)), [{ refresh: true, renderPage: false }]); assert.equal(h.saved.has(h.key), false); assert.equal(h.saved.has(h.active), false); assert.equal(h.run('orderEditEntry'), null); assert.match(h.toasts.at(-1).message, /修改已保存/); } finally { read.resolve(); await saving; } }); test('保存后后台读取失败仍明确已经保存,退出登录或换页后迟到失败不改当前页面', async () => { for (const steering of ['', 'session={user:null}', "tab='stock'", 'orderEditRequest++']) { const h = harness(); prepare(h); const status = prepareSavedView(h), read = deferred(); h.context.__read = read.promise; h.run('refresh=async function(){await __read;};'); await h.run(`finishOrderEditSave({date:'${D}'},{id:'${ID}'},'${ID}')`); if (steering) h.run(steering); read.reject(new Error('合成读取失败')); await new Promise(setImmediate); assert.equal(h.saved.has(h.key), false); assert.match(h.nodes.get('#main').innerHTML, /订单修改已保存/); assert.equal(h.toasts.length, 1); if (steering) assert.equal(status.textContent, '修改已经保存,可以查看修改后的订单。'); else assert.match(status.textContent, /已经保存,最新资料暂未读到/); } }); test('成功页按需查看先读取对应列表,再用原单在列表的位置打开上下条导航', async () => { const h = harness(); prepareSavedView(h); h.run("tab='orders'"); const source = { disabled: false, dataset: { action: 'view-saved-order-edit', id: ID }, closest() { return null; }, }, listElement = {}; h.context.__listElement = listElement; h.context.__showList = () => { h.nodes.delete('#order-edit-saved-status'); h.nodes.set('#order-list', listElement); }; h.run( `renderOrders=async function(){__calls.push({list:true});++orderBookRequest;orderBookDetailList={ids:['before','${ID}','after'],request:orderBookRequest,element:__listElement,user:session.user.id};__showList();};openOrder=async function(id,options){__calls.push({open:id,index:options.navigation.index,ids:options.navigation.list.ids});return true;};`, ); for (const handler of h.handlers.click) await handler({ target: { closest() { return source; }, }, }); assert.deepEqual(JSON.parse(JSON.stringify(h.calls)), [ { refresh: true }, { list: true }, { open: ID, index: 1, ids: ['before', ID, 'after'] }, ]); assert.equal(source.disabled, false); }); test('成功页查看读取失败保留已保存提示并恢复按钮,换页后的旧读取不会打开订单', async () => { const h = harness(); prepareSavedView(h); h.run("tab='orders';refresh=async function(){throw new Error('合成断线');};"); const source = { disabled: false }; h.context.__source = source; await h.run(`viewSavedOrderEdit('${ID}',__source)`); assert.equal(source.disabled, false); assert.match(h.nodes.get('#order-edit-saved-status').textContent, /已经保存,读取失败/); assert.equal(h.saved.size, 0); const read = deferred(); h.context.__read = read.promise; h.run('refresh=async function(){await __read;};'); const opening = h.run(`viewSavedOrderEdit('${ID}',__source)`); h.run("tab='stock'"); read.resolve(); await opening; assert.equal( h.calls.some(row => row.open), false, ); assert.equal(source.disabled, false); }); test('保存断线保留原操作和草稿,表单与提交禁用但底部恢复按钮仍可用', async () => { const h = harness(); prepare(h); const { fields, submit, retry } = h.form(); h.run("api=async function(url,data,key){__calls.push({url,data,key});throw new TypeError('合成断线');};"); await h.run('submitOrderEdit(__form)'); const job = JSON.parse(h.saved.get('mm-pending-edit-user')); assert.equal(job.url, '/api/orders/' + ID + '/edit'); assert.ok(job.key); assert.equal(h.saved.has(h.key), true); assert.equal(h.run('busy'), false); assert.equal(submit.disabled, true); assert.equal(fields.customer.disabled, true); assert.equal(retry.disabled, false); assert.match(h.nodes.get('#order-error').innerHTML, /恢复原操作/); assert.match(h.nodes.get('#order-error').innerHTML, /不要重复保存修改/); await h.run('submitOrderEdit(__form)'); assert.equal(h.calls.length, 1); assert.equal(JSON.parse(h.saved.get('mm-pending-edit-user')).key, job.key); });