仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
670 lines
28 KiB
JavaScript
670 lines
28 KiB
JavaScript
'use strict';
|
|
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, today } = require('../ledger'),
|
|
{ createApp, createUser } = require('../server');
|
|
const OrderChanges = require('../order-changes');
|
|
const Rolling = require('../rolling-material-pools');
|
|
const D = '2026-10-01',
|
|
D2 = '2026-10-02',
|
|
D3 = '2026-10-03';
|
|
const line = (extra = {}) => ({
|
|
name: '足金合成挂件',
|
|
unit: 'g',
|
|
quantity: '1.000',
|
|
pocket: '现货',
|
|
payer: 'owner',
|
|
sale: '1419',
|
|
costParts: { material: '1200', labor: '50', accessories: '0', other: '0' },
|
|
...extra,
|
|
});
|
|
const contents = l =>
|
|
JSON.stringify(
|
|
l
|
|
.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
|
.map(({ name }) => [name, l.rows('SELECT * FROM "' + name + '"')]),
|
|
);
|
|
function fixture(t) {
|
|
const l = new Ledger(':memory:'),
|
|
actors = {};
|
|
t.after(() => l.close());
|
|
for (const member of ['owner', 'assistant', 'assistant2']) {
|
|
const actor = { id: randomUUID(), name: '合成' + member, role: member === 'owner' ? 'owner' : 'assistant' };
|
|
actors[member] = actor;
|
|
l.run('INSERT INTO users VALUES (?,?,?,?,?)', actor.id, actor.name, actor.role, 'synthetic-salt', 'synthetic-hash');
|
|
l.bindMemberUser(actor.id, member);
|
|
}
|
|
l.enableTeamMode();
|
|
const run = (input, fn, actor = actors.owner, key = randomUUID()) =>
|
|
l.scope(actor, () => l.transact(key, actor, input, fn));
|
|
run({}, () => l.stock({ date: D, kind: 'opening', pocket: '现货', grams: '20', note: '合成起始库存' }, actors.owner));
|
|
const issue = (extra = {}) => {
|
|
const input = {
|
|
date: D,
|
|
member: 'assistant',
|
|
customer: '合成客户',
|
|
salesperson: '合成开单人',
|
|
payment_account: '助理微信',
|
|
rounding_mode: 'cent',
|
|
fee_items: [{ key: 'shipping', note: '合成运费', amount: '10', payer: 'owner' }],
|
|
lines: [line()],
|
|
...extra,
|
|
};
|
|
return run(input, () => l.issueOrder(input, actors.owner)).id;
|
|
};
|
|
const data = (id, extra = {}) => ({
|
|
date: D2,
|
|
revision: l.detail(id).revision,
|
|
verified: true,
|
|
reason: '合成实物和退款已核实',
|
|
afterSale: {
|
|
lines: [{ lineIndex: 0, quantity: '1.000', pocket: '金料', disposition: 'scrap' }],
|
|
refund: { amount: '1300', account: '助理微信', payer: 'assistant', reference: '合成退款凭据' },
|
|
deductionReason: '合成客户已确认实际扣费',
|
|
expenses: [],
|
|
},
|
|
...extra,
|
|
});
|
|
const apply = (id, input = data(id), actor = actors.owner, key = randomUUID()) =>
|
|
run({ id, input }, () => l.action(id, 'return', input, actor), actor, key);
|
|
const report = (date = D, from = date, actor = actors.owner, member) =>
|
|
l.asActor(actor).reportFor({ date, from, basis: 'orderDate', ...(member ? { member } : {}) }, actor);
|
|
const close = (date = D) => run({ date }, () => l.closeDay(date, actors.owner, 'orderDate'));
|
|
return { l, actors, run, issue, data, apply, report, close };
|
|
}
|
|
function check(report) {
|
|
assert.equal(report.sales - report.totalCost, report.profit);
|
|
assert.equal(report.dailyProfits.summary.profit, report.profit);
|
|
for (const group of Object.values(report.ownershipBusiness)) {
|
|
assert.equal(group.sales - group.totalCost, group.profit);
|
|
assert.equal(
|
|
Object.values(group.costByPayer).reduce((n, row) => n + row.knownTotalCost, 0),
|
|
group.knownTotalCost,
|
|
);
|
|
}
|
|
return report;
|
|
}
|
|
|
|
test('一体售后旧料保留原日1419销售和159利润,售后日调减100,实退1300从新账户发生且不新增购料付款', t => {
|
|
const f = fixture(t),
|
|
id = f.issue(),
|
|
before = f.report();
|
|
f.close();
|
|
const original = f.l.detail(id),
|
|
purchases = f.l.rows('SELECT * FROM material_purchases');
|
|
const input = f.data(id);
|
|
input.afterSale.refund = {
|
|
amount: '1300',
|
|
account: '助理2支付宝',
|
|
payer: 'assistant2',
|
|
reference: '合成另一实际付款人',
|
|
};
|
|
f.apply(id, input);
|
|
const detail = f.l.detail(id),
|
|
old = check(f.report()),
|
|
current = check(f.report(D2)),
|
|
month = check(f.report(D2, D));
|
|
assert.equal(detail.orderAfterSale.summary.profit, 5900);
|
|
assert.equal(detail.orderAfterSale.summary.profitAdjustment, -10000);
|
|
assert.equal(detail.balance, 0);
|
|
assert.deepEqual([old.sales, old.totalCost, old.profit], [141900, 126000, 15900]);
|
|
assert.equal(old.reportRevision, before.reportRevision);
|
|
assert.equal(old.close.stale, false);
|
|
assert.deepEqual([current.sales, current.totalCost, current.profit], [-130000, -120000, -10000]);
|
|
assert.equal(current.outlayTotal, 0);
|
|
assert.equal(current.dailyProfits.summary.orderCount, 0);
|
|
assert.equal(current.dailyProfits.summary.afterSaleCount, 1);
|
|
assert.deepEqual([month.sales, month.totalCost, month.profit], [11900, 6000, 5900]);
|
|
assert.equal(month.orderRows.length, 2);
|
|
assert.equal(month.dailyProfits.summary.orderCount, 1);
|
|
assert.equal(old.recipientReceipts.assistant.receipt, 141900);
|
|
assert.equal(old.recipientReceipts.assistant2.refund, 0);
|
|
assert.equal(current.recipientReceipts.assistant2.refund, 130000);
|
|
assert.equal(current.ownershipReceipts.assistant.refund, 130000);
|
|
assert.equal(current.ownershipBusiness.assistant.ownerAdvances.days[0].amount, -120000);
|
|
assert.equal(current.ownershipBusiness.assistant.currentAccount.days[0].amount, -130000);
|
|
const team = current.dailyFunds.team;
|
|
assert.equal(team.balances.find(row => row.member === 'assistant2').refunds, 130000);
|
|
assert.equal(
|
|
team.balances.reduce((n, row) => n + row.outlays, 0),
|
|
0,
|
|
);
|
|
assert.equal(f.l.orderBook({ date: D2 }).receiptsByOrderDate.refund, 130000);
|
|
assert.equal(f.l.orderBook({ date: D }).receiptsByOrderDate.refund, 0);
|
|
assert.deepEqual(f.l.rows('SELECT * FROM material_purchases'), purchases);
|
|
assert.equal(JSON.stringify(f.l.detail(id).orderAfterSale.original.payments), JSON.stringify(original.payments));
|
|
assert.ok(!f.l.report(D2).warnings.some(row => row.id === id && /待退客户款/.test(row.message)));
|
|
});
|
|
|
|
test('退回现货工费是库存成本,售后负垫付与再售耗用闭环且无第二次工费现金', t => {
|
|
const f = fixture(t),
|
|
id = f.issue(),
|
|
input = f.data(id);
|
|
input.afterSale.lines[0] = { lineIndex: 0, quantity: '1.000', pocket: '现货', disposition: 'stock' };
|
|
f.apply(id, input);
|
|
const after = check(f.report(D2));
|
|
assert.equal(f.l.detail(id).orderAfterSale.summary.profit, 10900);
|
|
assert.equal(after.profit, -5000);
|
|
assert.equal(after.outlayTotal, 0);
|
|
assert.equal(after.ownershipBusiness.assistant.ownerAdvances.days[0].amount, -125000);
|
|
assert.equal(after.ownershipBusiness.assistant.currentAccount.days[0].amount, -130000);
|
|
const lot = f.l.returnedStockLots({ date: D2 }, f.actors.owner).lots[0];
|
|
assert.equal(lot.laborCost, 5000);
|
|
const next = f.issue({
|
|
date: D3,
|
|
fee_items: [],
|
|
lines: [
|
|
line({
|
|
sale: '1400',
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
}),
|
|
],
|
|
});
|
|
const day = check(f.report(D3));
|
|
assert.equal(f.l.detail(next).goodsCost, 125000);
|
|
assert.equal(day.profit, 15000);
|
|
assert.equal(day.outlayGoods, 0);
|
|
assert.equal(day.outlayTotal, 0);
|
|
assert.equal(day.ownershipBusiness.assistant.ownerAdvances.days[0].amount, 125000);
|
|
assert.equal(day.ownershipBusiness.assistant.currentAccount.days[0].amount, 140000);
|
|
assert.equal(
|
|
day.dailyFunds.team.balances.reduce((n, row) => n + row.outlays, 0),
|
|
0,
|
|
);
|
|
assert.equal(f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots.length, 0);
|
|
});
|
|
|
|
test('售后新增实际费用只进售后日,原核对不变,读取和跨成员筛选只读且隔离', t => {
|
|
const f = fixture(t),
|
|
id = f.issue(),
|
|
before = f.report();
|
|
f.close();
|
|
const input = f.data(id);
|
|
input.afterSale.expenses = [{ amount: '12.34', payer: 'owner', note: '合成重寄费用' }];
|
|
f.apply(id, input);
|
|
const foreign = f.issue({
|
|
date: D2,
|
|
member: 'assistant2',
|
|
customer: '不可见另一助理客户',
|
|
payment_account: '助理2微信',
|
|
});
|
|
f.apply(foreign, f.data(foreign));
|
|
const old = check(f.report()),
|
|
day = check(f.report(D2, D2, f.actors.assistant)),
|
|
ownerFiltered = check(f.report(D2, D2, f.actors.owner, 'assistant'));
|
|
assert.equal(old.reportRevision, before.reportRevision);
|
|
assert.equal(old.close.stale, false);
|
|
assert.equal(day.profit, -11234);
|
|
assert.equal(day.outlayTotal, 1234);
|
|
assert.equal(day.expense, 1234);
|
|
assert.equal(day.ownershipBusiness.assistant.ownerAdvances.days[0].amount, -118766);
|
|
assert.equal(day.ownershipBusiness.assistant.currentAccount.days[0].amount, -130000);
|
|
assert.deepEqual(day.dailyProfits, ownerFiltered.dailyProfits);
|
|
assert.equal(day.orderRows.length, 1);
|
|
assert.ok(!JSON.stringify(day).includes('不可见另一助理客户'));
|
|
const stored = contents(f.l);
|
|
f.report(D2, D);
|
|
f.report(D3);
|
|
f.report(D2, D2, f.actors.assistant);
|
|
assert.equal(contents(f.l), stored);
|
|
});
|
|
|
|
test('一体售后预览与历史申请保存点不改业务,审批效果排除随机ID并支持幂等与回滚', t => {
|
|
const f = fixture(t),
|
|
id = f.issue(),
|
|
input = f.data(id),
|
|
before = contents(f.l);
|
|
const preview = OrderChanges.previewAfterSale(f.l, id, input, f.actors.assistant, f.l.businessEnv());
|
|
assert.equal(preview.afterSale.summary.profit, 5900);
|
|
assert.equal(contents(f.l), before);
|
|
assert.throws(
|
|
() => f.apply(id, input, f.actors.assistant),
|
|
error => error.status === 403,
|
|
);
|
|
const requestInput = { action: 'return', ...input },
|
|
request = f.run(
|
|
{ id, requestInput },
|
|
() => f.l.requestOrderChange(id, requestInput, f.actors.assistant),
|
|
f.actors.assistant,
|
|
);
|
|
assert.equal(request.request.action_label, '订单售后');
|
|
assert.equal(request.request.action_input.afterSale.refund.amount, '1300');
|
|
assert.equal(f.l.detail(id).status, 'delivered');
|
|
assert.equal(f.l.rows('SELECT * FROM returned_stock_lots').length, 0);
|
|
const approve = { revision: request.request.order_revision, verified: true, note: '合成复核' },
|
|
key = randomUUID();
|
|
const accepted = f.run(
|
|
{ requestId: request.requestId, approve },
|
|
() => f.l.approveOrderChange(request.requestId, approve, f.actors.owner),
|
|
f.actors.owner,
|
|
key,
|
|
);
|
|
assert.equal(accepted.order.orderAfterSale.summary.profit, 5900);
|
|
assert.equal(accepted.request.status, 'approved');
|
|
const retry = f.run(
|
|
{ requestId: request.requestId, approve },
|
|
() => f.l.approveOrderChange(request.requestId, approve, f.actors.owner),
|
|
f.actors.owner,
|
|
key,
|
|
);
|
|
assert.equal(JSON.stringify(retry), JSON.stringify(accepted));
|
|
assert.equal(f.l.rows('SELECT * FROM order_after_sales').length, 1);
|
|
assert.equal(f.l.rows("SELECT * FROM payments WHERE kind='refund' AND order_id=?", id).length, 1);
|
|
});
|
|
|
|
test('售后HTTP预览和批次列表要求登录及成员权限,写入保留CSRF历史审批和幂等', async t => {
|
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-order-after-sale-http-')),
|
|
l = new Ledger(path.join(directory, 'ledger.sqlite'));
|
|
createUser(l, '麦麦', 'owner', 'synthetic-owner-password', 'owner');
|
|
createUser(l, '娜娜', 'assistant', 'synthetic-assistant-password', 'assistant');
|
|
createUser(l, '小昊', 'assistant', 'synthetic-assistant2-password', 'assistant2');
|
|
const app = createApp({ mode: 'trial', port: 0, dataDir: directory, ledger: l, 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);
|
|
});
|
|
l.close();
|
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
});
|
|
const base = 'http://127.0.0.1:' + app.server.address().port,
|
|
cookies = {};
|
|
const call = (who, route, body, key = randomUUID(), extra = {}) =>
|
|
fetch(base + route, {
|
|
method: body === undefined ? 'GET' : 'POST',
|
|
headers: {
|
|
...(cookies[who] ? { Cookie: cookies[who] } : {}),
|
|
...(body === undefined
|
|
? {}
|
|
: {
|
|
'Content-Type': 'application/json',
|
|
'X-Requested-With': 'maimai-ledger',
|
|
Origin: base,
|
|
...(key ? { 'Idempotency-Key': key } : {}),
|
|
}),
|
|
...extra,
|
|
},
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
});
|
|
for (const [who, name, password] of [
|
|
['owner', '麦麦', 'synthetic-owner-password'],
|
|
['assistant', '娜娜', 'synthetic-assistant-password'],
|
|
['assistant2', '小昊', 'synthetic-assistant2-password'],
|
|
]) {
|
|
const login = await call(who, '/api/login', { name, password });
|
|
assert.equal(login.status, 200);
|
|
cookies[who] = login.headers.get('set-cookie').split(';')[0];
|
|
}
|
|
const owner = l.one("SELECT id,name,role FROM users WHERE role='owner'"),
|
|
input = {
|
|
date: D,
|
|
member: 'assistant',
|
|
customer: '合成HTTP客户',
|
|
salesperson: '合成开单人',
|
|
payment_account: '助理微信',
|
|
rounding_mode: 'cent',
|
|
fee_items: [{ key: 'shipping', note: '合成运费', amount: '10', payer: 'owner' }],
|
|
lines: [line({ pocket: '' })],
|
|
},
|
|
id = l.scope(owner, () => l.issueOrder(input, owner)).id;
|
|
const body = {
|
|
date: D2,
|
|
revision: l.detail(id).revision,
|
|
verified: true,
|
|
reason: '合成HTTP退款核验',
|
|
afterSale: {
|
|
lines: [{ lineIndex: 0, quantity: '1.000', pocket: '现货', disposition: 'stock' }],
|
|
refund: { amount: '1300', account: '麦麦支付宝', payer: 'owner' },
|
|
deductionReason: '合成核实扣费',
|
|
expenses: [],
|
|
},
|
|
},
|
|
route = '/api/orders/' + id;
|
|
const script = await call('none', '/order-after-sales-ui.js');
|
|
assert.equal(script.status, 200);
|
|
assert.match(await script.text(), /OrderAfterSales|orderAfterSale/);
|
|
assert.equal((await call('none', route + '/after-sale')).status, 401);
|
|
assert.equal((await call('assistant2', route + '/after-sale')).status, 404);
|
|
assert.equal((await call('assistant', route + '/after-sale')).status, 200);
|
|
assert.equal(
|
|
(await call('assistant', route + '/after-sale-preview', body, null, { Origin: 'https://invalid.example' })).status,
|
|
403,
|
|
);
|
|
const before = contents(l),
|
|
preview = await call('assistant', route + '/after-sale-preview', body, null);
|
|
assert.equal(preview.status, 200);
|
|
assert.equal((await preview.json()).afterSale.summary.profit, 10900);
|
|
assert.equal(contents(l), before);
|
|
assert.equal((await call('assistant2', route + '/after-sale-preview', body, null)).status, 404);
|
|
assert.equal((await call('assistant', route + '/return', body)).status, 403);
|
|
const requestResponse = await call('assistant', route + '/change', { action: 'return', ...body }),
|
|
request = await requestResponse.json();
|
|
assert.equal(requestResponse.status, 200);
|
|
assert.equal(l.detail(id).status, 'delivered');
|
|
const approval = '/api/order-changes/' + request.requestId + '/approve',
|
|
decision = { revision: body.revision, verified: true };
|
|
assert.equal((await call('assistant', approval, decision)).status, 403);
|
|
const key = randomUUID(),
|
|
responses = await Promise.all([call('owner', approval, decision, key), call('owner', approval, decision, key)]);
|
|
assert.deepEqual(
|
|
responses.map(row => row.status),
|
|
[200, 200],
|
|
);
|
|
assert.deepEqual(await responses[0].json(), await responses[1].json());
|
|
const ownLots = await (await call('assistant', '/api/returned-stock-lots?date=' + D2)).json(),
|
|
foreignLots = await (await call('assistant2', '/api/returned-stock-lots?date=' + D2)).json();
|
|
assert.equal(ownLots.lots.length, 1);
|
|
assert.equal(foreignLots.lots.length, 0);
|
|
assert.equal((await call('assistant', '/api/returned-stock-lots?member=assistant2')).status, 403);
|
|
const current = await (await call('assistant', route + '/after-sale')).json();
|
|
assert.equal(current.record.summary.profit, 10900);
|
|
assert.equal(current.eligible, false);
|
|
assert.equal(l.rows("SELECT * FROM payments WHERE kind='refund' AND order_id=?", id).length, 1);
|
|
});
|
|
|
|
test('助理仅能同日原单和同日售后直接保存,历史实物退回即使今天也仍须麦麦审批', t => {
|
|
const f = fixture(t),
|
|
day = today(),
|
|
id = f.issue({ date: day }),
|
|
input = f.data(id, { date: day }),
|
|
key = randomUUID();
|
|
const first = f.apply(id, input, f.actors.assistant, key),
|
|
retry = f.apply(id, input, f.actors.assistant, key);
|
|
assert.equal(JSON.stringify(first), JSON.stringify(retry));
|
|
assert.equal(f.l.detail(id).orderAfterSale.summary.profit, 5900);
|
|
const previous = f.issue(),
|
|
historical = f.data(previous, { date: day }),
|
|
before = contents(f.l);
|
|
assert.throws(
|
|
() => f.apply(previous, historical, f.actors.assistant),
|
|
error => error.status === 403,
|
|
);
|
|
assert.equal(contents(f.l), before);
|
|
});
|
|
|
|
test('回料目标池的真实耗用和采购改变会使待审售后过期,原批准不能套用新FIFO结果', t => {
|
|
const f = fixture(t),
|
|
id = f.issue(),
|
|
input = { action: 'return', ...f.data(id) },
|
|
request = f.run(input, () => f.l.requestOrderChange(id, input, f.actors.assistant), f.actors.assistant);
|
|
const purchase = { date: D2, grams: '2', total: '2000', payer: 'owner', note: '合成回料目标日新采购' };
|
|
f.run(purchase, () => f.l.createMaterialPurchase(purchase, f.actors.owner));
|
|
assert.equal(f.l.orderChangeRequest(request.requestId, f.actors.owner).stale, true);
|
|
const before = contents(f.l);
|
|
assert.throws(
|
|
() =>
|
|
f.run({}, () =>
|
|
f.l.approveOrderChange(request.requestId, { revision: input.revision, verified: true }, f.actors.owner),
|
|
),
|
|
error => error.status === 409,
|
|
);
|
|
assert.equal(contents(f.l), before);
|
|
assert.equal(f.l.detail(id).status, 'delivered');
|
|
});
|
|
|
|
test('改单申请所选退回现货被另一订单占用后过期,批次余额纳入审批快照', t => {
|
|
const f = fixture(t),
|
|
origin = f.issue(),
|
|
sale = f.data(origin);
|
|
sale.afterSale.lines[0] = { lineIndex: 0, quantity: '1.000', pocket: '现货', disposition: 'stock' };
|
|
f.apply(origin, sale);
|
|
const lot = f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots[0],
|
|
candidate = f.issue({ date: D3, fee_items: [] }),
|
|
inputs = f.l.orderEdit(candidate, f.actors.assistant).inputs;
|
|
const requestInput = {
|
|
...inputs,
|
|
revision: f.l.detail(candidate).revision,
|
|
reason: '合成改为销售已退回的现货',
|
|
verified: true,
|
|
};
|
|
requestInput.lines[0] = {
|
|
...requestInput.lines[0],
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
};
|
|
const request = f.run(
|
|
requestInput,
|
|
() => f.l.requestOrderChange(candidate, requestInput, f.actors.assistant),
|
|
f.actors.assistant,
|
|
);
|
|
assert.equal(f.l.orderChangeRequest(request.requestId, f.actors.owner).stale, false);
|
|
assert.equal(f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots.length, 1);
|
|
f.issue({
|
|
date: D3,
|
|
fee_items: [],
|
|
lines: [
|
|
line({
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
}),
|
|
],
|
|
});
|
|
assert.equal(f.l.orderChangeRequest(request.requestId, f.actors.owner).stale, true);
|
|
const before = contents(f.l);
|
|
assert.throws(
|
|
() =>
|
|
f.run({}, () =>
|
|
f.l.approveOrderChange(request.requestId, { revision: requestInput.revision, verified: true }, f.actors.owner),
|
|
),
|
|
error => error.status === 409,
|
|
);
|
|
assert.equal(contents(f.l), before);
|
|
});
|
|
|
|
test('跨月售后只调整发生月份团队利润和分成,历史月份利润保持原值', t => {
|
|
const f = fixture(t),
|
|
id = f.issue({ date: '2026-09-30', lines: [line({ pocket: '' })] }),
|
|
september = f.l.teamProfits({ month: '2026-09' }, f.actors.owner).rows.find(row => row.member === 'assistant');
|
|
f.apply(id, f.data(id));
|
|
const original = f.l.teamProfits({ month: '2026-09' }, f.actors.owner).rows.find(row => row.member === 'assistant'),
|
|
current = f.l.teamProfits({ month: '2026-10' }, f.actors.owner).rows.find(row => row.member === 'assistant');
|
|
assert.deepEqual(original, september);
|
|
assert.equal(original.profit, 15900);
|
|
assert.equal(current.profit, -10000);
|
|
assert.equal(current.estimatedShare, -3000);
|
|
assert.equal(current.orderCount, 0);
|
|
assert.equal(current.afterSaleCount, 1);
|
|
});
|
|
|
|
for (const rolling of [false, true])
|
|
test(
|
|
(rolling ? '滚动历史审批' : '旧料池直接更正') + '购料只重估剩余金料,不改写已确认售后、原成本与售后日损益',
|
|
t => {
|
|
const f = fixture(t),
|
|
purchaseInput = { date: D, grams: '10', total: '6000', payer: 'owner', note: '合成原采购' },
|
|
purchase = f.run(purchaseInput, () => f.l.createMaterialPurchase(purchaseInput, f.actors.owner));
|
|
if (rolling) {
|
|
const env = { ...f.l.businessEnv(), today: () => D, now: () => D + 'T10:00:00.000Z' },
|
|
preview = Rolling.previewEnable(f.l, { date: D }, f.actors.owner, env);
|
|
f.run({}, () =>
|
|
Rolling.enable(f.l, { date: D, revision: preview.revision, verified: true }, f.actors.owner, env),
|
|
);
|
|
}
|
|
const id = Rolling.withHistorical(f.l, () =>
|
|
f.issue({
|
|
lines: [
|
|
line({
|
|
quantity: '2',
|
|
costParts: { material: '', labor: '50', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: D },
|
|
}),
|
|
],
|
|
}),
|
|
),
|
|
input = { action: 'return', ...f.data(id) };
|
|
input.afterSale.lines[0].quantity = '1.900';
|
|
const request = f.run(input, () => f.l.requestOrderChange(id, input, f.actors.assistant), f.actors.assistant);
|
|
f.run({}, () =>
|
|
f.l.approveOrderChange(request.requestId, { revision: input.revision, verified: true }, f.actors.owner),
|
|
);
|
|
const original = f.l.detail(id),
|
|
event = check(f.report(D2)),
|
|
oldRow = f.report().orderRows[0],
|
|
returns = f.l.rows('SELECT * FROM material_rolling_returns WHERE order_id=?', id);
|
|
const correction = { revision: 1, date: D, grams: '10', total: '8000', payer: 'owner', note: '合成核实购料总额' };
|
|
if (rolling) {
|
|
const change = f.run(correction, () =>
|
|
f.l.requestMaterialPurchaseChange(
|
|
purchase.id,
|
|
{ action: 'edit', reason: '合成核实历史采购', verified: true, ...correction },
|
|
f.actors.owner,
|
|
),
|
|
);
|
|
f.run({}, () => f.l.approveMaterialPurchaseChange(change.id, { revision: 1, verified: true }, f.actors.owner));
|
|
} else f.run(correction, () => f.l.editMaterialPurchase(purchase.id, correction, f.actors.owner));
|
|
assert.equal(JSON.stringify(f.l.detail(id).orderAfterSale), JSON.stringify(original.orderAfterSale));
|
|
assert.equal(f.l.detail(id).profit, original.profit);
|
|
assert.deepEqual(f.l.detail(id).lines, original.lines);
|
|
assert.deepEqual(f.l.rows('SELECT * FROM material_rolling_returns WHERE order_id=?', id), returns);
|
|
const current = check(f.report(D2));
|
|
for (const key of ['sales', 'goods', 'expense', 'totalCost', 'profit', 'reportRevision'])
|
|
assert.equal(current[key], event[key], key);
|
|
assert.deepEqual(f.report().orderRows[0], oldRow);
|
|
const before = contents(f.l),
|
|
bad = { ...correction, revision: 2, payer: 'assistant2' };
|
|
assert.throws(
|
|
() =>
|
|
rolling
|
|
? f.run(bad, () =>
|
|
f.l.requestMaterialPurchaseChange(
|
|
purchase.id,
|
|
{ action: 'edit', reason: '合成试图替换已冻结付款来源', verified: true, ...bad },
|
|
f.actors.owner,
|
|
),
|
|
)
|
|
: f.run(bad, () => f.l.editMaterialPurchase(purchase.id, bad, f.actors.owner)),
|
|
/已售后|来源|成本/,
|
|
);
|
|
assert.equal(contents(f.l), before);
|
|
},
|
|
);
|
|
|
|
test('退回现货再售后申请取消释放同一批次和工费耗用,改单复售也不增加实际工费付款', t => {
|
|
const f = fixture(t),
|
|
origin = f.issue(),
|
|
input = f.data(origin);
|
|
input.afterSale.lines[0] = { lineIndex: 0, quantity: '1', pocket: '现货', disposition: 'stock' };
|
|
f.apply(origin, input);
|
|
const lot = f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots[0],
|
|
resale = f.issue({
|
|
date: D3,
|
|
fee_items: [],
|
|
lines: [
|
|
line({
|
|
sale: '1400',
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
}),
|
|
],
|
|
}),
|
|
requestInput = { revision: f.l.detail(resale).revision, reason: '合成录错再售单' };
|
|
const request = f.run(
|
|
requestInput,
|
|
() => f.l.requestOrderCancellation(resale, requestInput, f.actors.assistant),
|
|
f.actors.assistant,
|
|
);
|
|
f.run({}, () =>
|
|
f.l.approveOrderCancellation(
|
|
request.requestId,
|
|
{ revision: requestInput.revision, verified: true },
|
|
f.actors.owner,
|
|
),
|
|
);
|
|
assert.equal(f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots[0].id, lot.id);
|
|
const day = check(f.report(D3));
|
|
assert.equal(day.profit, 0);
|
|
assert.equal(day.outlayTotal, 0);
|
|
assert.equal(
|
|
day.dailyFunds.team.balances.reduce((n, row) => n + row.outlays, 0),
|
|
0,
|
|
);
|
|
const retry = f.issue({
|
|
date: D3,
|
|
fee_items: [],
|
|
lines: [
|
|
line({
|
|
sale: '1400',
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
}),
|
|
],
|
|
});
|
|
const edit = {
|
|
...f.l.orderEdit(retry, f.actors.owner).inputs,
|
|
revision: f.l.detail(retry).revision,
|
|
reason: '合成只核实新售价',
|
|
verified: true,
|
|
};
|
|
edit.lines[0].sale = '1500';
|
|
edit.lines[0].baseSale = '1500';
|
|
f.run(edit, () => f.l.editOrder(retry, edit, f.actors.owner));
|
|
const result = check(f.report(D3));
|
|
assert.equal(result.profit, 25000);
|
|
assert.equal(result.outlayTotal, 0);
|
|
assert.equal(
|
|
result.dailyFunds.team.balances.reduce((n, row) => n + row.outlays, 0),
|
|
0,
|
|
);
|
|
});
|
|
|
|
test('滚动料池跨日销售退回现货使用销售日承接金料,继承工费按耗用确认且不新增付款', t => {
|
|
const f = fixture(t),
|
|
purchase = { date: D, grams: '2', total: '2400', payer: 'owner', note: '合成滚动来源' };
|
|
f.run(purchase, () => f.l.createMaterialPurchase(purchase, f.actors.owner));
|
|
const env = { ...f.l.businessEnv(), today: () => D, now: () => D + 'T10:00:00.000Z' },
|
|
enable = Rolling.previewEnable(f.l, { date: D }, f.actors.owner, env);
|
|
f.run({}, () => Rolling.enable(f.l, { date: D, revision: enable.revision, verified: true }, f.actors.owner, env));
|
|
const origin = Rolling.withHistorical(f.l, () =>
|
|
f.issue({
|
|
lines: [
|
|
line({
|
|
costParts: { material: '', labor: '50', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: D },
|
|
}),
|
|
],
|
|
}),
|
|
),
|
|
input = { action: 'return', ...f.data(origin) };
|
|
input.afterSale.lines[0] = { lineIndex: 0, quantity: '1.000', pocket: '现货', disposition: 'stock' };
|
|
const request = f.run(input, () => f.l.requestOrderChange(origin, input, f.actors.assistant), f.actors.assistant);
|
|
f.run({}, () =>
|
|
f.l.approveOrderChange(request.requestId, { revision: input.revision, verified: true }, f.actors.owner),
|
|
);
|
|
const lot = f.l.returnedStockLots({ date: D3 }, f.actors.owner).lots[0];
|
|
assert.equal(lot.effectivePoolId, D3);
|
|
const resale = Rolling.withHistorical(f.l, () =>
|
|
f.issue({
|
|
date: D3,
|
|
fee_items: [],
|
|
lines: [
|
|
line({
|
|
sale: '1400',
|
|
returnedStockId: lot.id,
|
|
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
|
|
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
|
|
}),
|
|
],
|
|
}),
|
|
),
|
|
report = check(f.report(D3));
|
|
assert.equal(f.l.detail(resale).goodsCost, 125000);
|
|
assert.equal(report.profit, 15000);
|
|
assert.equal(report.outlayTotal, 0);
|
|
assert.equal(report.ownershipBusiness.assistant.ownerAdvances.days[0].amount, 125000);
|
|
assert.equal(
|
|
report.dailyFunds.team.balances.reduce((n, row) => n + row.outlays, 0),
|
|
0,
|
|
);
|
|
});
|