'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'); const { randomUUID } = require('node:crypto'), Calc = require('../public/calculations'); const ID = '11111111-1111-4111-8111-111111111111', RID = '22222222-2222-4222-8222-222222222222', D = '2026-10-22'; function order(extra = {}) { return { id: ID, revision: 7, number: 'XS20261022001', paper_number: '20261022001', date: D, status: 'delivered', customer: '客户代号', salesperson: '助理', payment_account: '助理微信', total: 210000, rounding_mode: 'cent', discount: 0, profit: 28000, directCost: 2000, goodsCost: 180000, ownerCost: 180000, netReceived: 210000, balance: 0, settlementDue: 208000, costDue: 180000, profitDue: 28000, costTransferred: 0, profitTransferred: 0, ownerDirect: 0, reviewed_revision: 0, lines: [], payments: [], expenses: [], settlements: [], corrections: [], pendingFees: [], fee_items: [], audit: [], note: '', ...extra, }; } function request(extra = {}) { return { id: RID, order_id: ID, order_number: 'XS20261022001', order_date: D, order_status: 'delivered', order_revision: 7, reason: '同一笔销售重复录入', status: 'pending', requester_name: '助理', requester_role: 'assistant', requester_id: 'assistant-id', created: D + 'T08:00:00.000Z', reviewer_name: null, reviewed: null, note: '', stale: false, canApprove: true, summary: { total: 210000, netReceived: 210000, goodsCost: 180000, directCost: 2000, profit: 28000, settlementDue: 208000, inventory: [{ date: D, pocket: '现货', mg: 2000 }], }, ...extra, }; } function detail(pending = null, extra = {}) { return { eligible: !pending, reason: pending ? '已有待审申请' : '', revision: 7, pending, requests: pending ? [pending] : [], canApprove: true, ...extra, }; } function node(extra = {}) { return { innerHTML: '', textContent: '', hidden: false, disabled: false, dataset: {}, classList: { toggle() {} }, setAttribute() {}, scrollIntoView() {}, focus() {}, ...extra, }; } function harness(role = 'owner') { const saved = new Map(), nodes = new Map(), calls = [], handlers = {}, toasts = []; for (const selector of [ '#main', '#order-content', '#detail-form', '#detail-error', '#order-cancellation-error', '#pending', '#order-cancellations-entry', ]) nodes.set(selector, node()); nodes.set( '#order-dialog', node({ open: true, showModal() { this.open = true; }, close() { this.open = false; }, }), ); const context = createBrowserContext({ LedgerCalc: Calc, crypto: { randomUUID }, console, setInterval() {}, setTimeout() {}, clearTimeout() {}, document: { querySelector: selector => nodes.get(selector) || null, querySelectorAll() { return []; }, addEventListener(type, handler) { (handlers[type] ??= []).push(handler); }, }, window: { 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() {}, }, __calls: calls, __toasts: toasts, __order: order(), __detail: detail(), __request: request(), __form: null, __finished: null, }); const run = code => vm.runInContext(code, context), json = code => JSON.parse(JSON.stringify(run(code))); for (const file of ['order-cancellations-ui.js', 'app.js']) run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, '')); run(`session={user:{id:'cancel-user',name:'${role === 'owner' ? '麦麦' : '助理'}',role:'${role}'}};state={user:session.user,today:'2026-10-23',pockets:['现货','金料'],accounts:['助理微信','麦麦微信']};tab='orders';currentOrder=__order; api=async function(url,data,key){__calls.push({url,data,key});return __detail;};toast=function(message,error){__toasts.push({message,error});}; invalidateMaterialPools=function(){};invalidateReport=function(){};invalidatePriceLockViews=function(){};materialPoolOrderNoticeHTML=function(){return '';};priceLockInventoryCreditHTML=function(){return '';}; profitSummary=function(){return {title:'利润',value:'¥280.00',hint:''};};useOrderCancellationDetail(currentOrder,__detail);`); function prepare(pending = null, extra = {}) { context.__detail = detail(pending, extra); run('useOrderCancellationDetail(currentOrder,__detail)'); } function form(kind, values = {}) { run(`showOrderCancellationForm('${kind}')`); kind = run('orderCancellationFormEntry.kind'); const fields = Object.fromEntries( Object.entries({ reason: '重复开单', note: '', verified: false, ...values }).map(([name, value]) => [ name, node({ name, value: typeof value === 'boolean' ? 'on' : value, checked: value === true }), ]), ); const submit = node({ type: 'submit' }), close = node({ dataset: { action: 'close-order-cancellation-form' } }), reload = node({ dataset: { action: 'reload-order-cancellation' } }), retry = node({ dataset: { action: 'retry' } }), controls = [...Object.values(fields), submit, close, reload, retry]; const title = node(), form = node({ id: 'order-cancellation-form', dataset: { kind }, querySelector(selector) { if (selector === 'h2') return title; if (selector === '[data-order-cancellation-submit]') return submit; const name = selector.match(/\[name="([^"]+)"\]/)?.[1]; return fields[name] || null; }, querySelectorAll() { return controls; }, }); nodes.set('#order-cancellation-form', form); nodes.set('#order-cancellation-form [name="verified"]', fields.verified); context.__form = form; return { form, fields, submit, close, reload, retry }; } async function click(action, attrs = {}) { const b = node({ dataset: { action, ...attrs }, closest() { return null; }, }); for (const handler of handlers.click) await handler({ target: { closest() { return b; }, }, }); } return { context, run, json, nodes, calls, saved, toasts, prepare, form, click }; } test('普通订单直接显示申请取消,锁价、退货、作废和待审单没有重复申请入口', () => { const h = harness(); assert.match(h.run('orderCancellationActionHTML(currentOrder)'), /申请取消/); for (const extra of [ { price_lock_id: 'lock-id' }, { status: 'returned' }, { status: 'cancelled' }, { cancellationPending: { id: RID, status: 'pending' } }, ]) { h.context.__order = order(extra); h.run('currentOrder=__order;useOrderCancellationDetail(currentOrder,__detail)'); assert.equal(h.run('orderCancellationActionHTML(currentOrder)'), ''); } assert.equal(h.calls.length, 0); }); test('取消原因必填,申请仅提交原版本与原因,申请成功走原单结果处理', async () => { const h = harness(), { fields } = h.form('request', { reason: ' ' }); h.run('finishOrderCancellationSave=async function(url,input,result){__finished={url,input,result};};'); await assert.rejects(h.run('submitOrderCancellation(__form)'), /取消原因/); assert.equal(h.calls.length, 0); fields.reason.value = ' 一笔交易重复录入 '; await h.run('submitOrderCancellation(__form)'); assert.equal(h.calls.length, 1); assert.equal(h.calls[0].url, '/api/orders/' + ID + '/cancellation'); assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), { revision: 7, reason: '一笔交易重复录入' }); assert.equal(h.json('__finished.input.revision'), 7); }); test('店主核对金额成本库存并勾选才能同意;助理没有审批按钮且无法调用审批表单', async () => { const h = harness(); h.prepare(request()); const html = h.run('orderCancellationDetailHTML(currentOrder)'); assert.match(html, /申请期间仍按原订单计账/); assert.match(html, /approve-order-cancellation/); assert.match(html, /reject-order-cancellation/); assert.match(html, /助理/); const { fields } = h.form('approve'); h.run('finishOrderCancellationSave=async function(){};'); await assert.rejects(h.run('submitOrderCancellation(__form)'), /勾选/); assert.equal(h.calls.length, 0); const preview = h.nodes.get('#detail-form').innerHTML; for (const text of [ '撤销收款净额', '2,100.00', '1,800.00', '20.00', '+2.000g', '真实采购付款保留', '双方实际交款保留', ]) assert.ok(preview.includes(text), text); fields.verified.checked = true; fields.note.value = '核对原单后确认'; await h.run('submitOrderCancellation(__form)'); assert.equal(h.calls[0].url, '/api/order-cancellations/' + RID + '/approve'); assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), { revision: 7, verified: true, note: '核对原单后确认', }); const assistant = harness('assistant'); assistant.prepare(request(), { canApprove: true }); const assistantHTML = assistant.run('orderCancellationDetailHTML(currentOrder)'); assert.ok(!assistantHTML.includes('approve-order-cancellation')); assert.ok(!assistantHTML.includes('reject-order-cancellation')); assert.throws(() => assistant.run("showOrderCancellationForm('approve')"), /店主账号/); assert.equal(assistant.calls.length, 0); }); test('过期申请隐藏同意、仍允许麦麦填意见驳回;驳回记录后可重新申请', async () => { const h = harness(), stale = request({ stale: true, canApprove: false }); h.prepare(stale); const html = h.run('orderCancellationDetailHTML(currentOrder)'); assert.ok(!html.includes('approve-order-cancellation')); assert.match(html, /reject-order-cancellation/); assert.match(html, /原申请不能同意/); assert.throws(() => h.run("showOrderCancellationForm('approve')"), /已有变动/); const { fields } = h.form('reject'); h.run('finishOrderCancellationSave=async function(){};'); await assert.rejects(h.run('submitOrderCancellation(__form)'), /驳回意见/); fields.note.value = '金额已有修正,请按最新单据重新申请'; await h.run('submitOrderCancellation(__form)'); assert.deepEqual(JSON.parse(JSON.stringify(h.calls[0].data)), { note: fields.note.value }); const rejected = request({ status: 'rejected', reviewer_name: '麦麦', reviewed: D + 'T09:00:00Z', note: '请重新核对', canApprove: false, }); h.prepare(null, { requests: [rejected] }); assert.match(h.run('orderCancellationDetailHTML(currentOrder)'), /已驳回/); assert.match(h.run('orderCancellationActionHTML(currentOrder)'), /申请取消/); }); test('pending投影在独立读取失败时仍阻止财务、退货、交款和普通复核,保留打印', () => { const h = harness(); h.context.__order = order({ cancellationPending: { id: RID, status: 'pending' }, payments: [{ id: 'p', date: D, kind: 'receipt', amount: 210000 }], expenses: [{ id: 'e', date: D, amount: 2000, payer: 'assistant' }], }); h.run('currentOrder=__order;useOrderCancellationDetail(currentOrder,null,new Error("暂未连接"));renderDetail()'); const html = h.nodes.get('#order-content').innerHTML; for (const action of ['edit-order', 'show-expense', 'show-return', 'show-settlement', 'show-correct', 'show-review']) assert.ok(!html.includes('data-action="' + action + '"'), action); assert.ok(html.includes('data-action="print"')); assert.match(html, /暂未连接/); assert.throws(() => h.run("showAction('return')"), /待店主复核/); }); test('审批作废保留收款费用冲回与双方交款明细,不能再登记销售退款或费用', () => { const h = harness(), approved = request({ status: 'approved', canApprove: false, reviewer_name: '麦麦', reviewed: D + 'T09:00:00Z' }); h.context.__order = order({ status: 'cancelled', cancellationApproved: approved, netReceived: 100, expenses: [{ date: D, amount: -2000, payer: 'assistant', note: '更正冲回:取消审批作废;重复开单' }], payments: [ { date: D, kind: 'receipt', amount: -210000, account: '助理微信', reference: '更正冲回:取消审批作废;重复开单' }, ], settlements: [{ id: 's', date: D, bucket: 'cost', amount: 1000, actor: '助理', note: '原实际交款' }], }); h.run('currentOrder=__order'); h.prepare(null, { eligible: false, requests: [approved] }); h.run('renderDetail()'); const html = h.nodes.get('#order-content').innerHTML; for (const text of [ '已取消 · 录错作废', '原成交金额(已作废)', '作废冲回收款', '作废冲回费用', '原实际交款', '已撤销的金额不计入本单成本', ]) assert.ok(html.includes(text), text); assert.ok(!html.includes('实际发生的费用仍保留')); for (const action of ['request-order-cancellation', 'show-refund', 'show-expense', 'show-return']) assert.ok(!html.includes('data-action="' + action + '"'), action); h.run("showAction('correct')"); const correction = h.nodes.get('#detail-form').innerHTML; assert.match(correction, /settlement:s/); assert.ok(!correction.includes('payment:')); assert.ok(!correction.includes('expense:')); }); test('撤销摘要的缺失成本不冒充0,原因、意见及货盘转义,负库存冲回保留符号', () => { const h = harness(), r = request({ reason: '', note: '', summary: { ...request().summary, goodsCost: null, profit: null, inventory: [{ date: D, pocket: '<现货>', mg: -1000 }], }, }); h.context.__request = r; const summary = h.run('orderCancellationSummaryHTML(__request)'); assert.match(summary, /待补齐/); assert.match(summary, /-1.000g/); assert.match(summary, /<现货>/); assert.ok(!summary.includes('<现货>')); const history = h.run('orderCancellationHistoryHTML(__request)'); assert.ok(!history.includes(' { const h = harness(); h.run( "orderBookFilters={mode:'today',date:'2026-10-23',q:'只看这个客户',status:'delivered'};api=async function(url){__calls.push({url});return {requests:[__request],counts:{pending:1,approved:3,rejected:2},canApprove:true};};", ); await h.run('loadOrderCancellationCount()'); assert.equal(h.calls[0].url, '/api/order-cancellations?status=pending'); assert.equal(h.nodes.get('#order-cancellations-entry').textContent, '待取消复核(1)'); h.run("api=async function(){throw new Error('断线');}"); await h.run('loadOrderCancellationCount()'); assert.equal(h.nodes.get('#order-cancellations-entry').textContent, '待取消复核(读取失败)'); h.context.__late = { requests: [], counts: { pending: 0, approved: 0, rejected: 0 }, canApprove: true }; h.run("api=async function(){session.user={id:'another-user',role:'owner'};return __late;}"); await h.run('loadOrderCancellationCount()'); assert.equal(h.nodes.get('#order-cancellations-entry').textContent, '待取消复核(读取失败)'); }); test('全局列表保留跨日期原单、申请人原因和状态,助理只有查看入口', () => { const h = harness(), r = request({ order_date: '2026-09-01', created: '2026-09-02T08:00:00Z' }); h.context.__list = { requests: [r], counts: { pending: 1, approved: 0, rejected: 0 }, canApprove: true }; const html = h.run('orderCancellationListHTML(__list)'); for (const text of ['2026-09-01', '2026/9/2', '同一笔销售重复录入', '查看并复核']) assert.ok(html.includes(text), text); h.run("state.user.role='assistant'"); const assistant = h.run('orderCancellationListHTML(__list)'); assert.match(assistant, /查看订单/); assert.ok(!assistant.includes('查看并复核')); }); test('409清空录错确认并阻止批准旧页面,必须重新读取复核', async () => { const h = harness(); h.prepare(request()); const { fields, submit, reload, retry } = h.form('approve', { verified: true }); h.run( "api=async function(){const err=new Error('订单或记账已有新变动');err.status=409;err.confirmed=true;throw err;};", ); await h.run('submitOrderCancellation(__form)'); assert.equal(h.run('orderCancellationFormEntry'), null); assert.equal(fields.verified.checked, false); assert.equal(submit.disabled, true); assert.equal(reload.disabled, false); assert.equal(retry.disabled, false); assert.match(h.nodes.get('#order-cancellation-error').innerHTML, /重新读取订单并复核/); assert.equal(h.saved.get('mm-pending-cancel-user'), undefined); await assert.rejects(h.run('submitOrderCancellation(__form)'), /重新读取/); }); test('断线恢复批准复用原操作号及旧版本,不重复生成新单或批准请求', async () => { const h = harness(); h.prepare(request()); h.form('approve', { verified: true }); h.run("api=async function(url,data,key){__calls.push({url,data,key});throw new Error('响应丢失');};"); await h.run('submitOrderCancellation(__form)'); const saved = JSON.parse(h.saved.get('mm-pending-cancel-user')); assert.equal(saved.url, '/api/order-cancellations/' + RID + '/approve'); h.run( 'api=async function(url,data,key){__calls.push({url,data,key});return {id:currentOrder.id};};finishOrderCancellationSave=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.calls[1].data.revision, 7); assert.equal(h.json('__finished.result.id'), ID); assert.equal(h.saved.get('mm-pending-cancel-user'), undefined); assert.ok(h.calls.every(call => !call.url.includes('/issue'))); }); test('保存已成功但刷新失败时只留只读重读入口,不再显示提交表单', async () => { const h = harness(); h.prepare(request()); h.form('approve', { verified: true }); h.context.__savedResult = { id: ID }; h.run("refresh=async function(){throw new Error('刷新失败');};"); await h.run(`finishOrderCancellationSave('/api/order-cancellations/${RID}/approve',{},__savedResult)`); assert.equal(h.run('currentOrder'), null); assert.equal(h.run('orderCancellationFormEntry'), null); const html = h.nodes.get('#order-content').innerHTML; assert.match(html, /已同意取消/); assert.match(html, /重新读取原订单/); assert.ok(!html.includes('type="submit"')); assert.equal(h.calls.length, 0); assert.match( h.nodes.get('#order-cancellation-saved-status')?.textContent || h.toasts.at(-1).message, /保存|重新读取/, ); }); test('详情版本不一致拒绝审批;晚到的旧订单和换账号响应不能覆盖当前单', async () => { const h = harness(); h.prepare(request(), { revision: 8 }); assert.equal(h.run('currentOrderCancellation().data'), null); assert.match(h.run('orderCancellationDetailHTML(currentOrder)'), /已有新记录/); assert.throws(() => h.run("showOrderCancellationForm('approve')"), /重新读取/); const second = '33333333-3333-4333-8333-333333333333', resolvers = new Map(); h.context.__api = url => new Promise(resolve => resolvers.set(url, resolve)); h.run('api=__api'); const first = h.run(`openOrder('${ID}')`), next = h.run(`openOrder('${second}')`); resolvers.get('/api/orders/' + second)(order({ id: second, number: '后打开的订单' })); resolvers.get('/api/orders/' + second + '/cancellation')(detail()); await next; assert.equal(h.run('currentOrder.id'), second); resolvers.get('/api/orders/' + ID)(order()); resolvers.get('/api/orders/' + ID + '/cancellation')(detail(request())); await first; assert.equal(h.run('currentOrder.id'), second); h.context.__api = async url => { h.run("session.user={id:'changed-user',role:'owner'}"); return url.endsWith('/cancellation') ? detail() : order(); }; h.run('api=__api'); await h.run(`openOrder('${ID}')`); assert.equal(h.run('currentOrder.id'), second); }); test('服务器当天的助理和麦麦都可核对摘要直接取消,原单日期或资格缺失仍申请', async () => { for (const role of ['assistant', 'owner']) { const h = harness(role); h.run("currentOrder={...currentOrder,date:'2026-10-23'}"); h.prepare(null, { directActionDate: '2026-10-23', directToday: true, summary: request().summary }); assert.match(h.run('orderCancellationActionHTML(currentOrder)'), />取消订单申请取消申请取消 h.run("showOrderCancellationForm('request')"), /锁价单/); }); test('当天直接取消403清核实留原因转申请,同操作号恢复canceltoday不伪造审批记录', async () => { const h = harness('assistant'); h.run("currentOrder={...currentOrder,date:'2026-10-23'}"); h.prepare(null, { directActionDate: '2026-10-23', directToday: true, summary: request().summary }); const { form, fields, submit } = h.form('request', { verified: true, reason: '凌晨发现重复录单' }); h.run( "api=async function(url,data,key){__calls.push({url,data,key});const err=new Error('已跨日,请申请取消');err.status=403;err.confirmed=true;throw err;}", ); await h.run('submitOrderCancellation(__form)'); assert.equal(h.calls.length, 1); assert.equal(form.dataset.kind, 'request'); assert.equal(submit.textContent, '提交取消申请'); assert.equal(fields.reason.value, '凌晨发现重复录单'); assert.equal(fields.verified.checked, false); assert.match(h.nodes.get('#order-cancellation-error').innerHTML, /输入已保留/); assert.equal(h.saved.get('mm-pending-cancel-user'), undefined); await assert.rejects(h.run('submitOrderCancellation(__form)'), /勾选/); assert.equal(h.calls.length, 1); fields.verified.checked = true; h.run( 'api=async function(url,data,key){__calls.push({url,data,key});return {id:currentOrder.id};};finishOrderCancellationSave=async function(){}', ); await h.run('submitOrderCancellation(__form)'); assert.equal(h.calls[1].url, '/api/orders/' + ID + '/cancellation'); const lost = harness('assistant'); lost.run("currentOrder={...currentOrder,date:'2026-10-23'}"); lost.prepare(null, { directActionDate: '2026-10-23', directToday: true, summary: request().summary }); lost.form('request', { verified: true }); lost.run("api=async function(url,data,key){__calls.push({url,data,key});throw new Error('响应丢失');}"); await lost.run('submitOrderCancellation(__form)'); const pending = JSON.parse(lost.saved.get('mm-pending-cancel-user')); assert.equal(pending.url, '/api/orders/' + ID + '/canceltoday'); lost.run( 'api=async function(url,data,key){__calls.push({url,data,key});return {id:currentOrder.id};};finishOrderCancellationSave=async function(url,input,result){__finished={url,input,result};}', ); await lost.click('retry'); assert.equal(lost.calls[1].key, pending.key); assert.deepEqual(JSON.parse(JSON.stringify(lost.calls[1].data)), pending.data); assert.equal(lost.json('__finished.url'), pending.url); assert.equal(lost.saved.get('mm-pending-cancel-user'), undefined); const direct = request({ status: 'approved', direct: true, operator_name: '<助理>', executedAt: D + 'T10:00:00Z', reviewer_name: null, reviewed: null, canApprove: false, }); lost.context.__request = direct; const history = lost.run('orderCancellationHistoryHTML(__request)'); assert.match(history, /当天直接取消/); assert.match(history, /经办人:<助理>/); assert.ok(!history.includes('复核人')); assert.ok(!history.includes('已同意取消')); lost.context.__list = { requests: [direct], counts: { pending: 0, approved: 1, rejected: 0 }, canApprove: true }; const list = lost.run('orderCancellationListHTML(__list)'); assert.match(list, /当天直接取消/); assert.ok(!list.includes('已同意取消')); });