- 50个后端模块用git mv移入core/与domains/<领域>/,入口server.js、launch.js、restore.js及server/原位不动 - 所有require路径由脚本按新旧位置统一换算(后端、server/、测试) - 新增test/app-paths.test.js,锁定默认数据目录、public目录与飞书配置文件的绝对位置 - 维护与部署.md补充目录说明并更新模块路径 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
429 lines
18 KiB
JavaScript
429 lines
18 KiB
JavaScript
'use strict';
|
|
const { historicalAction } = require('./fixtures/legacy-cancellation.cjs');
|
|
const { test } = require('node:test'),
|
|
assert = require('node:assert/strict'),
|
|
{ randomUUID } = require('node:crypto');
|
|
const fs = require('node:fs'),
|
|
os = require('node:os'),
|
|
path = require('node:path');
|
|
const { Ledger } = require('../core/ledger'),
|
|
{ createApp } = require('../server'),
|
|
Calc = require('../public/calculations');
|
|
const D = '2026-10-17',
|
|
NEXT = '2026-10-18',
|
|
owner = { id: 'pool-owner', name: '测试麦麦', role: 'owner' },
|
|
assistant = { id: 'pool-assistant', name: '测试助理', role: 'assistant' };
|
|
const line = (extra = {}) => ({
|
|
name: '足金999',
|
|
unit: 'g',
|
|
quantity: '3',
|
|
pocket: '',
|
|
payer: 'owner',
|
|
pricingMode: 'manual',
|
|
sale: '3000',
|
|
costParts: { material: '999999', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: D },
|
|
...extra,
|
|
});
|
|
const input = (extra = {}) => ({
|
|
date: D,
|
|
customer: '合成客户',
|
|
internal_note: '测试内部备注',
|
|
salesperson: '合成开单人',
|
|
discount: '0',
|
|
payment_account: '助理微信',
|
|
fee_items: [],
|
|
lines: [line()],
|
|
...extra,
|
|
});
|
|
const tables = [
|
|
'orders',
|
|
'payments',
|
|
'expenses',
|
|
'settlements',
|
|
'movements',
|
|
'journal',
|
|
'audit',
|
|
'operations',
|
|
'meta',
|
|
'sync',
|
|
'material_purchases',
|
|
'material_pool_usages',
|
|
'material_pool_events',
|
|
'material_pool_settlements',
|
|
];
|
|
const snapshot = ledger => Object.fromEntries(tables.map(table => [table, ledger.rows('SELECT * FROM ' + table)]));
|
|
function fixture(t) {
|
|
const l = new Ledger(':memory:');
|
|
t.after(() => l.close());
|
|
const run = (payload, fn, key = randomUUID(), actor = assistant) => l.transact(key, actor, payload, fn);
|
|
const buy = (grams = '10', total = '9000', payer = 'owner', date = D, key = randomUUID()) =>
|
|
run(
|
|
{ grams, total, payer, date },
|
|
() => l.createMaterialPurchase({ date, grams, total, payer, note: '原始采购凭据' }, assistant),
|
|
key,
|
|
);
|
|
const issue = (p = input(), key = randomUUID()) => run(p, () => l.issueOrder(p, assistant), key).id;
|
|
const save = (p = input()) => run(p, () => l.saveOrder(p, assistant)).id;
|
|
const act = (id, action, p = {}, actor = owner) =>
|
|
run({ id, action, p }, () => historicalAction(l, id, action, { date: D, ...p }, actor), randomUUID(), actor);
|
|
const settle = (id, amount, direction, extra = {}) => {
|
|
const p = { date: D, amount, direction, verified: true, revision: l.materialPoolDetail(id).revision, ...extra };
|
|
return run({ id, p }, () => l.settleMaterialPool(id, p, assistant));
|
|
};
|
|
return { l, run, buy, issue, save, act, settle };
|
|
}
|
|
test('同日采购按总金额除总克重加权,两位付款人留原始支付且订单不重复支出', t => {
|
|
const { l, buy, issue } = fixture(t);
|
|
buy();
|
|
buy('20', '18120', 'assistant');
|
|
const id = issue(),
|
|
o = l.detail(id),
|
|
pool = l.materialPoolDetail(D);
|
|
assert.equal(pool.totalMg, 30000);
|
|
assert.equal(pool.totalAmount, 2712000);
|
|
assert.equal(pool.averageRate, 90400);
|
|
assert.equal(o.goodsCost, 271200);
|
|
assert.equal(o.profit, 28800);
|
|
assert.equal(o.costParts, undefined);
|
|
assert.equal(pool.usedMg, 3000);
|
|
assert.equal(pool.remainingMg, 27000);
|
|
assert.equal(pool.status, 'using');
|
|
assert.deepEqual(o.lines[0].materialPool.allocations, [{ payer: 'owner', amount: 271200 }]);
|
|
assert.equal(o.settlementDue, 300000);
|
|
assert.equal(pool.settlement.settlementDue, -1812000);
|
|
assert.equal(l.report(D).settlementDue, -1512000);
|
|
assert.equal(l.rows('SELECT * FROM movements').length, 0);
|
|
assert.equal(l.rows('SELECT * FROM expenses').length, 0);
|
|
assert.equal(l.materialPoolReporting({ date: D }).purchases.length, 2);
|
|
assert.equal(
|
|
l.materialPoolReporting({ date: D }).purchases.reduce((n, r) => n + r.amount, 0),
|
|
2712000,
|
|
);
|
|
});
|
|
test('先交付打印后买料:缺口全部标待补,补足自动结转成本且客户款和库存保持不变', t => {
|
|
const { l, buy, issue } = fixture(t),
|
|
id = issue(),
|
|
pending = l.detail(id);
|
|
assert.equal(pending.status, 'delivered');
|
|
assert.equal(pending.goodsCost, null);
|
|
assert.equal(pending.profit, null);
|
|
assert.equal(pending.settlementDue, null);
|
|
assert.equal(pending.materialCostPending, true);
|
|
assert.equal(pending.knownProfit, 0);
|
|
assert.equal(pending.knownSettlementDue, 0);
|
|
assert.equal(l.report(D).profit, null);
|
|
assert.equal(l.report(D).knownProfit, 0);
|
|
assert.equal(l.reportByOrderDate(D).summary.partial, true);
|
|
const cash = l.rows('SELECT * FROM payments'),
|
|
stock = l.rows('SELECT * FROM movements'),
|
|
order = l.publicOrder(id);
|
|
buy('1', '900', 'assistant');
|
|
assert.equal(l.materialPoolDetail(D).shortageMg, 2000);
|
|
assert.equal(l.detail(id).profit, null);
|
|
buy('2', '1800', 'owner');
|
|
const final = l.detail(id);
|
|
assert.equal(final.goodsCost, 270000);
|
|
assert.equal(final.profit, 30000);
|
|
assert.equal(final.materialCostPending, false);
|
|
assert.equal(l.materialPoolDetail(D).status, 'exhausted');
|
|
assert.equal(l.report(D).profit, 30000);
|
|
assert.deepEqual(l.rows('SELECT * FROM payments'), cash);
|
|
assert.deepEqual(l.rows('SELECT * FROM movements'), stock);
|
|
assert.deepEqual(l.publicOrder(id), order);
|
|
assert.equal(l.rows("SELECT * FROM journal WHERE kind='日购料成本调整'").length, 1);
|
|
});
|
|
test('后开订单超过池克重时所有相关料费转待补,再补足时原单一起恢复,流水不重复', t => {
|
|
const { l, buy, issue } = fixture(t);
|
|
buy('5', '4500', 'owner');
|
|
const first = issue(),
|
|
second = issue();
|
|
assert.equal(l.detail(first).profit, null);
|
|
assert.equal(l.detail(second).profit, null);
|
|
assert.equal(l.materialPoolDetail(D).usedMg, 6000);
|
|
assert.equal(l.materialPoolDetail(D).shortageMg, 1000);
|
|
buy('1', '960', 'assistant');
|
|
assert.equal(l.detail(first).goodsCost, 273000);
|
|
assert.equal(l.detail(second).goodsCost, 273000);
|
|
assert.equal(l.detail(first).profit, 27000);
|
|
assert.equal(l.detail(second).profit, 27000);
|
|
assert.equal(l.report(D).profit, 54000);
|
|
assert.equal(l.rows('SELECT * FROM payments').length, 2);
|
|
assert.equal(l.rows("SELECT * FROM journal WHERE kind='交付'").length, 2);
|
|
assert.equal(l.rows('SELECT SUM(goods) AS amount FROM journal')[0].amount, 546000);
|
|
});
|
|
test('当天追加采购重估已耗成本并追加差额,原采购、售价、收款、库存、单号不改写', t => {
|
|
const { l, buy, issue } = fixture(t);
|
|
buy();
|
|
const id = issue(),
|
|
before = l.detail(id),
|
|
purchase = l.rows('SELECT * FROM material_purchases'),
|
|
cash = l.rows('SELECT * FROM payments'),
|
|
stock = l.rows('SELECT * FROM movements');
|
|
buy('10', '10000', 'assistant');
|
|
const after = l.detail(id);
|
|
assert.equal(before.goodsCost, 270000);
|
|
assert.equal(after.goodsCost, 285000);
|
|
assert.equal(after.profit, 15000);
|
|
assert.equal(after.paper_number, before.paper_number);
|
|
assert.equal(after.total, before.total);
|
|
assert.deepEqual(l.rows('SELECT * FROM payments'), cash);
|
|
assert.deepEqual(l.rows('SELECT * FROM movements'), stock);
|
|
assert.deepEqual(l.rows('SELECT * FROM material_purchases')[0], purchase[0]);
|
|
const adjustment = l.rows("SELECT * FROM journal WHERE kind='日购料成本调整'");
|
|
assert.equal(adjustment.length, 1);
|
|
assert.equal(adjustment[0].goods, 15000);
|
|
assert.equal(adjustment[0].date, D);
|
|
assert.ok(l.rows('SELECT * FROM material_pool_events').some(row => row.kind === '加权料费调整'));
|
|
});
|
|
test('整数分毫克分摊守恒,微量多行用尽时消耗金额恰等于采购金额,付款人相加不溢出', t => {
|
|
const { l, buy, issue } = fixture(t);
|
|
buy('0.002', '0.01', 'owner');
|
|
buy('0.005', '0.03', 'assistant');
|
|
const ids = Array.from({ length: 7 }, () => issue(input({ lines: [line({ quantity: '0.001', sale: '1' })] })));
|
|
const pool = l.materialPoolDetail(D);
|
|
assert.equal(pool.usedMg, 7);
|
|
assert.equal(pool.remainingMg, 0);
|
|
assert.equal(pool.consumedCost, 4);
|
|
assert.equal(pool.remainingCost, 0);
|
|
assert.equal(pool.byPayer.owner.consumed, 1);
|
|
assert.equal(pool.byPayer.assistant.consumed, 3);
|
|
assert.equal(
|
|
ids.reduce((n, id) => n + l.detail(id).goodsCost, 0),
|
|
4,
|
|
);
|
|
for (const id of ids) {
|
|
const o = l.detail(id),
|
|
parts = Calc.orderCosts(o);
|
|
assert.equal(parts.byPayer.owner.goods + parts.byPayer.assistant.goods, o.goodsCost);
|
|
assert.ok(o.goodsCost >= 0);
|
|
}
|
|
assert.equal(Calc.poolMaterialAmount(4, 7, 1), 1);
|
|
assert.equal(Calc.poolMaterialAmount(4, 7, 7), 4);
|
|
});
|
|
test('老池余额可选,草稿确认不占用料池,取消不造释放或耗用事件', t => {
|
|
const { l, buy, save, issue, act } = fixture(t);
|
|
buy();
|
|
const id = save(input({ date: NEXT }));
|
|
act(id, 'confirm', { date: NEXT });
|
|
assert.equal(l.materialPoolDetail(D).usedMg, 0);
|
|
act(id, 'cancel', { date: NEXT, reason: '取消测试' });
|
|
assert.equal(l.materialPoolDetail(D).usedMg, 0);
|
|
assert.equal(l.rows('SELECT * FROM material_pool_usages').length, 0);
|
|
const delivered = issue(input({ date: NEXT }));
|
|
assert.equal(l.detail(delivered).goodsCost, 270000);
|
|
assert.equal(l.materialPoolDetail(D).remainingMg, 7000);
|
|
});
|
|
test('实物退回自有货盘释放日购料,助理工费另抵扣,退货退款后双方现金守恒', t => {
|
|
const { l, buy, issue, act } = fixture(t);
|
|
buy('2', '1800', 'assistant');
|
|
const id = issue(
|
|
input({
|
|
lines: [
|
|
line({
|
|
quantity: '2',
|
|
sale: '2000',
|
|
payer: 'assistant',
|
|
costParts: { material: '', labor: '40', accessories: '0', other: '0' },
|
|
}),
|
|
],
|
|
}),
|
|
);
|
|
assert.equal(l.report(D).settlementDue, 16000);
|
|
const before = snapshot(l);
|
|
assert.throws(() => act(id, 'return', { verified: true, reason: '退货' }), /自有货盘/);
|
|
assert.deepEqual(snapshot(l), before);
|
|
act(id, 'return', { verified: true, reason: '退货', returnPockets: ['金料'] });
|
|
const pool = l.materialPoolDetail(D);
|
|
assert.equal(pool.usedMg, 0);
|
|
assert.equal(pool.remainingMg, 2000);
|
|
assert.equal(pool.byPayer.assistant.remaining, 180000);
|
|
assert.equal(l.detail(id).assistantInventoryCredit, 4000);
|
|
assert.equal(l.detail(id).profit, 0);
|
|
assert.equal(l.inventory().find(row => row.pocket === '金料').mg, 2000);
|
|
act(id, 'refund', { verified: true, amount: '2000', account: '助理微信' });
|
|
assert.equal(l.report(D).settlementDue, -184000);
|
|
assert.equal(l.rows('SELECT * FROM material_purchases').length, 1);
|
|
assert.equal(l.rows('SELECT * FROM material_pool_events WHERE kind=?', '实物退回释放').length, 1);
|
|
});
|
|
test('已结剩余垫款再消耗自动转成可回收余额,跨池及订单合计不重复报销', t => {
|
|
const { l, buy, issue, settle } = fixture(t);
|
|
buy('10', '9000', 'assistant');
|
|
settle(D, '9000', 'toAssistant');
|
|
assert.equal(l.materialPoolDetail(D).settlement.settlementDue, 0);
|
|
const id = issue();
|
|
assert.equal(l.detail(id).settlementDue, 30000);
|
|
assert.equal(l.materialPoolDetail(D).settlement.settlementDue, 270000);
|
|
assert.equal(l.report(D).settlementDue, 300000);
|
|
assert.equal(l.materialPoolReporting({ date: D }).settlements[0].amount, -900000);
|
|
settle(D, '2700', 'toOwner');
|
|
assert.equal(l.report(D).settlementDue, 30000);
|
|
});
|
|
test('购料和交付重试幂等,采购超精度、非法日期、单位和锁价池注入均原子拒绝', t => {
|
|
const { l, buy, issue, run } = fixture(t),
|
|
key = randomUUID();
|
|
buy('10', '9000', 'owner', D, key);
|
|
buy('10', '9000', 'owner', D, key);
|
|
assert.equal(l.rows('SELECT * FROM material_purchases').length, 1);
|
|
const p = input(),
|
|
orderKey = randomUUID();
|
|
assert.equal(issue(p, orderKey), issue(p, orderKey));
|
|
assert.equal(l.rows('SELECT * FROM material_pool_usages').length, 1);
|
|
const before = snapshot(l);
|
|
for (const bad of [
|
|
{ date: D, grams: '1.0001', total: '1', payer: 'owner' },
|
|
{ date: D, grams: '1', total: '1.001', payer: 'owner' },
|
|
{ date: D, grams: '0', total: '1', payer: 'owner' },
|
|
{ date: '2026-02-30', grams: '1', total: '1', payer: 'owner' },
|
|
{ date: D, grams: '1', total: '1', payer: 'other' },
|
|
])
|
|
assert.throws(() => run(bad, () => l.createMaterialPurchase(bad, assistant)));
|
|
for (const badLine of [
|
|
line({ unit: '件', quantity: '1' }),
|
|
line({ name: '纯银925' }),
|
|
line({ costMaterial: { mode: 'pool', poolId: NEXT } }),
|
|
])
|
|
assert.throws(() => issue(input({ lines: [badLine] })));
|
|
assert.deepEqual(snapshot(l), before);
|
|
});
|
|
test('缺口不能结算,采购变化使旧结算版本失效,失败不留下转款或审计半笔', t => {
|
|
const { l, buy, issue, settle, run } = fixture(t),
|
|
id = issue();
|
|
assert.throws(() => settle(D, '1', 'toAssistant'), /缺口/);
|
|
buy('5', '4500', 'assistant');
|
|
const revision = l.materialPoolDetail(D).revision;
|
|
buy('1', '900', 'owner');
|
|
const before = snapshot(l),
|
|
p = { date: D, amount: '1', direction: 'toAssistant', verified: true, revision };
|
|
assert.throws(() => run(p, () => l.settleMaterialPool(D, p, assistant)), /有新变动/);
|
|
assert.deepEqual(snapshot(l), before);
|
|
assert.throws(() => settle(D, '1', 'toOwner'), /方向或金额/);
|
|
assert.equal(l.detail(id).goodsCost, 270000);
|
|
});
|
|
test('混合手填与日购料订单独立核算,采购重估不触动旧手填订单', t => {
|
|
const { l, buy, issue } = fixture(t);
|
|
const manual = {
|
|
...line(),
|
|
costMaterial: { mode: 'total' },
|
|
costParts: { material: '100', labor: '0', accessories: '0', other: '0' },
|
|
};
|
|
const historical = issue(input({ lines: [manual] })),
|
|
frozen = l.detail(historical);
|
|
buy();
|
|
const id = issue(input({ lines: [line(), manual] }));
|
|
assert.equal(l.detail(id).goodsCost, 280000);
|
|
buy('10', '10000', 'assistant');
|
|
assert.equal(l.detail(id).goodsCost, 295000);
|
|
assert.deepEqual(l.detail(historical), frozen);
|
|
});
|
|
test('退回一单可消除其他单缺口,已退订单销售成本冲回且后续采购不重估原退单', t => {
|
|
const { l, buy, issue, act } = fixture(t);
|
|
buy('3', '2700', 'owner');
|
|
const first = issue(),
|
|
second = issue();
|
|
assert.equal(l.detail(first).profit, null);
|
|
act(second, 'return', { verified: true, reason: '退货', returnPockets: ['金料'] });
|
|
assert.equal(l.detail(first).profit, 30000);
|
|
assert.equal(l.detail(second).profit, 0);
|
|
assert.equal(l.materialPoolDetail(D).shortageMg, 0);
|
|
act(second, 'refund', { verified: true, amount: '3000', account: '助理微信' });
|
|
const returned = l.detail(second);
|
|
buy('3', '3000', 'assistant');
|
|
assert.deepEqual(l.detail(second), returned);
|
|
assert.equal(l.detail(first).goodsCost, 285000);
|
|
});
|
|
test('更换已交付来源池只调整成本与池余量,不重记销售、款项、费用或库存', t => {
|
|
const { l, buy, issue, act } = fixture(t);
|
|
buy();
|
|
buy('10', '10000', 'assistant', '2026-10-16');
|
|
const id = issue(),
|
|
before = l.detail(id),
|
|
cash = l.rows('SELECT * FROM payments'),
|
|
stock = l.rows('SELECT * FROM movements');
|
|
const source = { revision: before.revision, pools: ['2026-10-16'] },
|
|
state = snapshot(l);
|
|
assert.throws(
|
|
() => act(id, 'material', source, assistant),
|
|
error => error.status === 403,
|
|
);
|
|
assert.deepEqual(snapshot(l), state);
|
|
act(id, 'material', source, owner);
|
|
const o = l.detail(id);
|
|
assert.equal(o.goodsCost, 300000);
|
|
assert.equal(o.profit, 0);
|
|
assert.equal(l.materialPoolDetail(D).usedMg, 0);
|
|
assert.equal(l.materialPoolDetail('2026-10-16').usedMg, 3000);
|
|
assert.deepEqual(l.rows('SELECT * FROM payments'), cash);
|
|
assert.deepEqual(l.rows('SELECT * FROM movements'), stock);
|
|
assert.equal(l.rows("SELECT * FROM journal WHERE kind='交付'").length, 1);
|
|
});
|
|
test('HTTP购料受登录CSRF和幂等保护,客户接口打印隔离内部来源,重开数据库保留追溯', async t => {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-material-pool-http-')),
|
|
app = createApp({ mode: 'demo', dataDir: dir, feishuConfig: { enabled: false } });
|
|
await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve));
|
|
t.after(async () => {
|
|
await new Promise(resolve => {
|
|
app.server.closeAllConnections();
|
|
app.server.close(resolve);
|
|
});
|
|
app.ledger.close();
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
const base = 'http://127.0.0.1:' + app.server.address().port;
|
|
let cookie = '';
|
|
const call = (route, data, key = randomUUID(), origin = base) =>
|
|
fetch(base + route, {
|
|
method: data ? 'POST' : 'GET',
|
|
headers: {
|
|
Cookie: cookie,
|
|
...(data
|
|
? {
|
|
'Content-Type': 'application/json',
|
|
Origin: origin,
|
|
'X-Requested-With': 'maimai-ledger',
|
|
'Idempotency-Key': key,
|
|
}
|
|
: {}),
|
|
},
|
|
...(data ? { body: JSON.stringify(data) } : {}),
|
|
});
|
|
const p = {
|
|
date: D,
|
|
grams: '10',
|
|
total: '9000',
|
|
payer: 'assistant',
|
|
allocations: [{ member: 'assistant', amount: '9000' }],
|
|
};
|
|
assert.equal((await call('/api/material-purchases', p)).status, 401);
|
|
const login = await call('/api/demo-login', { role: 'assistant' });
|
|
cookie = login.headers.get('set-cookie').split(';')[0];
|
|
assert.equal((await call('/api/material-purchases', p, randomUUID(), 'https://invalid.example')).status, 403);
|
|
const key = randomUUID(),
|
|
responses = await Promise.all([call('/api/material-purchases', p, key), call('/api/material-purchases', p, key)]);
|
|
assert.deepEqual(
|
|
responses.map(r => r.status),
|
|
[200, 200],
|
|
);
|
|
assert.equal((await responses[0].json()).id, (await responses[1].json()).id);
|
|
const created = await call('/api/orders/issue', input());
|
|
assert.equal(created.status, 200);
|
|
const { id } = await created.json();
|
|
const pools = await (await call('/api/material-pools')).json();
|
|
assert.equal(pools.rows.length, 1);
|
|
assert.equal(pools.rows[0].usedMg, 3000);
|
|
const publicOrder = JSON.stringify(await (await call('/api/orders/' + id + '/public')).json()),
|
|
printed = await (await call('/print/' + id)).text();
|
|
for (const key of ['materialPool', 'costMaterial', 'allocations', 'costParts', 'payer']) {
|
|
assert.ok(!publicOrder.includes('"' + key + '"'));
|
|
assert.ok(!printed.includes(key));
|
|
}
|
|
const reopened = new Ledger(path.join(dir, 'ledger.sqlite'));
|
|
try {
|
|
assert.equal(reopened.detail(id).goodsCost, 270000);
|
|
assert.equal(reopened.materialPoolDetail(D).purchases.length, 1);
|
|
assert.equal(reopened.materialPoolDetail(D).usages.length, 1);
|
|
} finally {
|
|
reopened.close();
|
|
}
|
|
});
|