'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'); const D = '2026-10-23'; function order(id) { return { id, revision: 1, reviewed_revision: 1, number: 'XS-' + id, paper_number: id, date: D, status: 'delivered', customer: '合成客户-' + id, salesperson: '助理', payment_account: '助理微信', total: 10000, rounding_mode: 'cent', discount: 0, goodsCost: 0, knownGoodsCost: 0, directCost: 0, profit: 10000, ownerCost: 0, netReceived: 10000, balance: 0, costTransferred: 0, profitTransferred: 0, ownerDirect: 0, settlementDue: 10000, costDue: 0, profitDue: 10000, lines: [], pendingFees: [], fee_items: [], payments: [], expenses: [], settlements: [], corrections: [], audit: [], }; } function book(ids = ['C', 'A', 'B']) { const amounts = [ 'sale', 'material', 'laborAndFees', 'unallocated', 'totalCost', 'profit', 'ownerCost', 'assistantCost', ], counts = [ 'orderCount', 'completedCount', 'draftCount', 'incompleteCount', 'afterSaleCount', 'recordCount', 'mg', 'pieces', 'unknownCosts', 'unknownCostCount', 'unknownProfitCount', ]; const summary = { ...Object.fromEntries([...amounts, ...counts].map(key => [key, 0])), orderCount: ids.length, completedCount: ids.length, knownCounts: Object.fromEntries(amounts.map(key => [key, 0])), unknownCounts: Object.fromEntries(amounts.map(key => [key, 0])), }; const rows = ids.map(id => ({ ...order(id), kind: 'order', types: [], mg: 0, pieces: 1, sale: 10000, material: 0, laborAndFees: 0, totalCost: 0, })); if (rows.length > 1) rows.splice(1, 0, { kind: 'afterSale', id: 'not-an-order', status: 'after_sale', date: D, project: '合成售后', customer: '合成客户', types: [], mg: 0, pieces: 0, sale: 0, material: 0, laborAndFees: 0, totalCost: 0, profit: 0, }); return { from: D, date: D, today: D, rows, summaryWithoutCancelled: summary, receiptsWithoutCancelled: { basis: 'orderDate', filterScope: 'matchingOrdersWithoutCancelled', from: D, date: D, receipt: 0, refund: 0, net: 0, channels: ['wechat', 'alipay', 'cash'].map(channel => ({ channel, name: channel, receipt: 0, refund: 0, net: 0, })), }, }; } function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; } function node(extra = {}) { return { innerHTML: '', textContent: '', hidden: false, dataset: {}, disabled: false, classList: { toggle() {} }, setAttribute() {}, scrollIntoView() {}, querySelector() { return null; }, ...extra, }; } function harness(ids = ['C', 'A', 'B']) { const nodes = new Map(), handlers = {}, dialogHandlers = {}, calls = [], saved = new Map(), sessionSaved = new Map(), toasts = [], orders = new Map(ids.concat(['outside']).map(id => [id, order(id)])); for (const selector of [ '#main', '#order-content', '#order-detail-navigation', '#detail-error', '#pending', '#order-list', '#order-book-summary', '#order-book-count', '#order-book-scope', '#order-lock-activity', '#order-book-people', '#identity', '#mode', '#notice', ]) nodes.set(selector, node()); nodes.set( '#detail-form', node({ querySelector(selector) { return selector === 'form' && this.innerHTML.includes(' nodes.get(selector) || null, querySelectorAll: () => [], 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: key => sessionSaved.get(key) ?? null, setItem: (key, value) => sessionSaved.set(key, String(value)), }, __calls: calls, __book: book(ids), __toasts: toasts, __api: async url => { if (url === '/api/state') return context.__state; if (url.startsWith('/api/order-book?')) return context.__book; const match = url.match(/^\/api\/orders\/([^/]+)(?:\/(cancellation|change))?$/); if (!match) throw new Error('意外接口:' + url); if (match[2]) return { eligible: true, canApprove: true, revision: orders.get(match[1])?.revision || 1, pending: null, requests: [], }; if (!orders.has(match[1])) throw new Error('合成订单不存在'); return orders.get(match[1]); }, }); const run = code => vm.runInContext(code, context), json = code => JSON.parse(JSON.stringify(run(code))); for (const file of [ 'price-locks-ui.js', 'material-pools-ui.js', 'order-cancellations-ui.js', 'order-changes-ui.js', 'app.js', ]) run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, '')); run( `session={user:{id:'navigation-user',name:'麦麦',role:'owner'}};state={user:session.user,today:'${D}',pockets:['现货','金料'],orders:[{id:'outside'}]};tab='orders';getOrderBookFilters();api=async function(url,data,key){__calls.push({url,data,key});return await __api(url,data,key);};toast=function(message,error){__toasts.push({message,error});};`, ); context.__state = { ...run('state'), mode: 'trial', sync: { enabled: false, pending: 0 } }; async function submit(kind, data = {}) { const form = { id: 'action-form', dataset: { kind }, data }; nodes.get('#detail-form').innerHTML = '
合成已保存动作
'; for (const handler of handlers.submit || []) await handler({ target: form, preventDefault() {} }); } function source(id, fromList = true) { return { dataset: { action: 'open-order', id, ...(fromList ? { orderBookVersion: String(run('orderBookDetailList.version')) } : {}), }, closest: selector => (fromList && selector === '#order-list' ? nodes.get('#order-list') : null), }; } async function click(button) { for (const handler of handlers.click || []) await handler({ target: { closest: () => button } }); } async function open(id) { context.__source = source(id); return await run(`openOrder('${id}',{source:__source})`); } function html() { return run('orderDetailNavigationHTML()'); } function disabled(action) { const tag = html().match(new RegExp(']*data-action="' + action + '"[^>]*>')); assert.ok(tag, '按钮应存在:' + action); return /\sdisabled(?:\s|>)/.test(tag[0]); } async function load(nextBook) { if (nextBook) context.__book = nextBook; await run('loadOrderBook()'); } return { run, json, context, nodes, dialog, dialogHandlers, handlers, calls, saved, sessionSaved, toasts, orders, source, click, open, html, disabled, load, submit, }; } function rangeResponse(ids, from, date, pocket = '') { const value = book(ids); return { ...value, from, date, pocket, receiptsWithoutCancelled: { ...value.receiptsWithoutCancelled, from, date } }; } async function dateInput(h, id, value) { const target = { id, value, closest() { return null; }, }; for (const handler of h.handlers.input || []) await handler({ target }); } test('订单列表和详情显示同一首次录入时间,补录业务日期不变,缺失时间不补零点', async () => { const h = harness(['A']), saved = h.orders.get('A'); for (const created of ['2026-10-24T16:07:59.999Z', undefined, D]) { const value = { ...saved, created }; h.orders.set('A', value); const result = book(['A']); Object.assign(result.rows[0], value); await h.load(result); const list = h.nodes.get('#order-list').innerHTML; await h.open('A'); const detail = h.nodes.get('#order-content').innerHTML; const expected = created?.includes('T') ? '2026-10-25 00:07' : '未记录', display = '录入时间(北京时间):' + expected; for (const html of [list, detail]) { assert.ok(html.includes('业务日期 ' + D)); assert.ok(html.includes(display)); } assert.deepEqual(h.json('orderBookDetailList.ids'), ['A']); assert.equal(h.run('currentOrder.date'), D); } }); test('搜索框提示克重,带单位查询沿用筛后列表导航与按账号记忆', async () => { const h = harness(); h.nodes.set('#order-search', node({ value: '1.38克' })); h.nodes.set('#order-filter', node({ value: 'reviewed' })); h.nodes.set('#order-pocket-filter', node({ value: 'external' })); const read = h.context.__api; h.context.__api = (url, data) => url.startsWith('/api/order-book?') ? rangeResponse(['A', 'C'], D, D, new URLSearchParams(url.split('?')[1]).get('pocket') || '') : read(url, data); h.run('loadOrderCancellationCount=loadOrderChangeCount=loadAfterSaleChangeCount=async function(){};'); await h.run('renderOrders()'); assert.match(h.nodes.get('#main').innerHTML, /placeholder="单号、客户、商品或克重,如1.38克"/); await h.run('filterOrders()'); const query = new URLSearchParams(h.calls.at(-1).url.split('?')[1]); assert.equal(query.get('q'), '1.38克'); assert.equal(query.get('status'), 'reviewed'); assert.equal(query.get('pocket'), 'external'); assert.equal(JSON.parse(h.run('orderBookDetailList.scope')).q, '1.38克'); assert.deepEqual(h.json('orderBookDetailList.ids'), ['A', 'C']); await h.open('A'); await h.run('navigateOrderDetail(1)'); assert.equal(h.run('currentOrder.id'), 'C'); h.run('orderBookFilters=null;getOrderBookFilters();'); assert.equal(h.run('orderBookFilters.q'), '1.38克'); h.run("orderBookFilters.q='1.381克'"); assert.equal(h.run('orderDetailNavigationValid()'), false); }); test('自定义区间有开始结束入口,模式切换保留值,与其他筛选同传并按账号恢复', async () => { const h = harness(); for (const id of [ 'order-single-date', 'order-range-fields', 'order-date', 'order-from', 'order-to', 'order-period-caption', ]) h.nodes.set('#' + id, node()); const read = h.context.__api; h.context.__api = (url, data) => { if (url.startsWith('/api/order-book?')) { const q = new URLSearchParams(url.split('?')[1]); return rangeResponse(['A', 'B'], q.get('from'), q.get('date'), q.get('pocket') || ''); } return read(url, data); }; h.run('loadOrderCancellationCount=loadOrderChangeCount=loadAfterSaleChangeCount=async function(){};'); await h.run('renderOrders()'); const html = h.nodes.get('#main').innerHTML; for (const label of ['今天', '昨天', '本月', '某天', '自定义区间', '开始日期', '结束日期']) assert.ok(html.includes(label)); assert.match(html, /id="order-from"[^>]*min="2000-01-01"/); assert.match(html, /id="order-to"[^>]*max="2026-10-23"/); await h.click({ dataset: { action: 'order-period', period: 'month' } }); await h.click({ dataset: { action: 'order-period', period: 'range' } }); assert.deepEqual(h.json('orderBookRange()'), { from: '2026-10-01', date: D, name: '自定义区间' }); assert.equal(h.nodes.get('#order-range-fields').hidden, false); assert.equal(h.nodes.get('#order-single-date').hidden, true); await dateInput(h, 'order-from', '2026-09-30'); await dateInput(h, 'order-to', '2026-10-02'); h.run( "Object.assign(orderBookFilters,{q:'共同客户',status:'reviewed',pocket:'金料',member:'assistant'});saveOrderBookFilters();", ); await h.load(); let query = new URLSearchParams(h.calls.at(-1).url.split('?')[1]); assert.deepEqual(Object.fromEntries(query), { from: '2026-09-30', date: '2026-10-02', q: '共同客户', status: 'reviewed', pocket: '金料', member: 'assistant', }); assert.equal(h.nodes.get('#order-period-caption').textContent, '2026-09-30 至 2026-10-02(含首尾)'); await h.click({ dataset: { action: 'order-period', period: 'date' } }); assert.equal(h.run('orderBookFilters.date'), '2026-10-02'); assert.equal(h.nodes.get('#order-single-date').hidden, false); assert.equal(h.nodes.get('#order-range-fields').hidden, true); await h.click({ dataset: { action: 'order-period', period: 'range' } }); const saved = h.json('orderBookFilters'); h.run('orderBookFilters=null;getOrderBookFilters();'); assert.deepEqual(h.json('orderBookFilters'), saved); h.run( "session.user={id:'another-user',role:'assistant',name:'助理2'};state.user=session.user;getOrderBookFilters();", ); assert.equal(h.run('orderBookFilters.mode'), 'today'); assert.equal(h.run('orderBookFilters.from'), ''); assert.equal(h.run('orderBookFilters.q'), ''); h.run( "Object.assign(orderBookFilters,{mode:'range',from:'2026-10-10',to:'2026-10-11'});saveOrderBookFilters();session.user={id:'navigation-user',role:'owner',name:'麦麦'};state.user=session.user;getOrderBookFilters();", ); assert.deepEqual(h.json('orderBookFilters'), saved); for (const mode of ['today', 'yesterday', 'month']) { await h.click({ dataset: { action: 'order-period', period: mode } }); assert.equal(h.run('orderBookFilters.mode'), mode); } await h.click({ dataset: { action: 'order-period', period: 'range' } }); assert.equal(h.run('orderBookRange().from'), '2026-09-30'); assert.equal(h.run('orderBookRange().date'), '2026-10-02'); }); test('非法区间停止请求并清除旧列表及汇总,旧范围迟到响应不能覆盖错误', async () => { const h = harness(); await h.load(); assert.match(h.nodes.get('#order-list').innerHTML, /合成客户-C/); for (const [from, to, message] of [ ['', D, /请选择开始日期和结束日期/], ['2026-02-30', D, /日期区间无效/], ['2026-9-30', D, /日期区间无效/], ['1999-12-31', D, /日期区间无效/], [D, '2026-10-24', /今天或之前/], [D, '2026-10-01', /开始日期不能晚于结束日期/], ]) { h.context.__from = from; h.context.__to = to; h.run("Object.assign(orderBookFilters,{mode:'range',from:__from,to:__to});"); const before = h.calls.length; await h.load(); assert.equal(h.calls.length, before); assert.match(h.nodes.get('#order-list').innerHTML, message); assert.doesNotMatch(h.nodes.get('#order-list').innerHTML, /合成客户-C/); assert.doesNotMatch(h.nodes.get('#order-book-summary').innerHTML, /¥/); assert.equal(h.nodes.get('#order-book-count').textContent, ''); assert.equal(h.run('orderBookDetailList'), null); } const wait = deferred(), read = h.context.__api; h.context.__api = url => (url.startsWith('/api/order-book?') ? wait.promise : read(url)); h.run("Object.assign(orderBookFilters,{mode:'range',from:'2026-10-01',to:'2026-10-02'});"); const old = h.load(), before = h.calls.length; await dateInput(h, 'order-from', '2026-10-03'); assert.equal(h.calls.length, before); assert.match(h.nodes.get('#order-list').innerHTML, /开始日期不能晚于结束日期/); wait.resolve(rangeResponse(['A', 'B'], '2026-10-01', '2026-10-02')); await old; assert.match(h.nodes.get('#order-list').innerHTML, /开始日期不能晚于结束日期/); assert.doesNotMatch(h.nodes.get('#order-book-summary').innerHTML, /¥/); await dateInput(h, 'order-to', ''); h.run('orderBookFilters=null;getOrderBookFilters();'); assert.equal(h.run('orderBookFilters.mode'), 'range'); assert.equal(h.run('orderBookFilters.to'), ''); const count = h.calls.length; await h.load(); assert.equal(h.calls.length, count); assert.match(h.nodes.get('#order-list').innerHTML, /请选择开始日期和结束日期/); }); test('区间详情上下条只用筛后列表,单日区间有效,切换区间失效原导航', async () => { const h = harness(); h.run("Object.assign(orderBookFilters,{mode:'range',from:'2026-09-30',to:'2026-10-02',status:'reviewed'});"); await h.load(rangeResponse(['B', 'C'], '2026-09-30', '2026-10-02')); const scope = JSON.parse(h.run('orderBookDetailList.scope')); assert.equal(scope.from, '2026-09-30'); assert.equal(scope.date, '2026-10-02'); assert.equal(scope.status, 'reviewed'); assert.deepEqual(h.json('orderBookDetailList.ids'), ['B', 'C']); await h.open('B'); await h.run('navigateOrderDetail(1)'); assert.equal(h.run('currentOrder.id'), 'C'); assert.equal(h.disabled('order-detail-next'), true); h.run("orderBookFilters.to='2026-10-01'"); assert.equal(h.run('orderDetailNavigationValid()'), false); assert.equal(h.disabled('order-detail-prev'), true); h.run(`Object.assign(orderBookFilters,{from:'${D}',to:'${D}'});`); await h.load(rangeResponse(['A'], D, D)); assert.deepEqual(h.json('orderBookDetailList.ids'), ['A']); const query = new URLSearchParams(h.calls.at(-1).url.split('?')[1]); assert.equal(query.get('from'), D); assert.equal(query.get('date'), D); }); test('订单筛选只提供全部及5个新入口,新值可恢复、旧状态回到全部并保留其他筛选,锁价提示待交付边界', async () => { const h = harness(), key = 'mm-order-book-navigation-user'; assert.deepEqual(h.json('orderBookStatusOptions'), [ ['', '全部状态'], ['reviewed', '已复核'], ['unreviewed', '未复核'], ['after_sale', '售后'], ['recovery', '回收'], ['price_lock', '锁价'], ]); for (const status of [ 'reviewed', 'unreviewed', 'after_sale', 'recovery', 'price_lock', 'delivered', 'draft', 'confirmed', 'returned', 'cancelled', ]) { h.sessionSaved.set(key, JSON.stringify({ mode: 'date', date: D, q: '合成客户', status, pocket: '金料' })); h.run('orderBookFilters=null;getOrderBookFilters();'); const filters = h.json('orderBookFilters'); assert.equal( filters.status, ['reviewed', 'unreviewed', 'after_sale', 'recovery', 'price_lock'].includes(status) ? status : '', ); assert.equal(filters.date, D); assert.equal(filters.q, '合成客户'); assert.equal(filters.pocket, '金料'); h.run('saveOrderBookFilters();orderBookFilters=null;getOrderBookFilters();'); assert.deepEqual(h.json('orderBookFilters'), filters); } h.nodes.set('#order-status-hint', node()); h.run( "orderBookFilters.status='price_lock';loadOrderBook=async function(){};loadAfterSaleChangeCount=async function(){};loadOrderCancellationCount=async function(){};loadOrderChangeCount=async function(){};", ); await h.run('renderOrders()'); const html = h.nodes.get('#main').innerHTML, select = html.match(/'; const before = h.calls.length; await assert.rejects(h.run('navigateOrderDetail(1)'), /先保存或收起/); assert.equal(h.calls.length, before); assert.match(form.innerHTML, /未保存/); assert.match(h.nodes.get('#order-detail-navigation').innerHTML, /role="alert">[^<]*先保存或收起/); } form.innerHTML = ''; h.run('busy=true'); await assert.rejects(h.run('navigateOrderDetail(1)'), /正在保存/); h.run('busy=false'); h.saved.set('mm-pending-navigation-user', '{"url":"/api/orders/issue","key":"synthetic"}'); await assert.rejects(h.run('navigateOrderDetail(1)'), /恢复原操作/); assert.equal(h.run('currentOrder.id'), 'C'); assert.equal(h.disabled('order-detail-next'), true); }); test('切换途中弹出表单仍在响应提交前复查,不会被新详情覆盖', async () => { const h = harness(); await h.load(); await h.open('C'); const wait = deferred(), read = h.context.__api; h.context.__api = url => (url === '/api/orders/A' ? wait.promise : read(url)); const loading = h.run('navigateOrderDetail(1)'); h.nodes.get('#detail-form').innerHTML = '
保留我的内容
'; wait.resolve(h.orders.get('A')); await loading; assert.equal(h.run('currentOrder.id'), 'C'); assert.match(h.nodes.get('#detail-form').innerHTML, /保留我的内容/); assert.match(h.html(), /先保存或收起/); }); test('×关闭、原生Escape及close使晚到的响应失效,不会重新打开弹窗', async () => { for (const kind of ['button', 'cancel', 'close']) { const h = harness(); await h.load(); await h.open('C'); const wait = deferred(), read = h.context.__api; h.context.__api = url => (url === '/api/orders/A' ? wait.promise : read(url)); const loading = h.run('navigateOrderDetail(1)'); if (kind === 'button') await h.click({ dataset: { action: 'close-dialog' }, closest: () => h.dialog }); else if (kind === 'cancel') { for (const handler of h.dialogHandlers.cancel) handler(); h.dialog.close(); } else h.dialog.close(); wait.resolve(h.orders.get('A')); await loading; assert.equal(h.dialog.open, false); assert.equal(h.dialog.shows, 1); assert.equal(h.run('currentOrder'), null); assert.equal(h.run('orderDetailNavigation'), null); } }); test('列表更换、页签或账号变化时拒收旧响应,不影响已经显示的原单', async () => { for (const kind of ['list', 'tab', 'session', 'state']) { const h = harness(); await h.load(); await h.open('C'); const wait = deferred(), read = h.context.__api; h.context.__api = url => (url === '/api/orders/A' ? wait.promise : read(url)); const loading = h.run('navigateOrderDetail(1)'); if (kind === 'list') await h.load(book(['B'])); else if (kind === 'tab') h.run("tab='report'"); else if (kind === 'session') h.run("session={user:{id:'other-user'}}"); else h.run("state={...state,user:{id:'other-user'}}"); wait.resolve(h.orders.get('A')); await loading; assert.equal(h.run('currentOrder.id'), 'C'); assert.equal(h.run('orderDetailLoad'), null); } }); test('后打开的订单优先,晚到的前一张单及其审批响应不能覆盖当前资料', async () => { const h = harness(), wait = deferred(), read = h.context.__api; h.context.__api = url => (url === '/api/orders/C' ? wait.promise : read(url)); const old = h.run("openOrder('C')"); await h.run("openOrder('A')"); wait.resolve(h.orders.get('C')); await old; assert.equal(h.run('currentOrder.id'), 'A'); assert.equal(h.run('orderCancellationDetail.id'), 'A'); assert.equal(h.run('orderChangeDetail.id'), 'A'); }); test('mutate完成后重新应用首末禁用,原有全量按钮恢复不会解禁边界', async () => { const h = harness(); await h.load(); await h.open('C'); const read = h.context.__api; h.context.__api = (url, data) => (data ? { synthetic: true } : read(url)); await h.run("mutate('/synthetic-only',{test:true})"); assert.equal(h.disabled('order-detail-prev'), true); assert.equal(h.disabled('order-detail-next'), false); assert.match(h.nodes.get('#order-detail-navigation').innerHTML, /data-action="order-detail-prev"[^>]*disabled/); assert.equal(h.saved.size, 0); }); test('列表已复核标记只认可销售单当前正整数版本,售后与改后旧复核不误标且保留状态', async () => { const h = harness(); for (const row of [h.context.__book.rows[0], h.context.__book.rows[1]]) Object.assign(row, { revision: 3, reviewed_revision: 3 }); Object.assign(h.context.__book.rows[2], { revision: 4, reviewed_revision: 3, status: 'cancelled' }); h.context.__book.rows[3].status = 'returned'; await h.load(); const html = h.nodes.get('#order-list').innerHTML; assert.equal((html.match(/class="order-review-status"/g) || []).length, 2); for (const status of ['已完成', '已取消', '已退货']) assert.ok(html.includes(status)); for (const row of [ { revision: 0, reviewed_revision: 0 }, { revision: '3', reviewed_revision: '3' }, { revision: 3, reviewed_revision: '3' }, { revision: 4, reviewed_revision: 3 }, { kind: 'afterSale', revision: 1, reviewed_revision: 1 }, { revision: 3 }, ]) { h.context.__row = row; assert.equal(h.run('orderReviewBadge(__row)'), ''); } }); test('真实复核保存刷新列表徽标,并保留原筛选与顺序的中间位置和上一下一条', async () => { const h = harness(); h.orders.get('A').reviewed_revision = 0; h.context.__book.rows.find(row => row.id === 'A').reviewed_revision = 0; await h.load(); await h.open('A'); const oldList = h.run('orderDetailNavigation.list'), read = h.context.__api; h.context.__api = (url, data) => { if (url === '/api/orders/A/review') { assert.equal(data.revision, 1); Object.assign(h.orders.get('A'), { revision: 2, reviewed_revision: 2 }); Object.assign( h.context.__book.rows.find(row => row.id === 'A'), { revision: 2, reviewed_revision: 2 }, ); return { id: 'A' }; } return read(url, data); }; await h.submit('review'); assert.equal(h.run('pending()'), null); assert.notEqual(h.run('orderDetailNavigation.list'), oldList); assert.deepEqual(h.json('orderDetailNavigation.list.ids'), ['C', 'A', 'B']); assert.match(h.html(), />2 \/ 3 call.data).length, 1); }); test('复核POST丢响应在原弹窗用同操作号恢复,成功后导航和已复核版本均保留', async () => { const h = harness(); await h.load(); await h.open('A'); const read = h.context.__api; let committed = false; h.context.__api = (url, data) => { if (url === '/api/orders/A/review') { if (!committed) { committed = true; Object.assign(h.orders.get('A'), { revision: 2, reviewed_revision: 2 }); throw new Error('合成响应中断'); } return { id: 'A' }; } return read(url, data); }; await h.submit('review'); assert.ok(h.run('pending()')); assert.match(h.nodes.get('#detail-error').innerHTML, /data-action="retry"/); assert.match(h.html(), />2 \/ 3 h.dialog }); const writes = h.calls.filter(call => call.url === '/api/orders/A/review'); assert.equal(writes.length, 2); assert.equal(writes[0].key, writes[1].key); assert.equal(h.run('pending()'), null); assert.match(h.html(), />2 \/ 3 { for (const stage of ['state', 'book', 'detail']) { const h = harness(); await h.load(); await h.open('C'); const read = h.context.__api; let committed = false, failed = false; h.context.__api = (url, data) => { if (url === '/api/orders/C/review') { committed = true; Object.assign(h.orders.get('C'), { revision: 2, reviewed_revision: 2 }); return { id: 'C' }; } if ( committed && !failed && ((stage === 'state' && url === '/api/state') || (stage === 'book' && url.startsWith('/api/order-book?')) || (stage === 'detail' && url === '/api/orders/C')) ) { failed = true; throw new Error('合成读取失败'); } return read(url, data); }; await h.submit('review'); assert.equal(failed, true, stage); assert.equal(h.run('pending()'), null); assert.ok(h.run('orderDetailRetry.savedContext'), stage); assert.equal(h.nodes.get('#detail-form').innerHTML, ''); assert.equal(h.disabled('order-detail-retry'), false); await h.run('retryOrderDetail()'); assert.equal(h.run('currentOrder.reviewed_revision'), 2); assert.match(h.html(), />1 \/ 3 call.data).length, 1); } }); test('变更与取消审批成功回读保留列表导航,单据读取失败的原重读按钮也保留上下文', async () => { for (const kind of ['change', 'cancellation']) { const h = harness(); await h.load(); await h.open('A'); const read = h.context.__api; let failed = false; h.context.__api = (url, data) => { if (!failed && url === '/api/orders/A') { failed = true; throw new Error('合成审批后读取失败'); } return read(url, data); }; const save = kind === 'change' ? "finishOrderChangeSave('/api/order-changes/decision/approve',{}, {id:'A'})" : "finishOrderCancellationSave('/api/order-cancellations/decision/reject',{}, {id:'A'})"; await h.run(save); assert.equal(h.run('currentOrder'), null); assert.ok(h.run('orderDetailRetry.savedContext')); await h.click({ dataset: { action: 'reload-order-' + kind, id: 'A' }, closest: () => h.dialog }); assert.equal(h.run('currentOrder.id'), 'A'); assert.match(h.html(), />2 \/ 3 call.data).length, 0); } }); test('保存后订单离开原状态筛选则禁切并说明,不用旧列表;全局入口仍刷新原页且无导航', async () => { const h = harness(); h.run("orderBookFilters.status='delivered'"); await h.load(); await h.open('C'); h.context.__saved = h.run("captureOrderDetailReload('C')"); h.context.__book = book(['A', 'B']); h.orders.get('C').status = 'returned'; await h.run("refreshOrderDetailAfterSave('C',__saved)"); assert.equal(h.run('currentOrder.id'), 'C'); assert.equal(h.run('orderDetailNavigation'), null); assert.match(h.html(), /不在原筛选结果/); assert.equal(h.disabled('order-detail-prev'), true); assert.equal(h.disabled('order-detail-next'), true); const external = harness(); await external.run("openOrder('outside')"); external.run('refresh=async function(renderPage=true){__calls.push({renderPage});};'); await external.run("refreshOrderDetailAfterSave('outside')"); assert.equal(external.calls.find(call => Object.hasOwn(call, 'renderPage')).renderPage, true); assert.equal(external.run('orderDetailNavigation'), null); }); test('保存后等待重读期间关闭、切页、换账号或改日期搜索状态货盘成员都不恢复旧导航和弹窗', async () => { for (const kind of ['close', 'tab', 'session', 'state', 'date', 'search', 'status', 'pocket', 'member']) { const h = harness(); await h.load(); await h.open('C'); const wait = deferred(), read = h.context.__api; h.context.__api = (url, data) => (url === '/api/state' ? wait.promise : read(url, data)); const loading = h.run("refreshOrderDetailAfterSave('C')"); if (kind === 'close') h.dialog.close(); else if (kind === 'tab') h.run("tab='report'"); else if (kind === 'session') h.run("session={user:{id:'other'}}"); else if (kind === 'state') h.run("state={...state,user:{id:'other'}}"); else if (kind === 'date') h.run("orderBookFilters.mode='date';orderBookFilters.date='2026-10-22'"); else if (kind === 'search') h.run("orderBookFilters.q='另一个筛选'"); else if (kind === 'pocket') h.run("orderBookFilters.pocket='金料'"); else if (kind === 'member') h.run("orderBookFilters.member='assistant'"); else h.run("orderBookFilters.status='returned'"); wait.resolve(h.context.__state); await loading; assert.equal(h.calls.filter(call => call.url === '/api/orders/C').length, 1, kind); if (kind === 'close') { assert.equal(h.dialog.open, false); assert.equal(h.run('currentOrder'), null); } if (kind === 'state') assert.equal(h.run('state.user.id'), 'other'); } }); test('回收在客户旁醒目标记且只读展示,置换销售单标记一次,普通订单导航不混入回收', async () => { const h = harness(), b = h.context.__book, recovery = { id: 'recovery-only', kind: 'recovery', recovery_id: 'recovery-only', recovery_mode: 'direct', status: 'recovery', number: 'HS202610230001', date: D, customer: '合成回收客户', types: ['黄金回收'], mg: 9900, pieces: 0, cashPayment: 899991, note: '合成回收备注', }; b.rows.find(row => row.id === 'A').recovery_mode = 'exchange'; b.rows.find(row => row.id === 'A').recovery_id = 'swap-A'; b.displayRows = [b.rows[0], recovery, ...b.rows.slice(1)]; b.recoveryCount = 1; await h.load(); const html = h.nodes.get('#order-list').innerHTML, match = html.match(/([\s\S]*?)<\/tr>/); assert.ok(match); assert.match( match[1], /order-book-customer-name">合成回收客户<\/strong>回收/, ); assert.match(match[1], /data-action="recovery-open" data-id="recovery-only"/); assert.match(match[1], /data-action="recovery-print"/); assert.doesNotMatch(match[1], /data-action="open-order"|data-action="copy-order"|order-review-status/); assert.match(match[1], /回收付款 ¥8,999.91/); assert.match(match[1], /9.900g.*折后克重/); assert.equal((match[1].match(/—<\/span>/g) || []).length, 5); assert.equal((html.match(/order-book-recovery-badge is-exchange">置换/g) || []).length, 1); assert.match(h.nodes.get('#order-book-count').textContent, /汇总 3 单 · 回收 1 笔/); assert.match(h.nodes.get('#order-book-summary').innerHTML, /另有回收 1 笔/); assert.deepEqual(h.json('orderBookDetailList.ids'), ['C', 'A', 'B']); await h.open('A'); assert.match(h.html(), />2 \/ 3 { const h = harness(); h.run( "state.orders=[{lines:[{pocket:'臻金汇'}]}];loadOrderCancellationCount=async function(){};loadOrderChangeCount=async function(){};", ); assert.deepEqual(h.json('orderBookPocketOptions()'), [ ['', '全部货盘'], ['external', '配货'], ['现货', '现货'], ['金料', '金料'], ['臻金汇', '臻金汇(已停用 · 历史)'], ]); for (const [selector, value] of [ ['#order-search', '共同'], ['#order-filter', 'delivered'], ['#order-member-filter', 'assistant'], ['#order-pocket-filter', '金料'], ]) h.nodes.set( selector, node({ value, closest() { return null; }, id: selector.slice(1), }), ); h.nodes.set('#order-pocket-hint', node({ hidden: true })); h.context.__book = { ...book(['A', 'B']), pocket: '金料' }; for (const handler of h.handlers.change || []) await handler({ target: h.nodes.get('#order-pocket-filter') }); await new Promise(resolve => setImmediate(resolve)); const query = new URLSearchParams(h.calls.find(call => call.url.startsWith('/api/order-book?')).url.split('?')[1]); assert.equal(query.get('pocket'), '金料'); assert.equal(query.get('q'), '共同'); assert.equal(query.get('status'), 'delivered'); assert.equal(query.get('member'), 'assistant'); const saved = JSON.parse(h.sessionSaved.get('mm-order-book-navigation-user')); assert.equal(saved.pocket, '金料'); assert.equal(saved.member, 'assistant'); h.run('orderBookFilters=null;getOrderBookFilters();'); assert.equal(h.run('orderBookFilters.pocket'), '金料'); await h.run('renderOrders()'); assert.match(h.nodes.get('#main').innerHTML, /出货货盘