1023 lines
40 KiB
JavaScript
1023 lines
40 KiB
JavaScript
'use strict';
|
|
// 两版对账共用的校验和归集规则。成员、当前查询以及日期校验由调用方提供。
|
|
(function (root) {
|
|
function reportAfterSaleAmount(cost) {
|
|
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + item.amount, 0);
|
|
}
|
|
|
|
function reportCostItems(cost) {
|
|
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
|
}
|
|
|
|
function reportRowCost(row) {
|
|
const goods = (row.costItems || []).filter(item => item.kind === 'goods');
|
|
return {
|
|
goods: goods.reduce((sum, item) => sum + (item.amount ?? 0), 0),
|
|
missing: goods.filter(item => item.amount == null).length,
|
|
paidFees: (row.costItems || [])
|
|
.filter(item => ['paid', 'afterSale'].includes(item.kind))
|
|
.reduce((sum, item) => sum + item.amount, 0),
|
|
};
|
|
}
|
|
|
|
function reportCurrentAccountDays(business) {
|
|
const account = business.currentAccount;
|
|
return account.days.length
|
|
? account.days
|
|
: account.from === account.date
|
|
? [
|
|
{
|
|
date: account.date,
|
|
materialCost: 0,
|
|
knownMaterialCost: 0,
|
|
otherCost: 0,
|
|
knownOtherCost: 0,
|
|
profit: 0,
|
|
knownProfit: 0,
|
|
ownerNetReceipts: 0,
|
|
amount: 0,
|
|
incomplete: false,
|
|
},
|
|
]
|
|
: [];
|
|
}
|
|
|
|
function reimbursementAmounts(items, cents) {
|
|
let total = 0,
|
|
complete = true;
|
|
const amounts = [];
|
|
for (const item of items) {
|
|
try {
|
|
const amount = cents(item.amount);
|
|
if (!amount) complete = false;
|
|
total += amount;
|
|
amounts.push(amount);
|
|
} catch {
|
|
complete = false;
|
|
}
|
|
}
|
|
return {
|
|
total,
|
|
complete,
|
|
amounts,
|
|
};
|
|
}
|
|
|
|
function forContext({
|
|
teamDataKeys,
|
|
validOrderDate,
|
|
teamMode,
|
|
currentMember,
|
|
teamMemberKeys,
|
|
isReimbursementStatus,
|
|
state,
|
|
reportMember,
|
|
}) {
|
|
function validateReport(r, range) {
|
|
if (r.basis !== 'orderDate' || r.date !== range.date || r.from !== range.from)
|
|
throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
|
|
if (
|
|
!r.summary ||
|
|
!Array.isArray(r.orderRows) ||
|
|
!Array.isArray(r.accounts) ||
|
|
!r.receiptsByOrderDate ||
|
|
!teamDataKeys(r.payerCosts).length ||
|
|
!teamDataKeys(r.payerCosts).every(key => {
|
|
const c = r.payerCosts?.[key];
|
|
return (
|
|
c &&
|
|
Array.isArray(c.items) &&
|
|
['goods', 'paidFees', 'total', 'missingCount', 'pendingCount'].every(name => Number.isSafeInteger(c[name]))
|
|
);
|
|
})
|
|
)
|
|
throw new Error('对账数据尚未完整返回,请重新读取。');
|
|
const recipientKeys = teamDataKeys(r.recipientReceipts),
|
|
recipients = recipientKeys.map(key => r.recipientReceipts?.[key]);
|
|
if (
|
|
!recipientKeys.length ||
|
|
!recipients.every(
|
|
(person, index) =>
|
|
person &&
|
|
person.recipient === recipientKeys[index] &&
|
|
typeof person.name === 'string' &&
|
|
person.name &&
|
|
Array.isArray(person.items) &&
|
|
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(person[key])) &&
|
|
person.items.every(
|
|
item =>
|
|
item &&
|
|
['receipt', 'refund'].includes(item.kind) &&
|
|
Number.isSafeInteger(item.amount) &&
|
|
typeof item.account === 'string' &&
|
|
validOrderDate(item.date),
|
|
) &&
|
|
person.net === person.receipt - person.refund &&
|
|
['receipt', 'refund'].every(
|
|
kind =>
|
|
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + item.amount, 0) ===
|
|
person[kind],
|
|
),
|
|
) ||
|
|
!['receipt', 'refund', 'net'].every(
|
|
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
|
)
|
|
)
|
|
throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
|
|
validateOwnershipReceipts(r);
|
|
validateOwnershipBusiness(r);
|
|
validateDailyProfits(r);
|
|
}
|
|
|
|
function validateDailyFunds(data, range) {
|
|
if (data?.team) {
|
|
if (data.date !== range.date || data.from !== range.from || !Array.isArray(data.reimbursements))
|
|
throw new Error('团队日期或报销资料未完整返回,请重新读取。');
|
|
validateTeamFunds(data.team);
|
|
data.reimbursements.forEach(validateReimbursement);
|
|
return data;
|
|
}
|
|
const money = value => Number.isSafeInteger(value),
|
|
nullable = value => value === null || money(value);
|
|
if (
|
|
!data ||
|
|
data.date !== range.date ||
|
|
data.from !== range.from ||
|
|
typeof data.readOnly !== 'boolean' ||
|
|
typeof data.ready !== 'boolean' ||
|
|
!['receipt', 'refund', 'net'].every(key => money(data.ownerReceipts?.[key])) ||
|
|
data.ownerReceipts.net !== data.ownerReceipts.receipt - data.ownerReceipts.refund ||
|
|
!money(data.approvedReimbursements) ||
|
|
!nullable(data.actualOutlay) ||
|
|
!nullable(data.transferAmount) ||
|
|
data.transfersNotDeducted !== true ||
|
|
!Array.isArray(data.reimbursements) ||
|
|
!Array.isArray(data.days) ||
|
|
!Array.isArray(data.missingDates) ||
|
|
!Array.isArray(data.staleDates) ||
|
|
!Number.isSafeInteger(data.pendingCount) ||
|
|
data.pendingCount < 0 ||
|
|
typeof data.sources?.revision !== 'string' ||
|
|
!money(data.sources.total) ||
|
|
!Array.isArray(data.sources.items) ||
|
|
!data.sources.items.every(
|
|
item =>
|
|
item &&
|
|
typeof item.id === 'string' &&
|
|
validOrderDate(item.date) &&
|
|
money(item.amount) &&
|
|
item.payer === 'owner' &&
|
|
typeof item.name === 'string',
|
|
) ||
|
|
data.sources.items.reduce((sum, item) => sum + item.amount, 0) !== data.sources.total
|
|
)
|
|
throw new Error('转账核对资料未完整返回,请重新读取。');
|
|
data.reimbursements.forEach(validateReimbursement);
|
|
if (
|
|
data.confirmation &&
|
|
(!money(data.confirmation.amount) ||
|
|
data.confirmation.amount < 0 ||
|
|
!Number.isSafeInteger(data.confirmation.revision) ||
|
|
typeof data.confirmation.sourceRevision !== 'string' ||
|
|
typeof data.confirmation.stale !== 'boolean')
|
|
)
|
|
throw new Error('实际支出确认资料未完整返回,请重新读取。');
|
|
if (
|
|
(data.ready &&
|
|
(data.actualOutlay == null ||
|
|
data.transferAmount !== data.ownerReceipts.net - data.actualOutlay + data.approvedReimbursements)) ||
|
|
(!data.ready && data.transferAmount !== null)
|
|
)
|
|
throw new Error('转账合计与分项不一致,请重新读取。');
|
|
if (!range.month && range.from === range.date && data.ready && (!data.confirmation || data.confirmation.stale))
|
|
throw new Error('当天支出尚未有效确认,请重新读取。');
|
|
return data;
|
|
}
|
|
|
|
function validateDailyReimbursements(data) {
|
|
if (
|
|
!data ||
|
|
!Array.isArray(data.requests) ||
|
|
!Number.isSafeInteger(data.total) ||
|
|
!Number.isSafeInteger(data.offset) ||
|
|
!Number.isSafeInteger(data.limit) ||
|
|
typeof data.hasMore !== 'boolean' ||
|
|
!['pending', 'approved', 'rejected'].every(key => Number.isSafeInteger(data.counts?.[key]))
|
|
)
|
|
throw new Error('全日期报销列表未完整返回,请重新读取。');
|
|
data.requests.forEach(validateReimbursement);
|
|
return data;
|
|
}
|
|
|
|
function validateOwnershipReceipts(r) {
|
|
const fail = () => {
|
|
throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');
|
|
},
|
|
keys = teamDataKeys(r.ownershipReceipts),
|
|
selected = teamMode() ? (state.user.role === 'owner' ? reportMember : currentMember()) : '',
|
|
expected = selected ? [selected] : teamMode() ? teamMemberKeys() : teamDataKeys(r.recipientReceipts);
|
|
if (
|
|
!r.ownershipReceipts ||
|
|
typeof r.ownershipReceipts !== 'object' ||
|
|
Array.isArray(r.ownershipReceipts) ||
|
|
Object.keys(r.ownershipReceipts).length !== expected.length ||
|
|
keys.length !== expected.length ||
|
|
!expected.every(key => keys.includes(key))
|
|
)
|
|
fail();
|
|
const receipts = [],
|
|
owned = [],
|
|
sum = (items, kind) => items.filter(item => item.kind === kind).reduce((total, item) => total + item.amount, 0);
|
|
for (const key of keys) {
|
|
const person = r.ownershipReceipts[key];
|
|
if (
|
|
!person ||
|
|
person.member !== key ||
|
|
typeof person.name !== 'string' ||
|
|
!person.name ||
|
|
!Array.isArray(person.accounts) ||
|
|
!Array.isArray(person.items) ||
|
|
!['receipt', 'refund', 'net'].every(name => Number.isSafeInteger(person[name])) ||
|
|
person.net !== person.receipt - person.refund
|
|
)
|
|
fail();
|
|
if (
|
|
!person.items.every(
|
|
item =>
|
|
item &&
|
|
['receipt', 'refund'].includes(item.kind) &&
|
|
Number.isSafeInteger(item.amount) &&
|
|
typeof item.account === 'string' &&
|
|
validOrderDate(item.date),
|
|
) ||
|
|
!['receipt', 'refund'].every(kind => sum(person.items, kind) === person[kind])
|
|
)
|
|
fail();
|
|
const accounts = new Set();
|
|
for (const account of person.accounts) {
|
|
if (
|
|
!account ||
|
|
typeof account.account !== 'string' ||
|
|
!account.account ||
|
|
accounts.has(account.account) ||
|
|
!teamMemberKeys().includes(account.recipient) ||
|
|
!['wechat', 'alipay', 'cash', 'credit_card'].includes(account.channel) ||
|
|
!['receipt', 'refund', 'net', 'entryCount'].every(name => Number.isSafeInteger(account[name])) ||
|
|
account.entryCount < 1 ||
|
|
account.net !== account.receipt - account.refund
|
|
)
|
|
fail();
|
|
const items = person.items.filter(item => item.account === account.account);
|
|
if (
|
|
items.length !== account.entryCount ||
|
|
!['receipt', 'refund'].every(kind => sum(items, kind) === account[kind])
|
|
)
|
|
fail();
|
|
accounts.add(account.account);
|
|
}
|
|
if (
|
|
person.items.some(item => !accounts.has(item.account)) ||
|
|
!['receipt', 'refund', 'net'].every(
|
|
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
|
)
|
|
)
|
|
fail();
|
|
receipts.push(person);
|
|
owned.push(...person.items);
|
|
}
|
|
if (
|
|
!['receipt', 'refund', 'net'].every(
|
|
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
|
)
|
|
)
|
|
fail();
|
|
const identity = item =>
|
|
JSON.stringify([item.id, item.kind, item.amount, item.account, item.date, item.order_id, item.price_lock_id]),
|
|
actual = teamDataKeys(r.recipientReceipts)
|
|
.flatMap(key => r.recipientReceipts[key].items)
|
|
.map(identity)
|
|
.sort(),
|
|
copies = owned.map(identity).sort();
|
|
if (actual.length !== copies.length || actual.some((value, index) => value !== copies[index])) fail();
|
|
}
|
|
|
|
function validateOwnershipBusiness(r) {
|
|
const fail = () => {
|
|
throw new Error('所属订单成本、利润或待转资料未完整返回,请重新读取。');
|
|
},
|
|
money = value => Number.isSafeInteger(value),
|
|
nullable = value => value === null || money(value),
|
|
count = value => money(value) && value >= 0,
|
|
keys = teamDataKeys(r.ownershipReceipts);
|
|
if (
|
|
!r.ownershipBusiness ||
|
|
typeof r.ownershipBusiness !== 'object' ||
|
|
Array.isArray(r.ownershipBusiness) ||
|
|
Object.keys(r.ownershipBusiness).length !== keys.length ||
|
|
!keys.every(key => Object.hasOwn(r.ownershipBusiness, key))
|
|
)
|
|
fail();
|
|
for (const member of keys) {
|
|
const b = r.ownershipBusiness[member];
|
|
if (
|
|
!b ||
|
|
b.member !== member ||
|
|
typeof b.name !== 'string' ||
|
|
!b.name ||
|
|
b.basis !== 'orderDate' ||
|
|
b.from !== r.from ||
|
|
b.date !== r.date ||
|
|
b.netReceipts !== r.ownershipReceipts[member].net ||
|
|
!['sales', 'netReceipts', 'knownTotalCost', 'knownSelfCost', 'knownOtherCost', 'knownProfit'].every(key =>
|
|
money(b[key]),
|
|
) ||
|
|
!['totalCost', 'selfCost', 'otherCost', 'profit'].every(key => nullable(b[key])) ||
|
|
![
|
|
'missingCostCount',
|
|
'pendingCostCount',
|
|
'unknownProfitCount',
|
|
'draftCount',
|
|
'recordCount',
|
|
'orderCount',
|
|
'afterSaleCount',
|
|
].every(key => count(b[key])) ||
|
|
typeof b.incomplete !== 'boolean' ||
|
|
typeof b.hasActivity !== 'boolean'
|
|
)
|
|
fail();
|
|
if (
|
|
b.knownSelfCost + b.knownOtherCost !== b.knownTotalCost ||
|
|
(b.totalCost !== null && b.totalCost !== b.knownTotalCost) ||
|
|
(b.selfCost !== null && b.selfCost !== b.knownSelfCost) ||
|
|
(b.otherCost !== null && b.otherCost !== b.knownOtherCost)
|
|
)
|
|
fail();
|
|
if (!b.costByPayer || Object.keys(b.costByPayer).length !== teamMemberKeys().length) fail();
|
|
for (const payer of teamMemberKeys()) {
|
|
const row = b.costByPayer[payer];
|
|
if (
|
|
!row ||
|
|
row.member !== payer ||
|
|
typeof row.name !== 'string' ||
|
|
!row.name ||
|
|
!nullable(row.totalCost) ||
|
|
!money(row.knownTotalCost) ||
|
|
!count(row.missingCount) ||
|
|
!count(row.pendingCount) ||
|
|
(row.totalCost !== null && row.totalCost !== row.knownTotalCost)
|
|
)
|
|
fail();
|
|
}
|
|
if (
|
|
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].knownTotalCost, 0) !== b.knownTotalCost ||
|
|
b.costByPayer[member].knownTotalCost !== b.knownSelfCost ||
|
|
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].missingCount, 0) !== b.missingCostCount ||
|
|
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].pendingCount, 0) !== b.pendingCostCount
|
|
)
|
|
fail();
|
|
const recoveries = reportAfterSaleRecoveryCosts(r, b, fail);
|
|
validatePoolMaterialCosts(b, recoveries, fail);
|
|
validateOwnerAdvances(b, recoveries, fail);
|
|
validateCurrentAccount(b, r.ownershipReceipts[member], fail);
|
|
const difference = b.difference,
|
|
equation = b.equation,
|
|
settlement = b.settlement;
|
|
if (
|
|
!difference ||
|
|
difference.amount !== b.netReceipts - b.sales ||
|
|
typeof difference.reconciled !== 'boolean' ||
|
|
!Array.isArray(difference.reasons) ||
|
|
!difference.reasons.every(
|
|
reason => reason && typeof reason.code === 'string' && typeof reason.text === 'string',
|
|
)
|
|
)
|
|
fail();
|
|
if (
|
|
!equation ||
|
|
!['netReceipts', 'sales'].includes(equation.basis) ||
|
|
equation.revenue !== (equation.basis === 'netReceipts' ? b.netReceipts : b.sales) ||
|
|
equation.totalCost !== b.totalCost ||
|
|
equation.profit !== b.profit ||
|
|
typeof equation.complete !== 'boolean' ||
|
|
(equation.complete &&
|
|
(!money(equation.totalCost) ||
|
|
!money(equation.profit) ||
|
|
equation.revenue - equation.totalCost !== equation.profit))
|
|
)
|
|
fail();
|
|
if (
|
|
!settlement ||
|
|
typeof settlement.available !== 'boolean' ||
|
|
settlement.basis !== 'cumulative-through-date' ||
|
|
settlement.from !== r.from ||
|
|
settlement.date !== r.date ||
|
|
typeof settlement.partial !== 'boolean' ||
|
|
!count(settlement.pendingCount) ||
|
|
!count(settlement.legacyCount) ||
|
|
typeof settlement.notice !== 'string' ||
|
|
!Array.isArray(settlement.counterparts)
|
|
)
|
|
fail();
|
|
if (
|
|
settlement.available
|
|
? !count(settlement.dueOut) || !count(settlement.dueIn)
|
|
: settlement.dueOut !== null || settlement.dueIn !== null
|
|
)
|
|
fail();
|
|
const seen = new Set();
|
|
for (const row of settlement.counterparts) {
|
|
if (
|
|
!row ||
|
|
!teamMemberKeys().includes(row.member) ||
|
|
row.member === member ||
|
|
seen.has(row.member) ||
|
|
typeof row.name !== 'string' ||
|
|
!row.name ||
|
|
!['dueOut', 'dueIn', 'offset'].every(key => count(row[key])) ||
|
|
!['openingDue', 'periodNew', 'periodTransferred', 'closingDue'].every(key => money(row[key])) ||
|
|
row.openingDue + row.periodNew - row.periodTransferred !== row.closingDue ||
|
|
row.dueOut !== Math.max(0, row.closingDue) ||
|
|
row.dueIn !== Math.max(0, -row.closingDue) ||
|
|
!row.period ||
|
|
row.period.obligationNet !== row.periodNew ||
|
|
row.period.transferred !== row.periodTransferred ||
|
|
!money(row.period.receivedForNet) ||
|
|
!money(row.period.advancedNet) ||
|
|
row.period.receivedForNet + row.period.advancedNet !== row.periodNew
|
|
)
|
|
fail();
|
|
seen.add(row.member);
|
|
}
|
|
if (
|
|
settlement.available &&
|
|
['dueOut', 'dueIn'].some(
|
|
key => settlement.counterparts.reduce((total, row) => total + row[key], 0) !== settlement[key],
|
|
)
|
|
)
|
|
fail();
|
|
}
|
|
}
|
|
|
|
function validateDailyProfits(r) {
|
|
const fail = () => {
|
|
throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');
|
|
},
|
|
table = r.dailyProfits,
|
|
money = Number.isSafeInteger,
|
|
count = value => money(value) && value >= 0,
|
|
nullable = value => value === null || money(value),
|
|
members = teamDataKeys(r.ownershipReceipts);
|
|
const amounts = ['sales', 'knownTotalCost', 'knownProfit'],
|
|
counts = [
|
|
'recordCount',
|
|
'orderCount',
|
|
'afterSaleCount',
|
|
'draftCount',
|
|
'unknownCostCount',
|
|
'unknownProfitCount',
|
|
];
|
|
const valid = row =>
|
|
row &&
|
|
amounts.every(key => money(row[key])) &&
|
|
counts.every(key => count(row[key])) &&
|
|
nullable(row.totalCost) &&
|
|
nullable(row.profit) &&
|
|
typeof row.incomplete === 'boolean' &&
|
|
row.recordCount === row.orderCount + row.afterSaleCount &&
|
|
row.draftCount <= row.orderCount &&
|
|
row.unknownCostCount <= row.recordCount &&
|
|
row.unknownProfitCount <= row.recordCount &&
|
|
row.totalCost === (row.unknownCostCount ? null : row.knownTotalCost) &&
|
|
row.profit === (row.unknownProfitCount ? null : row.knownProfit) &&
|
|
(row.unknownCostCount || row.unknownProfitCount ? row.incomplete : true) &&
|
|
(row.profit === null || (row.totalCost !== null && row.sales - row.totalCost === row.profit));
|
|
if (
|
|
!table ||
|
|
table.basis !== 'orderDate' ||
|
|
table.from !== r.from ||
|
|
table.date !== r.date ||
|
|
!Array.isArray(table.rows) ||
|
|
!valid(table.summary)
|
|
)
|
|
fail();
|
|
let previousDate = '',
|
|
previousIndex = -1;
|
|
for (const row of table.rows) {
|
|
if (
|
|
!valid(row) ||
|
|
!row.recordCount ||
|
|
!members.includes(row.member) ||
|
|
typeof row.name !== 'string' ||
|
|
!row.name ||
|
|
!validOrderDate(row.date) ||
|
|
row.date < r.from ||
|
|
row.date > r.date
|
|
)
|
|
fail();
|
|
const index = teamMemberKeys().indexOf(row.member);
|
|
if (row.date < previousDate || (row.date === previousDate && index <= previousIndex)) fail();
|
|
previousDate = row.date;
|
|
previousIndex = index;
|
|
}
|
|
if (
|
|
[...amounts, ...counts].some(
|
|
key => table.rows.reduce((sum, row) => sum + row[key], 0) !== table.summary[key],
|
|
) ||
|
|
table.rows.some(row => row.incomplete) !== table.summary.incomplete ||
|
|
table.summary.sales !== r.summary.sale ||
|
|
table.summary.knownTotalCost !== r.summary.totalCost ||
|
|
table.summary.knownProfit !== r.summary.profit ||
|
|
table.summary.recordCount !== r.orderRows.length ||
|
|
table.summary.unknownProfitCount !== (r.summary.unknownProfitCount || 0) + (r.summary.draftCount || 0) ||
|
|
table.summary.unknownCostCount !== (r.summary.unknownCostCount || 0) + (r.summary.draftCount || 0)
|
|
)
|
|
fail();
|
|
}
|
|
|
|
function validateTeamFunds(report) {
|
|
const money = value => Number.isSafeInteger(value);
|
|
if (
|
|
!report ||
|
|
!Array.isArray(report.pairs) ||
|
|
!Array.isArray(report.balances) ||
|
|
!Array.isArray(report.transfers) ||
|
|
report.revision == null ||
|
|
!validOrderDate(report.from) ||
|
|
!validOrderDate(report.to)
|
|
)
|
|
throw new Error('团队账目未完整返回,请重新读取。');
|
|
for (const pair of report.pairs) {
|
|
if (
|
|
!pair ||
|
|
!Array.isArray(pair.members) ||
|
|
pair.members.length !== 2 ||
|
|
pair.members[0] === pair.members[1] ||
|
|
!pair.members.every(member => teamMemberKeys().includes(member)) ||
|
|
!['net', 'obligationNet', 'transferred', 'due'].every(key => money(pair[key])) ||
|
|
pair.due < 0 ||
|
|
Math.abs(pair.net) !== pair.due ||
|
|
!Array.isArray(pair.entries)
|
|
)
|
|
throw new Error('两人往来金额未完整返回,请重新读取。');
|
|
if (state.user.role !== 'owner' && !pair.members.includes(currentMember()))
|
|
throw new Error('返回了其他成员的往来,请重新登录。');
|
|
}
|
|
return report;
|
|
}
|
|
|
|
function validateReimbursement(row) {
|
|
if (
|
|
!row ||
|
|
typeof row.id !== 'string' ||
|
|
!row.id ||
|
|
!validOrderDate(row.date) ||
|
|
!isReimbursementStatus(row.status) ||
|
|
!Number.isSafeInteger(row.revision) ||
|
|
row.revision < 1 ||
|
|
typeof row.canEdit !== 'boolean' ||
|
|
typeof row.canApprove !== 'boolean' ||
|
|
!Array.isArray(row.items) ||
|
|
!row.items.length ||
|
|
row.items.length > 60 ||
|
|
!row.items.every(
|
|
item => typeof item.name === 'string' && item.name && Number.isSafeInteger(item.amount) && item.amount > 0,
|
|
) ||
|
|
!Number.isSafeInteger(row.total) ||
|
|
row.items.reduce((sum, item) => sum + item.amount, 0) !== row.total
|
|
)
|
|
throw new Error('报销单未完整返回,请重新读取。');
|
|
return row;
|
|
}
|
|
|
|
function reportAfterSaleRecoveryCosts(r, b, fail) {
|
|
const money = Number.isSafeInteger,
|
|
count = value => money(value) && value >= 0,
|
|
items = [],
|
|
byPayer = Object.fromEntries(teamMemberKeys().map(key => [key, 0]));
|
|
const identity = item =>
|
|
JSON.stringify([item.component, item.payer, item.amount, item.source, item.materialPoolId ?? null]);
|
|
for (const row of r.orderRows.filter(
|
|
row => row.kind === 'orderAfterSale' && (row.member ?? (teamMode() ? null : 'assistant')) === b.member,
|
|
)) {
|
|
const record = row.orderAfterSale,
|
|
summary = record?.summary,
|
|
original = record?.originalOrder ?? record?.original,
|
|
expected = [];
|
|
if (
|
|
row.status !== 'after_sale' ||
|
|
!validOrderDate(row.date) ||
|
|
row.date < b.from ||
|
|
row.date > b.date ||
|
|
record?.date !== row.date ||
|
|
(record.order_id ?? record.orderId) !== (row.order_id ?? row.id) ||
|
|
!summary ||
|
|
!Array.isArray(summary.lines) ||
|
|
!summary.lines.length ||
|
|
!Array.isArray(row.costItems) ||
|
|
!count(summary.materialReturnedCost) ||
|
|
!count(summary.laborRestockedCost)
|
|
)
|
|
fail();
|
|
for (const line of summary.lines) {
|
|
if (!line || !count(line.lineIndex) || typeof line.name !== 'string') fail();
|
|
for (const [component, key, totalKey] of [
|
|
['material', 'materialAllocations', 'materialReturnedCost'],
|
|
['labor', 'restockedLaborAllocations', 'laborRestockedCost'],
|
|
]) {
|
|
const parts = line[key];
|
|
if (
|
|
!Array.isArray(parts) ||
|
|
!count(line[totalKey]) ||
|
|
parts.some(part => !part || !teamMemberKeys().includes(part.payer) || !count(part.amount)) ||
|
|
parts.reduce((sum, part) => sum + part.amount, 0) !== line[totalKey]
|
|
)
|
|
fail();
|
|
for (const part of parts)
|
|
if (part.amount)
|
|
expected.push({
|
|
component,
|
|
payer: part.payer,
|
|
amount: -part.amount,
|
|
source: `商品 ${line.lineIndex + 1} · ${line.name}`,
|
|
materialPoolId: component === 'material' ? row.date : null,
|
|
});
|
|
}
|
|
}
|
|
if (
|
|
['materialReturnedCost', 'laborRestockedCost'].some(
|
|
key => summary.lines.reduce((sum, line) => sum + line[key], 0) !== summary[key],
|
|
)
|
|
)
|
|
fail();
|
|
const recovered = row.costItems.filter(item => item?.nonCash === true),
|
|
actual = recovered.map(identity).sort(),
|
|
wanted = expected.map(identity).sort();
|
|
if (
|
|
actual.length !== wanted.length ||
|
|
actual.some((value, index) => value !== wanted[index]) ||
|
|
row.costItems.some(
|
|
item =>
|
|
!item ||
|
|
!teamMemberKeys().includes(item.payer) ||
|
|
!money(item.amount) ||
|
|
(item.nonCash === true
|
|
? item.kind !== 'goods' || item.amount >= 0
|
|
: item.kind !== 'paid' ||
|
|
item.component !== 'fee' ||
|
|
item.afterSaleExpense !== true ||
|
|
item.amount < 0),
|
|
) ||
|
|
row.costItems.reduce((sum, item) => sum + item.amount, 0) !== row.known?.totalCost ||
|
|
row.totalCost !== row.known.totalCost ||
|
|
!money(original?.total) ||
|
|
!money(summary.retainedAmount) ||
|
|
row.sale !== summary.retainedAmount - original.total ||
|
|
!money(row.profit) ||
|
|
row.profit !== summary.profitAdjustment ||
|
|
row.sale - row.totalCost !== row.profit
|
|
)
|
|
fail();
|
|
for (const item of recovered) {
|
|
byPayer[item.payer] += item.amount;
|
|
items.push({
|
|
...item,
|
|
id: row.id,
|
|
date: row.date,
|
|
});
|
|
}
|
|
}
|
|
return {
|
|
byPayer,
|
|
items,
|
|
};
|
|
}
|
|
|
|
function validatePoolMaterialCosts(b, recoveries, fail) {
|
|
const money = Number.isSafeInteger,
|
|
count = value => money(value) && value >= 0,
|
|
nullable = value => value === null || count(value),
|
|
pool = b.poolMaterial;
|
|
const valid = value =>
|
|
value &&
|
|
['mg', 'knownAmount', 'missingCount'].every(key => count(value[key])) &&
|
|
nullable(value.amount) &&
|
|
value.amount === (value.missingCount ? null : value.knownAmount) &&
|
|
value.byPayer &&
|
|
Object.keys(value.byPayer).length === teamMemberKeys().length &&
|
|
teamMemberKeys().every(key => {
|
|
const payer = value.byPayer[key];
|
|
return (
|
|
payer &&
|
|
count(payer.knownAmount) &&
|
|
nullable(payer.amount) &&
|
|
payer.amount === (value.missingCount ? null : payer.knownAmount)
|
|
);
|
|
}) &&
|
|
teamMemberKeys().reduce((sum, key) => sum + value.byPayer[key].knownAmount, 0) === value.knownAmount;
|
|
if (
|
|
!valid(pool) ||
|
|
typeof pool.hasPriceLocks !== 'boolean' ||
|
|
!Array.isArray(pool.days) ||
|
|
pool.missingCount > b.missingCostCount ||
|
|
!pool.otherCosts ||
|
|
!money(pool.otherCosts.knownAmount) ||
|
|
!(pool.otherCosts.amount === null || money(pool.otherCosts.amount)) ||
|
|
(pool.otherCosts.amount !== null && pool.otherCosts.amount !== pool.otherCosts.knownAmount)
|
|
)
|
|
fail();
|
|
const seen = new Set();
|
|
for (const day of pool.days) {
|
|
if (
|
|
!valid(day) ||
|
|
day.mg <= 0 ||
|
|
!/^\d{4}-\d{2}-\d{2}$/.test(day.poolId) ||
|
|
day.date !== day.poolId ||
|
|
!nullable(day.averageRate)
|
|
)
|
|
fail();
|
|
if (day.sources !== undefined) {
|
|
if (
|
|
!Array.isArray(day.sources) ||
|
|
!day.sources.length ||
|
|
day.sources.some(
|
|
source =>
|
|
!source ||
|
|
!['public', 'personal_recovery'].includes(source.kind) ||
|
|
(source.kind === 'personal_recovery'
|
|
? !teamMemberKeys().includes(source.member)
|
|
: source.member !== null) ||
|
|
typeof source.priceLocked !== 'boolean' ||
|
|
!count(source.mg) ||
|
|
source.mg <= 0 ||
|
|
!nullable(source.averageRate) ||
|
|
!count(source.knownAmount) ||
|
|
!count(source.missingCount) ||
|
|
!nullable(source.amount) ||
|
|
source.amount !== (source.missingCount ? null : source.knownAmount),
|
|
) ||
|
|
day.sources.reduce((sum, source) => sum + source.mg, 0) !== day.mg ||
|
|
day.sources.reduce((sum, source) => sum + source.knownAmount, 0) < day.knownAmount ||
|
|
(!day.missingCount &&
|
|
(day.sources.some(source => source.missingCount) ||
|
|
day.sources.reduce((sum, source) => sum + source.knownAmount, 0) !== day.knownAmount)) ||
|
|
day.averageRate !== (day.sources.length === 1 ? day.sources[0].averageRate : null)
|
|
)
|
|
fail();
|
|
}
|
|
const key = day.poolId + ':' + (day.sources ? 'sources' : day.averageRate);
|
|
if (seen.has(key)) fail();
|
|
seen.add(key);
|
|
}
|
|
if (
|
|
['mg', 'knownAmount', 'missingCount'].some(
|
|
key => pool.days.reduce((sum, day) => sum + day[key], 0) !== pool[key],
|
|
) ||
|
|
teamMemberKeys().some(
|
|
key =>
|
|
pool.days.reduce((sum, day) => sum + day.byPayer[key].knownAmount, 0) !== pool.byPayer[key].knownAmount ||
|
|
pool.byPayer[key].knownAmount > b.costByPayer[key].knownTotalCost - recoveries.byPayer[key],
|
|
) ||
|
|
pool.otherCosts.knownAmount - teamMemberKeys().reduce((sum, key) => sum + recoveries.byPayer[key], 0) < 0 ||
|
|
pool.knownAmount + pool.otherCosts.knownAmount !== b.knownTotalCost ||
|
|
(b.totalCost !== null &&
|
|
(pool.amount === null ||
|
|
pool.otherCosts.amount === null ||
|
|
pool.amount + pool.otherCosts.amount !== b.totalCost))
|
|
)
|
|
fail();
|
|
}
|
|
|
|
function validateOwnerAdvances(b, recoveries, fail) {
|
|
const money = Number.isSafeInteger,
|
|
count = value => money(value) && value >= 0,
|
|
nullable = value => value === null || money(value),
|
|
advances = b.ownerAdvances;
|
|
const identity = item =>
|
|
JSON.stringify([
|
|
item.id,
|
|
item.date,
|
|
item.component,
|
|
item.source,
|
|
item.poolId ?? item.materialPoolId ?? null,
|
|
item.amount,
|
|
]),
|
|
remaining = recoveries.items.filter(item => item.payer === 'owner').map(identity);
|
|
if (
|
|
!advances ||
|
|
advances.basis !== 'orderDate' ||
|
|
advances.from !== b.from ||
|
|
advances.date !== b.date ||
|
|
!Array.isArray(advances.days)
|
|
)
|
|
fail();
|
|
let previous = '',
|
|
knownTotal = 0;
|
|
for (const day of advances.days) {
|
|
if (
|
|
!day ||
|
|
typeof day.date !== 'string' ||
|
|
day.date < b.from ||
|
|
day.date > b.date ||
|
|
day.date <= previous ||
|
|
!/^\d{4}-\d{2}-\d{2}$/.test(day.date) ||
|
|
!Array.isArray(day.items) ||
|
|
!day.items.length ||
|
|
!['knownAmount', 'knownPoolAmount', 'knownOtherAmount'].every(key => money(day[key])) ||
|
|
!['missingCount', 'pendingCount'].every(key => count(day[key])) ||
|
|
!['amount', 'poolAmount', 'otherAmount'].every(key => nullable(day[key]))
|
|
)
|
|
fail();
|
|
for (const item of day.items) {
|
|
if (
|
|
!item ||
|
|
item.date !== day.date ||
|
|
!['order', 'afterSale'].includes(item.kind) ||
|
|
!['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component'].every(
|
|
key => typeof item[key] === 'string',
|
|
) ||
|
|
!item.id ||
|
|
!item.name ||
|
|
typeof item.poolMaterial !== 'boolean' ||
|
|
typeof item.allocationPending !== 'boolean' ||
|
|
item.poolMaterial !== (item.poolId !== null) ||
|
|
(item.poolId !== null && !/^\d{4}-\d{2}-\d{2}$/.test(item.poolId)) ||
|
|
!['recorded', 'missing', 'pending'].includes(item.status) ||
|
|
!nullable(item.amount) ||
|
|
!nullable(item.estimatedAmount)
|
|
)
|
|
fail();
|
|
if (
|
|
(item.nonCash !== undefined && typeof item.nonCash !== 'boolean') ||
|
|
(item.estimatedAmount !== null && item.estimatedAmount < 0) ||
|
|
(item.status === 'recorded'
|
|
? item.amount === null || item.amount === 0 || item.estimatedAmount !== null || item.allocationPending
|
|
: item.amount !== null ||
|
|
(item.status === 'missing' && item.estimatedAmount !== null) ||
|
|
(item.allocationPending && (!item.poolMaterial || item.status !== 'missing')))
|
|
)
|
|
fail();
|
|
if (item.amount < 0 || item.nonCash === true) {
|
|
const index = remaining.indexOf(identity(item));
|
|
if (
|
|
item.kind !== 'order' ||
|
|
item.status !== 'recorded' ||
|
|
item.nonCash !== true ||
|
|
item.amount >= 0 ||
|
|
index < 0
|
|
)
|
|
fail();
|
|
remaining.splice(index, 1);
|
|
}
|
|
}
|
|
const recorded = day.items.filter(item => item.status === 'recorded'),
|
|
missing = day.items.filter(item => item.status === 'missing'),
|
|
total = rows => rows.reduce((sum, item) => sum + item.amount, 0),
|
|
poolMissing = missing.some(item => item.poolMaterial),
|
|
otherMissing = missing.some(item => !item.poolMaterial);
|
|
if (
|
|
day.knownAmount !== total(recorded) ||
|
|
day.knownPoolAmount !== total(recorded.filter(item => item.poolMaterial)) ||
|
|
day.knownOtherAmount !== day.knownAmount - day.knownPoolAmount ||
|
|
day.missingCount !== missing.length ||
|
|
day.pendingCount !== day.items.filter(item => item.status === 'pending').length ||
|
|
day.amount !== (missing.length ? null : day.knownAmount) ||
|
|
day.poolAmount !== (poolMissing ? null : day.knownPoolAmount) ||
|
|
day.otherAmount !== (otherMissing ? null : day.knownOtherAmount)
|
|
)
|
|
fail();
|
|
previous = day.date;
|
|
knownTotal += day.knownAmount;
|
|
}
|
|
if (remaining.length || knownTotal > b.costByPayer.owner.knownTotalCost) fail();
|
|
}
|
|
|
|
function validateCurrentAccount(b, income, fail) {
|
|
const account = b.currentAccount,
|
|
money = Number.isSafeInteger,
|
|
count = value => money(value) && value >= 0,
|
|
nullable = value => value === null || money(value);
|
|
if (
|
|
!account ||
|
|
account.basis !== 'orderDate' ||
|
|
account.from !== b.from ||
|
|
account.date !== b.date ||
|
|
!Array.isArray(account.days)
|
|
)
|
|
fail();
|
|
const ownerAccounts = new Set(income.accounts.filter(row => row.recipient === 'owner').map(row => row.account)),
|
|
received = new Map();
|
|
for (const item of income.items) {
|
|
const date = item.price_lock_id || item.order_after_sale ? item.date : item.order_date;
|
|
if (!date || date < b.from || date > b.date) continue;
|
|
if (ownerAccounts.has(item.account))
|
|
received.set(date, (received.get(date) || 0) + (item.kind === 'receipt' ? item.amount : -item.amount));
|
|
}
|
|
const seen = new Set();
|
|
let previous = '';
|
|
for (const day of account.days) {
|
|
if (
|
|
!day ||
|
|
!validOrderDate(day.date) ||
|
|
day.date < b.from ||
|
|
day.date > b.date ||
|
|
day.date <= previous ||
|
|
!['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount'].every(key =>
|
|
count(day[key]),
|
|
) ||
|
|
!['knownMaterialCost', 'knownOtherCost', 'knownProfit', 'ownerNetReceipts', 'knownAmount'].every(key =>
|
|
money(day[key]),
|
|
) ||
|
|
!['materialCost', 'otherCost', 'profit', 'amount'].every(key => nullable(day[key])) ||
|
|
typeof day.incomplete !== 'boolean'
|
|
)
|
|
fail();
|
|
if (
|
|
(day.materialCost !== null && day.materialCost !== day.knownMaterialCost) ||
|
|
(day.otherCost !== null && day.otherCost !== day.knownOtherCost) ||
|
|
day.profit !== (day.unknownProfitCount ? null : day.knownProfit) ||
|
|
day.knownAmount !== day.knownMaterialCost + day.knownOtherCost + day.knownProfit - day.ownerNetReceipts ||
|
|
day.amount !== (day.incomplete ? null : day.knownAmount) ||
|
|
((day.missingCostCount || day.pendingCostCount || day.unknownProfitCount) && !day.incomplete) ||
|
|
day.ownerNetReceipts !== (received.get(day.date) || 0)
|
|
)
|
|
fail();
|
|
const advance = b.ownerAdvances.days.find(row => row.date === day.date),
|
|
items = advance?.items || [],
|
|
recorded = items.filter(item => item.status === 'recorded');
|
|
const material = rows => rows.filter(item => item.component === 'material'),
|
|
other = rows => rows.filter(item => item.component !== 'material'),
|
|
sum = rows => rows.reduce((total, item) => total + item.amount, 0),
|
|
missing = items.filter(item => item.status === 'missing');
|
|
if (
|
|
day.knownMaterialCost !== sum(material(recorded)) ||
|
|
day.knownOtherCost !== sum(other(recorded)) ||
|
|
day.materialCost !== (material(missing).length ? null : day.knownMaterialCost) ||
|
|
day.otherCost !== (other(missing).length ? null : day.knownOtherCost) ||
|
|
day.missingCostCount !== (advance?.missingCount || 0) ||
|
|
day.pendingCostCount !== (advance?.pendingCount || 0)
|
|
)
|
|
fail();
|
|
seen.add(day.date);
|
|
previous = day.date;
|
|
}
|
|
if (
|
|
[...received.keys(), ...b.ownerAdvances.days.map(day => day.date)].some(date => !seen.has(date)) ||
|
|
account.days.reduce((sum, day) => sum + day.knownProfit, 0) !== b.knownProfit ||
|
|
account.days.reduce((sum, day) => sum + day.unknownProfitCount, 0) !== b.unknownProfitCount ||
|
|
account.days.reduce((sum, day) => sum + day.recordCount, 0) !== b.recordCount ||
|
|
account.days.some(day => day.incomplete) !== b.incomplete
|
|
)
|
|
fail();
|
|
}
|
|
function reportActiveAccounts(r) {
|
|
const recorded = new Set(
|
|
teamDataKeys(r.recipientReceipts).flatMap(key => r.recipientReceipts[key].items.map(item => item.account)),
|
|
);
|
|
return r.accounts.filter(
|
|
account =>
|
|
account.receipt !== 0 ||
|
|
account.refund !== 0 ||
|
|
account.net !== 0 ||
|
|
account.entryCount > 0 ||
|
|
recorded.has(account.account),
|
|
);
|
|
}
|
|
|
|
function reportOwnershipKeys(r) {
|
|
const keys = teamDataKeys(r.ownershipReceipts);
|
|
return state.user.role === 'owner' && !reportMember
|
|
? keys.filter(key => {
|
|
const person = r.ownershipReceipts[key];
|
|
return (
|
|
person.items.length ||
|
|
person.receipt !== 0 ||
|
|
person.refund !== 0 ||
|
|
person.net !== 0 ||
|
|
r.ownershipBusiness[key].recordCount ||
|
|
r.ownershipBusiness[key].currentAccount.days.length
|
|
);
|
|
})
|
|
: keys;
|
|
}
|
|
return {
|
|
validateReport,
|
|
validateDailyProfits,
|
|
validateDailyFunds,
|
|
validateDailyReimbursements,
|
|
validateTeamFunds,
|
|
reportActiveAccounts,
|
|
reportOwnershipKeys,
|
|
};
|
|
}
|
|
const api = {
|
|
forContext,
|
|
reportAfterSaleAmount,
|
|
reportCostItems,
|
|
reportRowCost,
|
|
reportCurrentAccountDays,
|
|
reimbursementAmounts,
|
|
};
|
|
if (typeof module === 'object' && module.exports) module.exports = api;
|
|
else root.ReportRules = api;
|
|
})(typeof globalThis === 'object' ? globalThis : this);
|