'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), vm = require('node:vm'); const D = '2026-10-26', pockets = ['现货', '金料', '找金', '回收旧料', '君宝汇']; function node(extra = {}) { return { innerHTML: '', textContent: '', value: '', dataset: {}, isConnected: true, disabled: false, setAttribute(name, value) { this[name] = value; }, closest() { return null; }, ...extra, }; } function result({ from = '', to = '', pocket = '', kind = 'all', hideDeleted = false, page = 1, total = 205, note = '合成流水', } = {}) { const totalPages = Math.max(1, Math.ceil(total / 100)); page = Math.min(page, totalPages); const shown = Math.min(100, total - (page - 1) * 100); return { pocket, kind, hideDeleted, from, to, pockets: pockets.map(pocket => ({ pocket, active: true })), total, shown, limit: 100, pageSize: 100, page, totalPages, hasPrev: page > 1, hasNext: page < totalPages, movements: Array.from({ length: shown }, (_, i) => ({ id: 'synthetic-' + ((page - 1) * 100 + i), date: D, pocket: pocket || '现货', mg: kind === 'decrease' ? -1000 : 1000, kind: ['decrease', 'transfer'].includes(kind) ? kind : 'increase', manual: true, current: true, status: 'active', reversal: false, actor: '合成经办人', note: note + ((page - 1) * 100 + i), })), }; } function harness() { const nodes = new Map(), handlers = {}, calls = [], toasts = [], downloads = [], revoked = [], timers = []; for (const id of [ 'inventory-movements-from', 'inventory-movements-to', 'main', 'inventory-movements-list', 'inventory-movements-count', 'inventory-movements-pagination', 'inventory-movements-pocket', 'inventory-movements-kind', 'inventory-movements-toggle-deleted', 'inventory-movements-export', 'inventory-movements-export-status', ]) nodes.set('#' + id, node()); nodes.get('#inventory-movements-kind').value = 'all'; const form = node({ values: { kind: 'transfer', pocket: '现货', to: '金料', grams: '3.123', note: '合成尚未提交的草稿' }, innerHTML: '合成未提交表单', }); nodes.set('#stock-form', form); nodes.get('#main').innerHTML = '合成库存整页'; const context = vm.createContext({ console, URLSearchParams, URL: { createObjectURL() { return 'blob:synthetic-xlsx'; }, revokeObjectURL(value) { revoked.push(value); }, }, setInterval() {}, setTimeout(fn) { timers.push(fn); }, clearTimeout() {}, window: { scrollTo() {} }, document: { querySelector: query => nodes.get(query) || null, querySelectorAll() { return []; }, body: { append() {} }, createElement() { return node({ click() { downloads.push({ href: this.href, filename: this.download }); }, remove() { this.removed = true; }, }); }, addEventListener(type, handler) { (handlers[type] ??= []).push(handler); }, }, __calls: calls, __toasts: toasts, }); const run = code => vm.runInContext(code, context), json = code => JSON.parse(JSON.stringify(run(code))); run(fs.readFileSync(require.resolve('../public/app.js'), 'utf8').replace(/\ninit\(\);\s*$/, '')); context.__api = async url => { const query = new URL(url, 'http://synthetic.invalid').searchParams; return result({ from: query.get('from') || '', to: query.get('to') || '', pocket: query.get('pocket') || '', kind: query.get('kind') || 'all', hideDeleted: query.get('hideDeleted') === 'true', page: Number(query.get('page') || 1), }); }; run( `state={user:{id:'synthetic-owner',member:'owner',role:'owner'},today:'${D}'};session={user:state.user};tab='stock';inventoryPage={date:'${D}'};toast=(message,error=false)=>__toasts.push({message,error});api=async url=>{__calls.push(url);return __api(url);};`, ); return { run, json, context, nodes, calls, toasts, form, downloads, revoked, timers, async load() { await run('loadInventoryMovements()'); }, async change(id, value) { const target = node({ id, value }); nodes.get('#' + id).value = value; await Promise.all((handlers.change || []).map(handler => handler({ target }))); }, async click(action, direction) { const button = node({ dataset: { action, direction } }); for (const handler of handlers.click || []) await handler({ target: { closest: selector => (selector === 'button' ? button : null) } }); }, }; } test('流水区域提供五种筛选及上下翻页,页码和总数与当前页同步', async () => { const h = harness(), html = h.run('stockMovements()'); for (const text of ['全部流水', '手动增加', '手动减少', '手动平移', '全部手动变动']) assert.ok(html.includes(text)); assert.doesNotMatch(html, /最近100条|最多显示/); await h.load(); let pagination = h.nodes.get('#inventory-movements-pagination').innerHTML; assert.match(pagination, /第 1 \/ 3 页/); assert.match(pagination, /data-direction="previous" disabled/); assert.match(pagination, /data-direction="next" >下一页/); assert.match(h.nodes.get('#inventory-movements-count').textContent, /共 205 条,当前显示 1~100 条/); assert.match( h.nodes.get('#inventory-movements-list').innerHTML, /data-direction="next"/, '看完本页后可直接在底部翻页', ); await h.click('inventory-movements-page', 'next'); assert.equal(h.run('inventoryMovementPage'), 2); assert.match(h.calls.at(-1), /page=2/); assert.match(h.nodes.get('#inventory-movements-count').textContent, /101~200/); await h.click('inventory-movements-page', 'next'); pagination = h.nodes.get('#inventory-movements-pagination').innerHTML; assert.match(pagination, /第 3 \/ 3 页/); assert.match(pagination, /data-direction="next" disabled/); assert.match(h.nodes.get('#inventory-movements-count').textContent, /201~205/); const count = h.calls.length; await h.click('inventory-movements-page', 'next'); assert.equal(h.calls.length, count); await h.click('inventory-movements-page', 'previous'); assert.equal(h.run('inventoryMovementPage'), 2); }); test('货盘与类型共同筛选回第一页,翻页保留筛选及未提交库存草稿', async () => { const h = harness(), before = JSON.stringify(h.form.values); h.run('inventoryMovementPage=3;'); await h.change('inventory-movements-pocket', '金料'); assert.equal(h.run('inventoryMovementPage'), 1); assert.match(h.calls.at(-1), /pocket=%E9%87%91%E6%96%99/); await h.click('inventory-movements-page', 'next'); await h.change('inventory-movements-kind', 'increase'); assert.equal(h.run('inventoryMovementPage'), 1); assert.match(h.calls.at(-1), /kind=increase&page=1/); await h.click('inventory-movements-page', 'next'); const query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('pocket'), '金料'); assert.equal(query.get('kind'), 'increase'); assert.equal(query.get('page'), '2'); assert.equal(h.nodes.get('#stock-form'), h.form); assert.equal(JSON.stringify(h.form.values), before); assert.equal(h.form.innerHTML, '合成未提交表单'); assert.equal(h.nodes.get('#main').innerHTML, '合成库存整页'); }); test('隐藏开关可恢复显示,保留货盘类型、回第一页并随翻页和重试传递,不丢入库草稿', async () => { const h = harness(), before = JSON.stringify(h.form.values); assert.match(h.run('stockMovements()'), /隐藏已删除记录/); assert.equal(h.run('inventoryMovementHideDeleted'), false); await h.change('inventory-movements-pocket', '金料'); await h.change('inventory-movements-kind', 'increase'); await h.click('inventory-movements-page', 'next'); await h.click('inventory-movements-toggle-deleted'); let query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('hideDeleted'), 'true'); assert.equal(query.get('pocket'), '金料'); assert.equal(query.get('kind'), 'increase'); assert.equal(query.get('page'), '1'); const toggle = h.nodes.get('#inventory-movements-toggle-deleted'); assert.equal(toggle.textContent, '显示已删除记录'); assert.equal(toggle['aria-pressed'], 'true'); assert.match(h.run('stockMovements()'), /显示已删除记录/); await h.click('inventory-movements-page', 'next'); query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('hideDeleted'), 'true'); assert.equal(query.get('page'), '2'); await h.click('inventory-movements-retry'); assert.equal(h.calls.at(-1), h.calls.at(-2)); await h.click('inventory-movements-toggle-deleted'); query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('hideDeleted'), 'false'); assert.equal(query.get('page'), '1'); assert.equal(toggle.textContent, '隐藏已删除记录'); assert.equal(toggle['aria-pressed'], 'false'); assert.equal(h.nodes.get('#stock-form'), h.form); assert.equal(JSON.stringify(h.form.values), before); assert.equal(h.nodes.get('#main').innerHTML, '合成库存整页'); }); test('切换已删除显示时丢弃旧响应,服务器返回错误筛选或漏过滤已删除行均不展示', async () => { const h = harness(), pending = []; h.context.__api = () => new Promise(resolve => pending.push(resolve)); const old = h.load(), latest = h.click('inventory-movements-toggle-deleted'); pending[1](result({ hideDeleted: true, note: '隐藏后的结果' })); await latest; pending[0](result({ note: '过期显示全部' })); await old; assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /隐藏后的结果/); assert.doesNotMatch(h.nodes.get('#inventory-movements-list').innerHTML, /过期显示全部/); for (const override of [ { hideDeleted: false }, { movements: result({ hideDeleted: true }).movements.map(row => ({ ...row, status: 'deleted' })) }, ]) { h.context.__api = async () => ({ ...result({ hideDeleted: true, note: '不应出现' }), ...override }); await h.load(); assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /流水数据与筛选不一致/); assert.doesNotMatch(h.nodes.get('#inventory-movements-list').innerHTML, /不应出现/); } }); test('无结果与服务端钳到末页时页码一致,两个边界均不可继续翻页', async () => { const h = harness(); h.run('inventoryMovementPage=8;'); h.context.__api = async () => result({ page: 8, total: 101 }); await h.load(); assert.equal(h.run('inventoryMovementPage'), 2); assert.match(h.nodes.get('#inventory-movements-pagination').innerHTML, /第 2 \/ 2 页/); assert.match(h.nodes.get('#inventory-movements-count').textContent, /101~101/); h.context.__api = async () => result({ page: 2, total: 0 }); await h.load(); assert.equal(h.run('inventoryMovementPage'), 1); assert.equal(h.nodes.get('#inventory-movements-count').textContent, '共 0 条'); assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /当前筛选下暂无/); assert.equal((h.nodes.get('#inventory-movements-pagination').innerHTML.match(/ disabled/g) || []).length, 2); const count = h.calls.length; await h.click('inventory-movements-page', 'previous'); await h.click('inventory-movements-page', 'next'); assert.equal(h.calls.length, count); }); test('读取失败可按原货盘类型和页码重试,加载时重复点击不会跳页', async () => { const h = harness(); h.run("inventoryMovementPocket='金料';inventoryMovementKind='increase';inventoryMovementPage=2;"); h.context.__api = async () => { throw new Error('合成断网'); }; await h.load(); assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /合成断网/); assert.equal(h.run('inventoryMovementPage'), 2); assert.equal(h.nodes.get('#inventory-movements-pagination').innerHTML, ''); h.context.__api = async () => result({ pocket: '金料', kind: 'increase', page: 2 }); await h.click('inventory-movements-retry'); assert.equal(h.calls.at(-1), h.calls.at(-2)); let resolve; h.context.__api = () => new Promise(done => { resolve = done; }); const next = h.click('inventory-movements-page', 'next'); await h.click('inventory-movements-page', 'next'); assert.equal(h.run('inventoryMovementPage'), 3); assert.equal(h.calls.length, 3); resolve(result({ pocket: '金料', kind: 'increase', page: 3 })); await next; assert.match(h.nodes.get('#inventory-movements-count').textContent, /201~205/); }); test('快速切筛选时较晚到达的旧成功和旧失败都不能覆盖新结果', async () => { const h = harness(), pending = []; h.context.__api = () => new Promise((resolve, reject) => pending.push({ resolve, reject })); const old = h.load(), current = h.change('inventory-movements-kind', 'increase'); pending[1].resolve(result({ kind: 'increase', note: '最新结果' })); await current; pending[0].resolve(result({ note: '不得显示的旧结果' })); await old; assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /最新结果/); assert.doesNotMatch(h.nodes.get('#inventory-movements-list').innerHTML, /不得显示/); const failed = h.load(), latest = h.change('inventory-movements-pocket', '金料'); pending[3].resolve(result({ pocket: '金料', kind: 'increase', note: '货盘新结果' })); await latest; pending[2].reject(new Error('过期错误')); await failed; assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /货盘新结果/); assert.doesNotMatch(h.nodes.get('#inventory-movements-list').innerHTML, /过期错误/); }); test('离开库存页或切换身份会丢弃旧响应,身份重置同时清除页码类型和货盘', async () => { for (const action of [ "tab='orders';invalidateInventoryMovementViews();", "invalidateInventoryMovementViews(true);state.user={id:'synthetic-other',member:'assistant2',role:'assistant'};", "state.user={id:'synthetic-owner',member:'assistant',role:'assistant'};", ]) { const h = harness(); h.run("inventoryMovementPocket='金料';inventoryMovementKind='increase';inventoryMovementPage=2;"); let resolve; h.context.__api = () => new Promise(done => { resolve = done; }); const loading = h.load(); h.run(action); const before = h.nodes.get('#inventory-movements-list').innerHTML; resolve(result({ pocket: '金料', kind: 'increase', page: 2, note: '旧身份记录' })); await loading; assert.equal(h.nodes.get('#inventory-movements-list').innerHTML, before); assert.equal(h.run('inventoryMovementPagination'), null); } const h = harness(); h.run( "inventoryMovementPocket='金料';inventoryMovementKind='increase';inventoryMovementHideDeleted=true;inventoryMovementPage=3;inventoryMovementPockets=[{pocket:'臻金汇',active:false}];invalidateInventoryMovementViews(true);", ); assert.deepEqual( h.json( '[inventoryMovementPocket,inventoryMovementKind,inventoryMovementHideDeleted,inventoryMovementPage,inventoryMovementPockets]', ), ['', 'all', false, 1, []], ); }); test('响应页码、数量或手动口径不符时不显示记录并可重新读取', async () => { for (const override of [ { page: 2 }, { totalPages: 1 }, { shown: 99 }, { hasNext: false }, { kind: 'all' }, { movements: result({ kind: 'increase' }).movements.map(row => ({ ...row, kind: 'return', order_id: 'synthetic-order', })), }, ]) { const h = harness(); h.run("inventoryMovementKind='increase';"); h.context.__api = async () => ({ ...result({ kind: 'increase', note: '不可展示的错页' }), ...override }); await h.load(); const html = h.nodes.get('#inventory-movements-list').innerHTML; assert.match(html, /流水数据与筛选不一致/); assert.match(html, /重新读取流水/); assert.doesNotMatch(html, /不可展示/); assert.equal(h.run('inventoryMovementPagination'), null); } }); test('导出按钮按当前货盘类型下载中文Excel全部记录,不传页码、不导航或清理库存草稿', async () => { const h = harness(), filename = '库存流水-金料-手动平移-2026-10-26.xlsx'; assert.match(h.run('stockMovements()'), /导出Excel/); assert.match(h.run('stockMovements()'), /包含其他页/); h.run("inventoryMovementPocket='现货';inventoryMovementKind='all';inventoryMovementPage=3;"); h.nodes.get('#inventory-movements-pocket').value = '金料'; h.nodes.get('#inventory-movements-kind').value = 'transfer'; h.context.__api = async () => ({ blob: new Blob(['PK合成文件']), contentDisposition: "attachment; filename=inventory.xlsx; filename*=UTF-8''" + encodeURIComponent(filename), }); const draft = JSON.stringify(h.form.values), html = h.nodes.get('#main').innerHTML; await h.click('inventory-movements-export'); const query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('pocket'), '金料'); assert.equal(query.get('kind'), 'transfer'); assert.equal(query.has('page'), false); assert.deepEqual(h.downloads, [{ href: 'blob:synthetic-xlsx', filename }]); assert.equal(h.run('inventoryMovementPage'), 3); assert.equal(h.nodes.get('#main').innerHTML, html); assert.equal(JSON.stringify(h.form.values), draft); assert.equal(h.nodes.get('#inventory-movements-export').disabled, false); assert.match(h.nodes.get('#inventory-movements-export-status').textContent, /所选日期、货盘与类型/); for (const timer of h.timers) timer(); assert.deepEqual(h.revoked, ['blob:synthetic-xlsx']); }); test('导出中禁止重复点击,切页回来重建的按钮在结束时恢复,不把旧响应下载到新账号', async () => { const h = harness(); let resolve; h.context.__api = () => new Promise(done => (resolve = done)); const pending = h.run('exportInventoryMovements()'); assert.equal(h.nodes.get('#inventory-movements-export').disabled, true); await h.run('exportInventoryMovements()'); assert.equal(h.calls.length, 1); h.nodes.get('#inventory-movements-export').isConnected = false; h.nodes.get('#inventory-movements-export-status').isConnected = false; const replacement = node({ disabled: true }); h.nodes.set('#inventory-movements-export', replacement); h.run("tab='settings';tab='stock';"); resolve({ blob: new Blob(['PK合成文件']), contentDisposition: null }); await pending; assert.equal(replacement.disabled, false); assert.equal(h.run('inventoryExporting'), false); assert.equal(h.downloads.length, 1); const switching = h.run('exportInventoryMovements()'); h.run("state.user={id:'another-user',role:'assistant',member:'assistant2'};session.user=state.user;"); resolve({ blob: new Blob(['PK合成文件']), contentDisposition: null }); await switching; assert.equal(h.downloads.length, 1); assert.equal(replacement.disabled, false); assert.equal(h.run('inventoryExporting'), false); }); test('导出失败给出具体提示并恢复按钮,筛选和页码保留可再次导出', async () => { const h = harness(); h.run('inventoryMovementPage=2'); h.context.__api = async () => { throw new Error('导出被拒绝403'); }; await h.run('exportInventoryMovements()'); assert.equal(h.downloads.length, 0); assert.match(h.nodes.get('#inventory-movements-export-status').textContent, /导出被拒绝403/); assert.equal(h.toasts.at(-1).error, true); assert.equal(h.nodes.get('#inventory-movements-export').disabled, false); assert.equal(h.run('inventoryMovementPage'), 2); h.context.__api = async () => ({ blob: new Blob(['PK合成文件']), contentDisposition: null }); await h.run('exportInventoryMovements()'); assert.equal(h.downloads.length, 1); assert.equal(h.run('inventoryMovementPage'), 2); }); test('Excel导出跟随隐藏筛选,下载期间切换显示设置会丢弃旧筛选文件', async () => { const h = harness(); await h.click('inventory-movements-toggle-deleted'); h.context.__api = async () => ({ blob: new Blob(['PK合成文件']), contentDisposition: null }); await h.click('inventory-movements-export'); let query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('hideDeleted'), 'true'); assert.equal(query.has('page'), false); assert.equal(h.downloads.length, 1); assert.match(h.nodes.get('#inventory-movements-export-status').textContent, /已隐藏已删除记录/); let resolve; h.context.__api = url => url.includes('export.xlsx') ? new Promise(done => (resolve = done)) : Promise.resolve(result()); const oldExport = h.run('exportInventoryMovements()'); await h.click('inventory-movements-toggle-deleted'); resolve({ blob: new Blob(['PK旧筛选']), contentDisposition: null }); await oldExport; assert.equal(h.downloads.length, 1); assert.equal(h.nodes.get('#inventory-movements-export').disabled, false); assert.equal(h.run('inventoryMovementHideDeleted'), false); }); test('导出期间货盘或类型变化时不下载旧文件,并提示按当前筛选重导', async () => { for (const [id, value] of [ ['inventory-movements-pocket', '金料'], ['inventory-movements-kind', 'manual'], ]) { const h = harness(); let resolve; h.context.__api = url => url.includes('export.xlsx') ? new Promise(done => (resolve = done)) : Promise.resolve( result({ pocket: id.includes('pocket') ? value : '', kind: id.includes('kind') ? value : 'all' }), ); const exporting = h.run('exportInventoryMovements()'); await h.change(id, value); resolve({ blob: new Blob(['PK旧筛选']), contentDisposition: null }); await exporting; assert.equal(h.downloads.length, 0); assert.match(h.nodes.get('#inventory-movements-export-status').textContent, /筛选已变化/); assert.equal(h.nodes.get('#inventory-movements-export').disabled, false); } }); test('日期区间重置页码,翻页和导出沿用日期,清空后恢复全部日期', async () => { const h = harness(); assert.match(h.run('stockMovements()'), /开始日期/); assert.match(h.run('stockMovements()'), /结束日期/); await h.load(); await h.click('inventory-movements-page', 'next'); await h.change('inventory-movements-from', '2026-10-25'); await h.change('inventory-movements-to', D); assert.equal(h.run('inventoryMovementPage'), 1); await h.click('inventory-movements-page', 'next'); let query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('from'), '2026-10-25'); assert.equal(query.get('to'), D); assert.equal(query.get('page'), '2'); const api = h.context.__api; h.context.__api = async () => ({ blob: new Blob(['PK合成文件']), contentDisposition: null }); await h.click('inventory-movements-export'); query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('from'), '2026-10-25'); assert.equal(query.get('to'), D); assert.equal(query.has('page'), false); assert.equal(h.downloads.length, 1); h.context.__api = api; await h.click('inventory-movements-clear-dates'); query = new URL(h.calls.at(-1), 'http://synthetic.invalid').searchParams; assert.equal(query.get('from'), ''); assert.equal(query.get('to'), ''); assert.equal(query.get('page'), '1'); }); test('倒置日期阻止导出,日期变化时丢弃旧文件和旧流水响应', async () => { const h = harness(); await h.change('inventory-movements-from', '2026-10-27'); await h.change('inventory-movements-to', D); assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /开始日期不能晚于结束日期/); const count = h.calls.length; await h.click('inventory-movements-export'); assert.equal(h.calls.length, count); assert.equal(h.downloads.length, 0); assert.match(h.toasts.at(-1).message, /开始日期不能晚于结束日期/); await h.click('inventory-movements-clear-dates'); let resolve; const api = h.context.__api; h.context.__api = url => (url.includes('export.xlsx') ? new Promise(done => (resolve = done)) : api(url)); const pending = h.run('exportInventoryMovements()'); await h.change('inventory-movements-from', D); resolve({ blob: new Blob(['PK旧日期']), contentDisposition: null }); await pending; assert.equal(h.downloads.length, 0); assert.match(h.nodes.get('#inventory-movements-export-status').textContent, /筛选已变化/); h.context.__api = async () => result({ note: '日期错误不可展示' }); await h.load(); assert.match(h.nodes.get('#inventory-movements-list').innerHTML, /流水数据与筛选不一致/); assert.doesNotMatch(h.nodes.get('#inventory-movements-list').innerHTML, /日期错误不可展示/); });