第3项:旧界面与 React 共用对账、回收及基础业务规则
This commit is contained in:
1 parent
54c05879d5
commit
389952f31c
65 files changed
+2265
-3800
No files matched your search
+29
-831
@@ -5,9 +5,8 @@ const e = s =>
|
||||
/[&<>"']/g,
|
||||
c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],
|
||||
);
|
||||
const yuan = n =>
|
||||
n == null ? '待补' : (n / 100).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
const grams = n => (n / 1000).toFixed(3);
|
||||
const yuan = n => (n == null ? '待补' : LedgerValues.yuan(n));
|
||||
const grams = n => LedgerValues.grams(n);
|
||||
const label = {
|
||||
draft: '旧草稿',
|
||||
confirmed: '旧单待补齐',
|
||||
@@ -555,24 +554,11 @@ async function render() {
|
||||
if (tab === 'private-operations') await renderPrivateOperations();
|
||||
if (tab === 'people-entry') await renderPeopleEntry();
|
||||
}
|
||||
const legacyTeamMembers = [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
{ member: 'assistant2', label: '小昊' },
|
||||
];
|
||||
function teamMemberCatalog() {
|
||||
const rows = state?.members?.length
|
||||
? state.members
|
||||
: state?.shopSettings?.members?.length
|
||||
? state.shopSettings.members
|
||||
: legacyTeamMembers;
|
||||
return rows.filter(row => row && typeof row.member === 'string');
|
||||
}
|
||||
function teamMemberKeys() {
|
||||
return teamMemberCatalog().map(row => row.member);
|
||||
return LedgerValues.memberKeys(state);
|
||||
}
|
||||
function teamMemberEnabled(member) {
|
||||
return teamMemberCatalog().find(row => row.member === member)?.enabled !== false && teamMemberKeys().includes(member);
|
||||
return LedgerValues.memberEnabled(state, member);
|
||||
}
|
||||
function activeTeamMemberKeys() {
|
||||
return teamMemberKeys().filter(teamMemberEnabled);
|
||||
@@ -644,18 +630,10 @@ function currentSalesperson() {
|
||||
return defaultSalesperson();
|
||||
}
|
||||
function memberAccountPrefix(member) {
|
||||
return { owner: '麦麦', assistant: '助理', assistant2: '助理2' }[member] || member;
|
||||
return LedgerValues.memberAccountPrefix(member);
|
||||
}
|
||||
function accountIdentity(value) {
|
||||
const text = String(value ?? '');
|
||||
for (const member of teamMemberKeys()) {
|
||||
const prefixes = member === 'assistant' ? ['助理', '助理1'] : [memberAccountPrefix(member)];
|
||||
for (const prefix of prefixes)
|
||||
if (text === prefix) return { member, prefix, channel: '' };
|
||||
else if (text.startsWith(prefix) && ['微信', '支付宝', '现金', '信用卡'].includes(text.slice(prefix.length)))
|
||||
return { member, prefix, channel: text.slice(prefix.length) };
|
||||
}
|
||||
return null;
|
||||
return LedgerValues.accountIdentity(teamMemberKeys(), value);
|
||||
}
|
||||
function accountDisplayName(value) {
|
||||
const account = accountIdentity(value);
|
||||
@@ -1382,12 +1360,7 @@ function draftRoundingMode(draft) {
|
||||
return draft.id ? draft.rounding_mode || 'cent' : 'yuan';
|
||||
}
|
||||
function orderAmount(value, mode) {
|
||||
return value == null
|
||||
? '待补'
|
||||
: '¥' +
|
||||
(mode === 'yuan'
|
||||
? (value / 100).toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 0 })
|
||||
: yuan(value));
|
||||
return value == null ? '待补' : '¥' + (mode === 'yuan' ? LedgerValues.yuan(value, 0) : yuan(value));
|
||||
}
|
||||
function orderRoundingHint(total) {
|
||||
if (total.rounding_mode !== 'yuan') return '保留原单金额,精确到分。';
|
||||
@@ -1918,9 +1891,7 @@ function profitSummary(o) {
|
||||
};
|
||||
}
|
||||
function validOrderDate(value) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value || '')) return false;
|
||||
const date = new Date(value + 'T12:00:00Z');
|
||||
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
return LedgerValues.validDate(value);
|
||||
}
|
||||
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
@@ -1949,10 +1920,8 @@ function orderEntryTime(value) {
|
||||
function orderEntryTimeHTML(order) {
|
||||
return `<div class="small muted order-entry-time">录入时间(北京时间):${e(orderEntryTime(order.created))}</div>`;
|
||||
}
|
||||
function previousOrderDate(today) {
|
||||
const date = new Date(today + 'T12:00:00Z');
|
||||
date.setUTCDate(date.getUTCDate() - 1);
|
||||
return date.toISOString().slice(0, 10);
|
||||
function previousOrderDate(day) {
|
||||
return LedgerValues.previousDate(day);
|
||||
}
|
||||
function orderBookPocketOptions() {
|
||||
const active = activePocketKeys(),
|
||||
@@ -2660,8 +2629,8 @@ function peopleCountDisplayName(name, period = false) {
|
||||
function peopleCountNumber(value) {
|
||||
return Number.isSafeInteger(value) && value >= 0 && value <= 1000000;
|
||||
}
|
||||
function peopleCountPreviousDate(date) {
|
||||
return new Date(Date.parse(date + 'T00:00:00Z') - 86400000).toISOString().slice(0, 10);
|
||||
function peopleCountPreviousDate(day) {
|
||||
return LedgerValues.previousDate(day);
|
||||
}
|
||||
function peopleCountChangeReason(current, previous) {
|
||||
return current === null
|
||||
@@ -4913,9 +4882,6 @@ function reportPayerHints(cost) {
|
||||
.filter(Boolean)
|
||||
.join(';');
|
||||
}
|
||||
function reportCostItems(cost) {
|
||||
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
||||
}
|
||||
function reportCostFormula(item) {
|
||||
const c = item.calculation;
|
||||
if (!c) return '';
|
||||
@@ -4931,19 +4897,7 @@ function reportCostItemAmount(item) {
|
||||
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
|
||||
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
|
||||
}
|
||||
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 reportAfterSaleAmount(cost) {
|
||||
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + item.amount, 0);
|
||||
}
|
||||
const { reportAfterSaleAmount, reportCostItems, reportRowCost, reportCurrentAccountDays } = ReportRules;
|
||||
function reportAfterSaleHint(cost) {
|
||||
return cost.items.some(item => item.kind === 'afterSale')
|
||||
? `<div class="small muted">其中售后 ¥${yuan(reportAfterSaleAmount(cost))}</div>`
|
||||
@@ -5018,33 +4972,10 @@ function reportRecipientReceiptsHTML(r, range) {
|
||||
.join('')}</div></section>`;
|
||||
}
|
||||
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),
|
||||
);
|
||||
return currentReportRules().reportActiveAccounts(r);
|
||||
}
|
||||
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 currentReportRules().reportOwnershipKeys(r);
|
||||
}
|
||||
function reportOwnershipAccountsHTML(person) {
|
||||
const ownAccounts = person.accounts.filter(account => account.recipient === person.member),
|
||||
@@ -5177,27 +5108,6 @@ function reportOwnershipProfitHTML(business, range) {
|
||||
difference = business.difference;
|
||||
return `<section class="report-business-profit" aria-label="${e(business.name + title)}"><h3>${title}</h3>${complete ? `<p class="report-business-profit-equation"><span>${revenue} <b>¥${yuan(equation.revenue)}</b></span><span aria-hidden="true">−</span><span>订单总成本 <b>¥${yuan(equation.totalCost)}</b></span><span aria-hidden="true">=</span><strong class="${business.profit < 0 ? 'danger-text' : ''}">¥${yuan(business.profit)}</strong></p>` : '<strong class="report-business-profit-pending">待核算</strong><p class="small muted">成本或利润资料尚未完整,先核对原单;完整利润暂不显示。</p>'}${difference.amount !== 0 || !difference.reconciled ? `<div class="report-business-difference"><p>所属净收款 ¥${yuan(business.netReceipts)},销售净额 ¥${yuan(business.sales)},差额 ¥${yuan(difference.amount)}。</p>${difference.reasons.length ? `<ul>${difference.reasons.map(reason => `<li>${e(reason.text)}</li>`).join('')}</ul>` : '<p>按原账销售与成本核对利润。</p>'}</div>` : ''}</section>`;
|
||||
}
|
||||
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 reportCurrentAccountDirection(business, day) {
|
||||
return day.amount === null
|
||||
? '应转金额待核算'
|
||||
@@ -5339,735 +5249,23 @@ function reportDailyProfitsText(r) {
|
||||
'',
|
||||
];
|
||||
}
|
||||
function currentReportRules() {
|
||||
return ReportRules.forContext({
|
||||
state,
|
||||
reportMember,
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
teamMode,
|
||||
currentMember,
|
||||
teamMemberKeys,
|
||||
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
|
||||
});
|
||||
}
|
||||
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);
|
||||
return currentReportRules().validateReport(r, range);
|
||||
}
|
||||
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 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 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 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 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();
|
||||
return currentReportRules().validateDailyProfits(r);
|
||||
}
|
||||
async function renderReport() {
|
||||
if (!reportDateInitialized) {
|
||||
|
||||
Reference in new issue
Block a user