第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) {
|
||||
|
||||
@@ -37,92 +37,8 @@ function dailyFundsMatches(entry = dailyFundsEntry) {
|
||||
function dailyFundsMoney(value) {
|
||||
return value == null ? '待确认' : '¥' + yuan(value);
|
||||
}
|
||||
function validateReimbursement(row) {
|
||||
if (
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
!row.id ||
|
||||
!validOrderDate(row.date) ||
|
||||
!Object.hasOwn(reimbursementStatusNames, 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 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;
|
||||
return currentReportRules().validateDailyFunds(data, range);
|
||||
}
|
||||
function preserveDailyFundsDrafts() {
|
||||
const outlay = $('#daily-outlay-form');
|
||||
@@ -272,20 +188,8 @@ function reimbursementRowsHTML(data, readOnly) {
|
||||
return `<div class="reimbursement-records">${data.reimbursements.map(row => `<article class="reimbursement-record" data-id="${e(row.id)}"><div class="reimbursement-record-heading"><strong>${e(row.date)} · ¥${yuan(row.total)}</strong><span class="badge${row.status === 'rejected' ? ' danger' : row.status === 'pending' ? ' warn' : ''}">${e(reimbursementStatusNames[row.status])}</span></div><p class="small muted">${e(row.requester_name || '提交人未提供')}提交${row.payer ? ' · ' + e(teamMemberName(row.payer)) + '实际付款' : ''}${row.reviewer_name ? ' · ' + e(row.reviewer_name) + '复核' : ''}</p>${reimbursementItemsHTML(row)}${row.note ? `<p class="small reimbursement-note">备注:${e(row.note)}</p>` : ''}${row.review_note ? `<p class="small ${row.status === 'rejected' ? 'danger-text' : 'muted'} reimbursement-note">${row.status === 'rejected' ? '驳回原因' : '复核备注'}:${e(row.review_note)}</p>` : ''}${!readOnly ? `<div class="actions">${row.canEdit && row.status !== 'approved' ? button(row.status === 'rejected' ? '修改后重新提交' : '修改报销单', 'reimbursement-edit', '', `data-id="${e(row.id)}"`) : ''}${dailyFundsOwner() && row.canApprove && row.status === 'pending' ? button('复核通过', 'reimbursement-approve', 'primary', `data-id="${e(row.id)}"`) + button('驳回', 'reimbursement-reject', '', `data-id="${e(row.id)}"`) : ''}</div>` : ''}</article>`).join('') || '<p class="small muted">所选日期暂无报销单。</p>'}</div>`;
|
||||
}
|
||||
function reimbursementDraftTotal(items) {
|
||||
let total = 0,
|
||||
complete = true;
|
||||
const amounts = [];
|
||||
for (const item of items) {
|
||||
try {
|
||||
const amount = LedgerCalc.cents(item.amount);
|
||||
if (!amount) complete = false;
|
||||
total += amount;
|
||||
amounts.push('¥' + yuan(amount));
|
||||
} catch {
|
||||
complete = false;
|
||||
}
|
||||
}
|
||||
return { total, complete, formula: amounts.join(' + ') };
|
||||
const { total, complete, amounts } = ReportRules.reimbursementAmounts(items, LedgerCalc.cents);
|
||||
return { total, complete, formula: amounts.map(amount => '¥' + yuan(amount)).join(' + ') };
|
||||
}
|
||||
function reimbursementEditorHTML(entry) {
|
||||
const draftKey = reimbursementEditors.get(entry.key),
|
||||
@@ -750,18 +654,7 @@ function dailyFundsInput(target) {
|
||||
}
|
||||
}
|
||||
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;
|
||||
return currentReportRules().validateDailyReimbursements(data);
|
||||
}
|
||||
async function openDailyReimbursements() {
|
||||
dailyReimbursementsOffset = 0;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>珠宝台账 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/order-formula.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-cost-presets-ui.js" defer></script><script src="/credit-card-fees.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/price-lock-changes-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/order-cancellations-ui.js" defer></script><script src="/order-changes-ui.js" defer></script><script src="/order-after-sales-ui.js" defer></script><script src="/order-ownership-ui.js" defer></script><script src="/daily-funds-ui.js" defer></script><script src="/cost-funding-ui.js" defer></script><script src="/team-funds-ui.js" defer></script><script src="/inventory-changes-ui.js" defer></script><script src="/recoveries-ui.js" defer></script><script src="/recovery-changes-ui.js" defer></script><script src="/pockets-ui.js" defer></script><script src="/shop-settings-ui.js" defer></script><script src="/employees-ui.js" defer></script><script src="/private-operations-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>珠宝台账 · 新账系统</title><link rel="stylesheet" href="/app.css"><script src="/calculations.js" defer></script><script src="/ledger-values.js" defer></script><script src="/report-rules.js" defer></script><script src="/recovery-rules.js" defer></script><script src="/order-formula.js" defer></script><script src="/fee-estimates.js" defer></script><script src="/order-cost-presets-ui.js" defer></script><script src="/credit-card-fees.js" defer></script><script src="/order-copy.js" defer></script><script src="/order-templates.js" defer></script><script src="/order-templates-ui.js" defer></script><script src="/price-locks-ui.js" defer></script><script src="/price-lock-changes-ui.js" defer></script><script src="/material-pools-ui.js" defer></script><script src="/order-edit-ui.js" defer></script><script src="/order-cancellations-ui.js" defer></script><script src="/order-changes-ui.js" defer></script><script src="/order-after-sales-ui.js" defer></script><script src="/order-ownership-ui.js" defer></script><script src="/daily-funds-ui.js" defer></script><script src="/cost-funding-ui.js" defer></script><script src="/team-funds-ui.js" defer></script><script src="/inventory-changes-ui.js" defer></script><script src="/recoveries-ui.js" defer></script><script src="/recovery-changes-ui.js" defer></script><script src="/pockets-ui.js" defer></script><script src="/shop-settings-ui.js" defer></script><script src="/employees-ui.js" defer></script><script src="/private-operations-ui.js" defer></script><script src="/app.js" defer></script></head>
|
||||
<body><div id="toast" role="status" hidden></div><div id="login"></div><div id="shell" hidden>
|
||||
<header class="app-header"><div class="brand"><span class="brand-mark" data-shop-mark>店</span><div><strong data-shop-name>珠宝台账</strong><small>开单 · 库存 · 订单利润</small></div></div><div class="header-right"><span id="mode" class="badge"></span><span id="identity"></span><button class="quiet" data-action="logout">退出</button></div></header>
|
||||
<div id="request-status" class="notice" role="status" aria-live="polite" hidden></div>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
// 单位换算、业务日期与收款账户识别。页面自行决定币种符号、空值文案和日期范围。
|
||||
(function (root) {
|
||||
/** @param {number} cents @param {number} [places] */
|
||||
const yuan = (cents, places = 2) =>
|
||||
(cents / 100).toLocaleString('zh-CN', { minimumFractionDigits: places, maximumFractionDigits: places });
|
||||
/** @param {number} mg */
|
||||
const grams = mg => (mg / 1000).toFixed(3);
|
||||
|
||||
/** 克输入转为整数毫克。空值、零、超出业务范围或精度的输入返回 null。 @param {unknown} input */
|
||||
function positiveMg(input) {
|
||||
const text = String(input ?? '').trim();
|
||||
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null;
|
||||
const [whole, fraction = ''] = text.split('.');
|
||||
const mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0'));
|
||||
return mg > 0n && mg <= 100000000000n ? Number(mg) : null;
|
||||
}
|
||||
|
||||
/** @param {unknown} value @returns {value is string} */
|
||||
function validDate(value) {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
const date = new Date(value + 'T12:00:00Z');
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
|
||||
/** @param {string} day */
|
||||
function previousDate(day) {
|
||||
const date = new Date(day + 'T12:00:00Z');
|
||||
date.setUTCDate(date.getUTCDate() - 1);
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** @type {Record<string,string>} */
|
||||
const prefixes = { owner: '麦麦', assistant: '助理', assistant2: '助理2' };
|
||||
/** @param {string} member */
|
||||
const memberAccountPrefix = member => prefixes[member] || member;
|
||||
/** @param {readonly string[]} members @param {unknown} value */
|
||||
function accountIdentity(members, value) {
|
||||
const text = String(value ?? '');
|
||||
for (const member of members) {
|
||||
const names = member === 'assistant' ? ['助理', '助理1'] : [memberAccountPrefix(member)];
|
||||
for (const prefix of names) {
|
||||
if (text === prefix) return { member, prefix, channel: '' };
|
||||
const channel = text.slice(prefix.length);
|
||||
if (text.startsWith(prefix) && ['微信', '支付宝', '现金', '信用卡'].includes(channel))
|
||||
return { member, prefix, channel };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @typedef {{member: string, label?: string, enabled?: boolean}} Member */
|
||||
/** @typedef {{members?: Member[], shopSettings?: {members?: Member[]}, user?: {member?: string}}} MemberState */
|
||||
const legacyMembers = [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
{ member: 'assistant2', label: '小昊' },
|
||||
];
|
||||
/** @param {MemberState | null | undefined} state @returns {Member[]} */
|
||||
function memberCatalog(state) {
|
||||
const rows = state?.members?.length
|
||||
? state.members
|
||||
: state?.shopSettings?.members?.length
|
||||
? state.shopSettings.members
|
||||
: legacyMembers;
|
||||
return rows.filter(row => row && typeof row.member === 'string');
|
||||
}
|
||||
/** @param {MemberState | null | undefined} state */
|
||||
const memberKeys = state => memberCatalog(state).map(row => row.member);
|
||||
/** @param {MemberState | null | undefined} state @param {string} key */
|
||||
const memberEnabled = (state, key) => {
|
||||
const row = memberCatalog(state).find(row => row.member === key);
|
||||
return !!row && row.enabled !== false;
|
||||
};
|
||||
|
||||
const api = {
|
||||
memberCatalog,
|
||||
memberKeys,
|
||||
memberEnabled,
|
||||
yuan,
|
||||
grams,
|
||||
positiveMg,
|
||||
validDate,
|
||||
previousDate,
|
||||
memberAccountPrefix,
|
||||
accountIdentity,
|
||||
};
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.LedgerValues = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
@@ -219,11 +219,7 @@ async function loadMaterialQuote(entry = materialQuoteEntry) {
|
||||
}
|
||||
}
|
||||
function materialPoolMg(value) {
|
||||
const text = String(value ?? '').trim();
|
||||
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null;
|
||||
const [whole, fraction = ''] = text.split('.'),
|
||||
mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0'));
|
||||
return mg > 0n && mg <= 100000000000n ? Number(mg) : null;
|
||||
return LedgerValues.positiveMg(value);
|
||||
}
|
||||
function materialPoolRate(value) {
|
||||
return value == null ? '待补采购' : yuan(value);
|
||||
|
||||
@@ -9,10 +9,11 @@
|
||||
node ? require('./calculations') : root.LedgerCalc,
|
||||
node ? require('./fee-estimates') : root.FeeEstimates,
|
||||
node ? require('./credit-card-fees') : root.CreditCardFees,
|
||||
node ? require('./ledger-values') : root.LedgerValues,
|
||||
);
|
||||
if (node) module.exports = api;
|
||||
else root.OrderEntryModel = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this, function (Calc, Fees, Cards) {
|
||||
})(typeof globalThis === 'object' ? globalThis : this, function (Calc, Fees, Cards, Values) {
|
||||
const productNames = ['足金999', '足银999', '纯银925'];
|
||||
const chargeNames = ['编绳', '证书', '包装', '快递', '附加费'];
|
||||
const chargeSaleDefaults = { 编绳: '55', 证书: '10', 包装: '10', 快递: '8' };
|
||||
@@ -24,27 +25,16 @@
|
||||
sticker: '手机贴',
|
||||
other: '其他直接费用',
|
||||
};
|
||||
const legacyTeamMembers = [
|
||||
{ member: 'owner', label: '麦麦' },
|
||||
{ member: 'assistant', label: '娜娜' },
|
||||
{ member: 'assistant2', label: '小昊' },
|
||||
];
|
||||
const defaultPocketKeys = ['现货', '金料', '找金', '回收旧料', '君宝汇'];
|
||||
const orderCostCategories = { jd: 'shipping', yt: 'shipping', box: 'box', steel: 'braiding', silver: 'silverChain' };
|
||||
const clone = value => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));
|
||||
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
||||
|
||||
// —— 金额与文字 ——
|
||||
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 ? '待补' : Values.yuan(n));
|
||||
const grams = Values.grams;
|
||||
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' ? Values.yuan(value, 0) : yuan(value));
|
||||
}
|
||||
function orderRoundingHint(total) {
|
||||
if (total.rounding_mode !== 'yuan') return '保留原单金额,精确到分。';
|
||||
@@ -65,17 +55,8 @@
|
||||
}
|
||||
|
||||
// —— 账号、成员与店铺配置(输入为 /api/state 结果,可附 session)——
|
||||
function memberCatalog(st) {
|
||||
const rows = st?.members?.length
|
||||
? st.members
|
||||
: st?.shopSettings?.members?.length
|
||||
? st.shopSettings.members
|
||||
: legacyTeamMembers;
|
||||
return rows.filter(row => row && typeof row.member === 'string');
|
||||
}
|
||||
const memberKeys = st => memberCatalog(st).map(row => row.member);
|
||||
const memberEnabled = (st, member) =>
|
||||
memberCatalog(st).find(row => row.member === member)?.enabled !== false && memberKeys(st).includes(member);
|
||||
const memberKeys = Values.memberKeys;
|
||||
const memberEnabled = Values.memberEnabled;
|
||||
const activeMemberKeys = st => memberKeys(st).filter(member => memberEnabled(st, member));
|
||||
const teamMode = st => !!(st?.user?.member || st?.members?.some(member => member.member === 'assistant2'));
|
||||
const currentMember = (st, session) =>
|
||||
@@ -121,18 +102,8 @@
|
||||
const costConfig = st => Fees.presets(st?.shopSettings?.costPresets);
|
||||
const creditCardRate = st => st?.shopSettings?.creditCardRatePermille ?? 6;
|
||||
const creditCardAvailable = st => !!st?.accounts?.includes('麦麦信用卡');
|
||||
const memberAccountPrefix = member => ({ owner: '麦麦', assistant: '助理', assistant2: '助理2' })[member] || member;
|
||||
function accountIdentity(st, value) {
|
||||
const text = String(value ?? '');
|
||||
for (const member of memberKeys(st)) {
|
||||
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;
|
||||
}
|
||||
const memberAccountPrefix = Values.memberAccountPrefix;
|
||||
const accountIdentity = (st, value) => Values.accountIdentity(memberKeys(st), value);
|
||||
const activePocketKeys = st => (Array.isArray(st?.pockets) ? st.pockets : defaultPocketKeys);
|
||||
const pocketLabel = (st, key) => st?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||
const pocketCountsEnabled = (st, key) =>
|
||||
@@ -432,13 +403,7 @@
|
||||
}
|
||||
|
||||
// —— 日购料(旧 material-pools-ui.js 中与开单有关的部分)——
|
||||
function materialPoolMg(value) {
|
||||
const text = String(value ?? '').trim();
|
||||
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) return null;
|
||||
const [whole, fraction = ''] = text.split('.'),
|
||||
mg = BigInt(whole) * 1000n + BigInt(fraction.padEnd(3, '0'));
|
||||
return mg > 0n && mg <= 100000000000n ? Number(mg) : null;
|
||||
}
|
||||
const materialPoolMg = Values.positiveMg;
|
||||
const poolHasPersonal = pool => !!pool && own(pool, 'personalPools');
|
||||
const rollingOf = pools => (pools?.rolling?.enabled === true ? pools.rolling : null);
|
||||
function poolRows(pools) {
|
||||
@@ -1250,7 +1215,9 @@
|
||||
form.presets = presetsEnabled ? newPresets(st, items, recorded) : null;
|
||||
if (recorded) {
|
||||
form.editing = true;
|
||||
form.presets.originals = Object.fromEntries(items.map(item => [Fees.presetKind(item, { presets: config, recorded }), item]).filter(([kind]) => kind));
|
||||
form.presets.originals = Object.fromEntries(
|
||||
items.map(item => [Fees.presetKind(item, { presets: config, recorded }), item]).filter(([kind]) => kind),
|
||||
);
|
||||
}
|
||||
form.feeRows = rows.map(item => feeRow(item, st, teamDefaultPayer(form, st)));
|
||||
form.lines = (draft.lines?.length ? draft.lines : [{}]).map(l =>
|
||||
@@ -1295,9 +1262,12 @@
|
||||
fees_date: form.fees_date,
|
||||
fee_auto_initialized: true,
|
||||
fee_cost_mode: form.feeCostMode || (!form.id ? 'checkboxes' : 'legacy'),
|
||||
fee_items: [...form.feeRows.map(readFeeRow), ...readPresets(form, st).items.map(item =>
|
||||
form.presets?.originals?.[Fees.presetKind(item, { presets: costConfig(st) })] || item
|
||||
)].filter(item => form.editing || !Cards.isFee(item)),
|
||||
fee_items: [
|
||||
...form.feeRows.map(readFeeRow),
|
||||
...readPresets(form, st).items.map(
|
||||
item => form.presets?.originals?.[Fees.presetKind(item, { presets: costConfig(st) })] || item,
|
||||
),
|
||||
].filter(item => form.editing || !Cards.isFee(item)),
|
||||
discount: form.discount,
|
||||
note: form.note,
|
||||
internal_note: form.internal_note,
|
||||
|
||||
@@ -24,7 +24,7 @@ function privateOpsCurrent() {
|
||||
return state?.user?.role === 'owner' && tab === 'private-operations';
|
||||
}
|
||||
function privateOpsMemberOptions() {
|
||||
return teamMemberCatalog().map(row => [row.member, row.label + (row.enabled === false ? '(已停用)' : '')]);
|
||||
return LedgerValues.memberCatalog(state).map(row => [row.member, row.label + (row.enabled === false ? '(已停用)' : '')]);
|
||||
}
|
||||
async function renderPrivateOperations() {
|
||||
if (!privateOpsCurrent()) return;
|
||||
|
||||
+34
-582
@@ -6,7 +6,40 @@ let recoveryListRequest = 0,
|
||||
recoveryDetail = null,
|
||||
recoveryFilters = null,
|
||||
recoveryFilterUser = '';
|
||||
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
|
||||
const { recoveryModeNames, recoveryProductFields, customerMaterialOldLines } = RecoveryRules;
|
||||
const recoveryPageRules = RecoveryRules.createModel({
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
get originalInput() {
|
||||
return typeof recoveryEditEntry !== 'undefined' &&
|
||||
recoveryEditEntry &&
|
||||
$('#recovery-form')?.dataset.recoveryEdit === 'true'
|
||||
? recoveryEditEntry.data.inputs
|
||||
: null;
|
||||
},
|
||||
currentMember: () => currentMember(),
|
||||
defaultSalesperson: () => defaultSalesperson(),
|
||||
teamMemberKeys: () => teamMemberKeys(),
|
||||
activePocketKeys: () => activePocketKeys(),
|
||||
pocketCountsEnabled: key => pocketCountsEnabled(key),
|
||||
stockCountValue: (value, options) => stockCountValue(value, options),
|
||||
validOrderDate: value => validOrderDate(value),
|
||||
isCreditCardAccount: value => isCreditCardAccount(value),
|
||||
memberAccountPrefix: member => memberAccountPrefix(member),
|
||||
accountIdentity: value => accountIdentity(value),
|
||||
isSilver: name => LedgerCalc.isSilver(name),
|
||||
});
|
||||
const {
|
||||
defaults: recoveryDefaults,
|
||||
sharedDraft: recoverySharedOldDraft,
|
||||
input: recoveryInput,
|
||||
calculate: recoveryCalculate,
|
||||
validate: validateRecoveryInput,
|
||||
newWeight: recoveryNewWeight,
|
||||
units: recoveryUnits,
|
||||
multiply: recoveryMul,
|
||||
} = recoveryPageRules;
|
||||
const recoveryDraftFields = [
|
||||
'shared_old_notice',
|
||||
'surplus_mode',
|
||||
@@ -62,77 +95,11 @@ const recoveryDraftKey = () => `mm-recovery-draft-${state.user.id}`;
|
||||
const recoveryUser = () => state?.user?.id || '';
|
||||
const recoveryPrefix = member => memberAccountPrefix(member);
|
||||
const recoveryMoney = value => (value == null ? '待填写' : '¥' + yuan(value));
|
||||
function recoveryUnits(value, places, title, { zero = true } = {}) {
|
||||
const raw = recoveryText(value),
|
||||
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
|
||||
if (!pattern.test(raw))
|
||||
throw new Error(`${title}请填写${zero ? '不小于0' : '大于0'}的数字,最多保留${places}位小数。`);
|
||||
const [whole, fraction = ''] = raw.split('.'),
|
||||
units = BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0'));
|
||||
if (units > 100000000000n || (!zero && units === 0n)) throw new Error(`${title}超出范围或尚未填写。`);
|
||||
return Number(units);
|
||||
}
|
||||
function recoveryLimit(value, title = '回收/置换合计') {
|
||||
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000) throw new Error(title + '超出支持范围,请核对。');
|
||||
return value;
|
||||
}
|
||||
function recoveryMul(weight, rate) {
|
||||
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
|
||||
}
|
||||
function recoveryCardRate() {
|
||||
return typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry
|
||||
? (recoveryEditEntry.data?.record?.credit_card_rate_permille ?? configuredCreditCardRate())
|
||||
: configuredCreditCardRate();
|
||||
}
|
||||
const recoveryProductFields = [
|
||||
'new_name',
|
||||
'new_quantity',
|
||||
'pocket',
|
||||
'stockCount',
|
||||
'labor_mode',
|
||||
'labor_rate',
|
||||
'cost_labor_mode',
|
||||
'cost_labor_value',
|
||||
'labor_payer',
|
||||
];
|
||||
function recoveryProductInput(draft) {
|
||||
return {
|
||||
name: draft.new_name,
|
||||
quantity: draft.new_quantity,
|
||||
pocket: draft.pocket,
|
||||
...(pocketCountsEnabled(draft.pocket) ? { stockCount: draft.stockCount || null } : {}),
|
||||
labor_mode: draft.labor_mode,
|
||||
labor_rate: draft.labor_rate,
|
||||
...(draft.cost_labor_value !== ''
|
||||
? {
|
||||
cost_labor:
|
||||
draft.cost_labor_mode === 'total'
|
||||
? { mode: 'total', amount: draft.cost_labor_value }
|
||||
: { mode: 'gram', rate: draft.cost_labor_value },
|
||||
}
|
||||
: {}),
|
||||
cost_labor_payer: draft.labor_payer,
|
||||
};
|
||||
}
|
||||
function recoveryProductDraft(row) {
|
||||
return {
|
||||
new_name: row.name,
|
||||
new_quantity: row.quantity,
|
||||
pocket: row.pocket,
|
||||
stockCount: row.stockCount ?? '',
|
||||
labor_mode: row.labor_mode,
|
||||
labor_rate: row.labor_rate,
|
||||
cost_labor_mode: row.cost_labor?.mode || 'total',
|
||||
cost_labor_value: row.cost_labor?.mode === 'gram' ? row.cost_labor.rate : (row.cost_labor?.amount ?? ''),
|
||||
labor_payer: row.cost_labor_payer,
|
||||
};
|
||||
}
|
||||
function recoveryNewWeight(draft) {
|
||||
return [draft, ...(draft.extra_products || [])].reduce(
|
||||
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
|
||||
0,
|
||||
);
|
||||
}
|
||||
// 第一件与新增商品共用商品字段,保持候选名称、货盘和计费选项一致。
|
||||
function recoveryProductFieldsHTML(row, { prefix = '', original = null } = {}) {
|
||||
const name = key => prefix + key;
|
||||
@@ -162,61 +129,6 @@ function recoveryExtraProductHTML(row, index) {
|
||||
typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry?.data?.inputs?.exchange?.products?.[index + 1] : null;
|
||||
return `<section class="recovery-new-product" data-recovery-product="${index}"><div class="panel-title"><h3>置换新货 ${index + 2}</h3>${button('移除商品', 'recovery-remove-product', 'quiet', `data-index="${index}"`)}</div>${recoveryProductFieldsHTML(row, { prefix: 'extra_', original })}<div class="internal recovery-product-cost"><h4>本件内部成本</h4>${recoveryProductLaborHTML(row, { prefix: 'extra_' })}</div></section>`;
|
||||
}
|
||||
function recoveryDefaults(mode = 'direct') {
|
||||
const member = currentMember();
|
||||
return {
|
||||
independent_products: false,
|
||||
surplus_mode: 'buy',
|
||||
surplus_memo: '',
|
||||
old_source: 'incoming',
|
||||
deposit_id: '',
|
||||
deposit_weight: '',
|
||||
mode,
|
||||
date: state.today,
|
||||
customer: '',
|
||||
salesperson: defaultSalesperson(),
|
||||
member,
|
||||
old_name: 'Au旧料',
|
||||
incoming_weight: '',
|
||||
melted_weight: '',
|
||||
purity: '100',
|
||||
old_pocket: '回收旧料',
|
||||
old_stock_count: '',
|
||||
buy_rate: '',
|
||||
buy_total: '',
|
||||
new_name: '足金999',
|
||||
new_quantity: '',
|
||||
pocket: '现货',
|
||||
stockCount: '',
|
||||
gold_price: '',
|
||||
labor_mode: 'gram',
|
||||
labor_rate: '',
|
||||
depreciation_weight: '',
|
||||
depreciation_rate: '10',
|
||||
charge_name: '其他收费',
|
||||
charge_amount: '0',
|
||||
discount: '0',
|
||||
rounding_mode: 'yuan',
|
||||
material_source: 'pool',
|
||||
material_pool_id: state.today,
|
||||
material_rate: '',
|
||||
material_payer: member,
|
||||
cost_labor_mode: 'gram',
|
||||
cost_labor_value: '',
|
||||
labor_payer: member,
|
||||
fee_note: '其他费用',
|
||||
fee_amount: '0',
|
||||
fee_payer: member,
|
||||
payment_method: '微信',
|
||||
payment_recipient: recoveryPrefix(member),
|
||||
payout_method: '微信',
|
||||
payer: member,
|
||||
note: '',
|
||||
buy_total_manual: false,
|
||||
depreciation_manual: false,
|
||||
melted_manual: false,
|
||||
};
|
||||
}
|
||||
function recoveryStoredDraft() {
|
||||
let value;
|
||||
try {
|
||||
@@ -237,20 +149,6 @@ function recoveryStoredDraft() {
|
||||
if (state.user.role !== 'owner') draft.member = currentMember();
|
||||
return draft;
|
||||
}
|
||||
// 新建草稿统一只保留上方一份来料;后续行仅保留新货字段。
|
||||
function recoverySharedOldDraft(draft) {
|
||||
if (!draft.independent_products) return draft;
|
||||
return {
|
||||
...draft,
|
||||
independent_products: false,
|
||||
extra_products: (draft.extra_products || []).map(row =>
|
||||
Object.fromEntries(recoveryProductFields.map(k => [k, row[k]])),
|
||||
),
|
||||
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
|
||||
verified: false,
|
||||
shared_old_notice: draft.extra_products?.length ? '已恢复为一份来料,沿用上方第一份来料;请核对实际总克重。' : '',
|
||||
};
|
||||
}
|
||||
function recoveryField(form, name) {
|
||||
return form?.elements?.namedItem?.(name) || form?.elements?.[name] || form?.querySelector?.(`[name="${name}"]`);
|
||||
}
|
||||
@@ -281,329 +179,6 @@ function rememberRecoveryDraft(form = $('#recovery-form')) {
|
||||
localStorage.setItem(recoveryDraftKey(), JSON.stringify(recoveryFormDraft(form)));
|
||||
} catch {}
|
||||
}
|
||||
function recoveryInput(draft, { quote = false } = {}) {
|
||||
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
|
||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
|
||||
const member = state.user.role === 'owner' ? draft.member : currentMember();
|
||||
const input = {
|
||||
mode: draft.mode,
|
||||
date: draft.date,
|
||||
customer: draft.customer,
|
||||
customer_type: draft.customer_type,
|
||||
salesperson: draft.salesperson,
|
||||
member,
|
||||
note: draft.note,
|
||||
old_pocket: draft.old_pocket ?? '回收旧料',
|
||||
...(pocketCountsEnabled(draft.old_pocket) ? { old_stock_count: recoveryText(draft.old_stock_count) || null } : {}),
|
||||
old_lines: Array.isArray(draft.old_lines)
|
||||
? draft.old_lines
|
||||
: [
|
||||
{
|
||||
name: draft.old_name || 'Au旧料',
|
||||
incoming_weight: draft.incoming_weight,
|
||||
melted_weight: draft.melted_weight,
|
||||
purity: draft.purity,
|
||||
},
|
||||
],
|
||||
buy_rate: draft.buy_rate,
|
||||
payer: draft.payer || member,
|
||||
payment_account: recoveryPrefix(draft.payer || member) + (draft.payout_method || '微信'),
|
||||
verified: !quote && draft.verified === true,
|
||||
};
|
||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||
Object.assign(input, { old_source: 'deposit', deposit_id: draft.deposit_id, deposit_weight: draft.deposit_weight });
|
||||
if (draft.buy_total_manual && draft.buy_total !== '') input.buy_total = draft.buy_total;
|
||||
if (draft.mode === 'exchange' && draft.surplus_mode === 'deposit')
|
||||
Object.assign(input, {
|
||||
surplus_mode: 'deposit',
|
||||
surplus_memo: draft.surplus_memo || '',
|
||||
buy_rate: '0',
|
||||
buy_total: '0',
|
||||
});
|
||||
if (draft.mode === 'exchange') {
|
||||
const costLabor =
|
||||
draft.cost_labor_value === ''
|
||||
? undefined
|
||||
: draft.cost_labor_mode === 'total'
|
||||
? { mode: 'total', amount: draft.cost_labor_value }
|
||||
: { mode: 'gram', rate: draft.cost_labor_value };
|
||||
const costMaterial =
|
||||
draft.material_source === 'pool'
|
||||
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
|
||||
: draft.material_rate === ''
|
||||
? undefined
|
||||
: { mode: 'gram', rate: draft.material_rate };
|
||||
input.exchange = {
|
||||
name: draft.new_name,
|
||||
quantity: draft.new_quantity,
|
||||
pocket: draft.pocket,
|
||||
...(pocketCountsEnabled(draft.pocket)
|
||||
? { stockCount: draft.stockCount == null || String(draft.stockCount).trim() === '' ? null : draft.stockCount }
|
||||
: {}),
|
||||
gold_price: draft.gold_price,
|
||||
labor_mode: draft.labor_mode,
|
||||
labor_rate: draft.labor_rate,
|
||||
depreciation_rate: draft.depreciation_rate || '0',
|
||||
...(draft.depreciation_manual ? { depreciation_weight: draft.depreciation_weight } : {}),
|
||||
...(costMaterial ? { cost_material: costMaterial } : {}),
|
||||
...(costLabor ? { cost_labor: costLabor } : {}),
|
||||
cost_payer: draft.cost_payer || draft.labor_payer || member,
|
||||
cost_material_payer: draft.material_payer || member,
|
||||
cost_labor_payer: draft.labor_payer || member,
|
||||
charges: Array.isArray(draft.charges)
|
||||
? draft.charges
|
||||
: recoveryText(draft.charge_amount) && recoveryUnits(draft.charge_amount, 2, '其他收费') > 0
|
||||
? [{ name: draft.charge_name || '其他收费', amount: draft.charge_amount }]
|
||||
: [],
|
||||
fee_items: Array.isArray(draft.fee_items)
|
||||
? draft.fee_items
|
||||
: recoveryText(draft.fee_amount) && recoveryUnits(draft.fee_amount, 2, '其他内部费用') > 0
|
||||
? [
|
||||
{
|
||||
key: 'other',
|
||||
note: draft.fee_note || '其他费用',
|
||||
amount: draft.fee_amount,
|
||||
payer: draft.fee_payer || member,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
discount: draft.discount || '0',
|
||||
rounding_mode: draft.rounding_mode || 'yuan',
|
||||
};
|
||||
if (draft.extra_products?.length)
|
||||
input.exchange.products = [draft, ...draft.extra_products].map(recoveryProductInput);
|
||||
const old = recoveryCalculate({ ...input, mode: 'direct', buy_rate: '1', buy_total: '1' }),
|
||||
newMg = recoveryNewWeight(draft);
|
||||
if (newMg >= old.oldMg) {
|
||||
input.buy_rate = '0';
|
||||
input.buy_total = '0';
|
||||
}
|
||||
if (newMg <= old.oldMg) {
|
||||
input.exchange.gold_price = '0';
|
||||
delete input.exchange.cost_material;
|
||||
}
|
||||
const calculation = recoveryCalculate(input);
|
||||
if (calculation.netSettlement > 0)
|
||||
input.payment_account =
|
||||
draft.payment_method === '信用卡'
|
||||
? '麦麦信用卡'
|
||||
: (draft.payment_recipient || recoveryPrefix(member)) + (draft.payment_method || '微信');
|
||||
}
|
||||
return input;
|
||||
}
|
||||
function recoveryCalculate(input) {
|
||||
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
|
||||
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
|
||||
const oldLines = (input.old_lines || []).map(line => {
|
||||
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
|
||||
meltedMg = recoveryUnits(line.melted_weight, 3, '熔后重量', { zero: false }),
|
||||
purity = recoveryUnits(line.purity, 3, '成色', { zero: false });
|
||||
if (meltedMg > incomingMg) throw new Error('熔后重量不能大于来料重量,请核对。');
|
||||
if (purity > 100000) throw new Error('成色请填写0到100之间的百分数,例如99表示99%。');
|
||||
const foldedMg = Number((BigInt(meltedMg) * BigInt(purity) + 50000n) / 100000n);
|
||||
if (foldedMg <= 0) throw new Error('折后重量须至少为0.001g,请核对重量和成色。');
|
||||
return { ...line, incomingMg, meltedMg, purity: purity / 1000, foldedMg };
|
||||
});
|
||||
if (!oldLines.length) throw new Error('请填写旧料重量。');
|
||||
const oldMg = recoveryLimit(
|
||||
oldLines.reduce((sum, line) => sum + line.foldedMg, 0),
|
||||
'旧料总重量',
|
||||
),
|
||||
buyRate = recoveryUnits(input.buy_rate, 2, '回收单价');
|
||||
let newMg = 0,
|
||||
matchedMg = 0,
|
||||
differenceMg = 0,
|
||||
surplusMg = oldMg,
|
||||
goldAmount = 0,
|
||||
laborAmount = 0,
|
||||
depreciationMg = 0,
|
||||
depreciationAmount = 0,
|
||||
chargesAmount = 0,
|
||||
discount = 0,
|
||||
receivable = 0,
|
||||
roundingAdjustment = 0;
|
||||
if (input.mode === 'exchange') {
|
||||
const x = input.exchange || {};
|
||||
newMg = x.products
|
||||
? recoveryLimit(x.products.reduce((n, row) => n + recoveryUnits(row.quantity, 3, '新货克重', { zero: false }), 0))
|
||||
: recoveryUnits(x.quantity, 3, '新货克重', { zero: false });
|
||||
matchedMg = Math.min(oldMg, newMg);
|
||||
differenceMg = Math.max(0, newMg - oldMg);
|
||||
surplusMg = Math.max(0, oldMg - newMg);
|
||||
const goldPrice = differenceMg > 0 ? recoveryUnits(x.gold_price, 2, '当天销售金价') : 0,
|
||||
laborRate = recoveryUnits(x.labor_rate, 2, '销售工费'),
|
||||
depreciationRate = recoveryUnits(x.depreciation_rate ?? '10', 2, '折旧费单价');
|
||||
if (differenceMg > 0 && goldPrice <= 0) throw new Error('有补金差重时,请填写大于0的当天销售金价。');
|
||||
goldAmount = recoveryMul(differenceMg, goldPrice);
|
||||
laborAmount = x.products
|
||||
? recoveryLimit(
|
||||
x.products.reduce((n, row) => {
|
||||
const rate = recoveryUnits(row.labor_rate, 2, '销售工费');
|
||||
return (
|
||||
n + (row.labor_mode === 'total' ? rate : recoveryMul(recoveryUnits(row.quantity, 3, '新货克重'), rate))
|
||||
);
|
||||
}, 0),
|
||||
)
|
||||
: x.labor_mode === 'total'
|
||||
? laborRate
|
||||
: recoveryMul(newMg, laborRate);
|
||||
depreciationMg =
|
||||
x.depreciation_weight == null ? matchedMg : recoveryUnits(x.depreciation_weight, 3, '折旧费计费克重');
|
||||
depreciationAmount = recoveryMul(depreciationMg, depreciationRate);
|
||||
chargesAmount = recoveryLimit(
|
||||
(x.charges || []).reduce((sum, row) => sum + recoveryUnits(row.amount, 2, '其他收费'), 0),
|
||||
);
|
||||
discount = recoveryUnits(x.discount || '0', 2, '优惠金额');
|
||||
const before = recoveryLimit(goldAmount + laborAmount + depreciationAmount + chargesAmount) - discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于本次置换费用。');
|
||||
receivable = x.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
roundingAdjustment = receivable - before;
|
||||
}
|
||||
const depositMg = input.mode === 'exchange' && input.surplus_mode === 'deposit' ? surplusMg : 0,
|
||||
purchaseMg = surplusMg - depositMg;
|
||||
if (purchaseMg > 0 && buyRate <= 0) throw new Error('有回收旧料或余料时,请填写大于0的回收单价。');
|
||||
const defaultPurchaseAmount = recoveryMul(purchaseMg, buyRate),
|
||||
purchaseAmount = depositMg
|
||||
? 0
|
||||
: input.buy_total == null
|
||||
? defaultPurchaseAmount
|
||||
: recoveryUnits(input.buy_total, 2, input.mode === 'direct' ? '回收结算额' : '余料回收款');
|
||||
if (purchaseMg > 0 && purchaseAmount <= 0) throw new Error('回收结算金额须大于0,请核对。');
|
||||
if (!surplusMg && purchaseAmount) throw new Error('本次没有余料,余料回收款应为0。');
|
||||
const netSettlement = recoveryLimit(receivable - purchaseAmount);
|
||||
return {
|
||||
mode: input.mode,
|
||||
old_lines: oldLines,
|
||||
oldMg,
|
||||
newMg,
|
||||
matchedMg,
|
||||
differenceMg,
|
||||
surplusMg,
|
||||
depositMg,
|
||||
purchaseMg,
|
||||
goldAmount,
|
||||
laborAmount,
|
||||
depreciationMg,
|
||||
depreciationAmount,
|
||||
chargesAmount,
|
||||
discount,
|
||||
receivable,
|
||||
purchaseAmount,
|
||||
defaultPurchaseAmount,
|
||||
roundingAdjustment,
|
||||
netSettlement,
|
||||
cashReceipt: Math.max(0, netSettlement),
|
||||
cashPayment: Math.max(0, -netSettlement),
|
||||
};
|
||||
}
|
||||
function recoveryValidationOriginal(input) {
|
||||
const source = recoveryEditEntry?.data?.inputs,
|
||||
item = source?.exchange?.items?.[input._recoveryItemIndex];
|
||||
return item ? { ...source, ...item } : source;
|
||||
}
|
||||
function validateRecoveryInput(input) {
|
||||
if (input.exchange?.items) {
|
||||
for (const [index, row] of input.exchange.items.entries())
|
||||
validateRecoveryInput({
|
||||
...input,
|
||||
...row,
|
||||
_recoveryItemIndex: index,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
exchange: row.exchange,
|
||||
payment_account: recoveryPrefix(input.payer) + '微信',
|
||||
});
|
||||
if (!state.accounts.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
||||
return input;
|
||||
}
|
||||
if (!validOrderDate(input.date) || input.date > state.today) throw new Error('业务日期请选择今天或之前的有效日期。');
|
||||
if (!input.customer || input.customer.length > 60) throw new Error('请填写1~60字的客户称呼或代号。');
|
||||
if (!input.salesperson || input.salesperson.length > 30) throw new Error('请填写1~30字的开单人。');
|
||||
if (input.note.length > 240) throw new Error('备注最多填写240字。');
|
||||
if (!teamMemberKeys().includes(input.member) || !teamMemberKeys().includes(input.payer))
|
||||
throw new Error('请选择归属成员和实际付款人。');
|
||||
const calculation = recoveryCalculate(input);
|
||||
const editing =
|
||||
typeof recoveryEditEntry !== 'undefined' &&
|
||||
recoveryEditEntry &&
|
||||
$('#recovery-form')?.dataset.recoveryEdit === 'true';
|
||||
const oldPocket = input.old_pocket ?? '回收旧料',
|
||||
oldOriginal = editing ? recoveryValidationOriginal(input) : null;
|
||||
if (!activePocketKeys().includes(oldPocket) && !(oldOriginal && (oldOriginal.old_pocket ?? '回收旧料') === oldPocket))
|
||||
throw new Error('请选择旧料实际入库的已启用货盘。');
|
||||
if (pocketCountsEnabled(oldPocket)) {
|
||||
stockCountValue(input.old_stock_count, {
|
||||
optional:
|
||||
!!oldOriginal && oldOriginal.old_stock_count == null && (oldOriginal.old_pocket ?? '回收旧料') === oldPocket,
|
||||
title: '旧料入库数量(对)',
|
||||
});
|
||||
const since = state.pocketCatalog?.find(row => row.key === oldPocket)?.countSince;
|
||||
if (input.old_stock_count != null && String(input.old_stock_count).trim() !== '' && since && input.date < since)
|
||||
throw new Error('旧料入库日期不能早于' + since + '对数盘点基准。');
|
||||
}
|
||||
if (input.old_source === 'deposit') {
|
||||
if (!input.deposit_id) throw new Error('请选择寄存记录');
|
||||
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
|
||||
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
|
||||
}
|
||||
if (input.mode === 'exchange') {
|
||||
const x = input.exchange,
|
||||
original = editing ? recoveryValidationOriginal(input)?.exchange : null;
|
||||
if (pocketCountsEnabled(x.pocket))
|
||||
stockCountValue(x.stockCount, {
|
||||
optional:
|
||||
!!original &&
|
||||
original.stockCount == null &&
|
||||
original.pocket === x.pocket &&
|
||||
Number(original.quantity) === Number(x.quantity),
|
||||
title: '新货出库数量(对)',
|
||||
});
|
||||
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
|
||||
if (
|
||||
x.pocket !== '' &&
|
||||
!activePocketKeys().includes(x.pocket) &&
|
||||
!(editing && recoveryValidationOriginal(input)?.exchange?.pocket === x.pocket)
|
||||
)
|
||||
throw new Error('请选择新货实际出库的已启用货盘。');
|
||||
for (const [index, row] of (x.products || []).entries()) {
|
||||
const original = editing
|
||||
? (recoveryEditEntry.data.inputs.exchange?.products ?? [recoveryEditEntry.data.inputs.exchange])[index]
|
||||
: null;
|
||||
if (!row.name || row.name.length > 60 || LedgerCalc.isSilver(row.name))
|
||||
throw new Error('请逐件填写黄金商品名称。');
|
||||
if (row.pocket !== '' && !activePocketKeys().includes(row.pocket) && row.pocket !== original?.pocket)
|
||||
throw new Error('请选择已启用货盘或外配。');
|
||||
if (pocketCountsEnabled(row.pocket))
|
||||
stockCountValue(row.stockCount, {
|
||||
optional:
|
||||
!!original &&
|
||||
original.stockCount == null &&
|
||||
original.pocket === row.pocket &&
|
||||
original.quantity === row.quantity,
|
||||
});
|
||||
if (!row.cost_labor) throw new Error('请逐件填写进货工费,没有发生填0。');
|
||||
recoveryUnits(row.cost_labor.mode === 'gram' ? row.cost_labor.rate : row.cost_labor.amount, 2, '进货工费');
|
||||
if (!teamMemberKeys().includes(row.cost_labor_payer)) throw new Error('请选择工费付款人。');
|
||||
}
|
||||
if (!x.cost_labor) throw new Error('请填写进货工费,没有发生请明确填0。');
|
||||
recoveryUnits(x.cost_labor.mode === 'total' ? x.cost_labor.amount : x.cost_labor.rate, 2, '进货工费');
|
||||
if (calculation.differenceMg > 0) {
|
||||
if (!x.cost_material) throw new Error('请填写差重进货料价,或选择每日料池。');
|
||||
if (x.cost_material.mode === 'gram') {
|
||||
if (recoveryUnits(x.cost_material.rate, 2, '差重进货料价') <= 0) throw new Error('差重进货料价须大于0。');
|
||||
} else if (!validOrderDate(x.cost_material.poolId) || x.cost_material.poolId > input.date)
|
||||
throw new Error('料池日期不能晚于业务日期。');
|
||||
}
|
||||
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
|
||||
if (!teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
||||
}
|
||||
if (calculation.netSettlement < 0 && isCreditCardAccount(input.payment_account))
|
||||
throw new Error('向客户付款不能使用信用卡收款账户。');
|
||||
if (!state.accounts.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
||||
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
||||
return input;
|
||||
}
|
||||
function recoveryCustomerRateField(title, name, value, { daily = true } = {}) {
|
||||
return `<div class="recovery-customer-rate">${recoveryNumberField(title, name, value, 2, 'required')}${daily ? button('使用当日加权料价', 'recovery-use-daily-rate', 'quiet', `data-rate-field="${e(name)}"`) + `<p class="small muted" data-rate-status></p>` : ''}</div>`;
|
||||
}
|
||||
@@ -1585,124 +1160,6 @@ const recoveryItemFields = [
|
||||
'material_rate',
|
||||
'material_payer',
|
||||
];
|
||||
function recoveryItemsInput(draft, { quote = false } = {}) {
|
||||
const common = {
|
||||
mode: 'exchange',
|
||||
date: draft.date,
|
||||
customer: draft.customer,
|
||||
customer_type: draft.customer_type,
|
||||
salesperson: draft.salesperson,
|
||||
member: draft.member,
|
||||
payer: draft.payer,
|
||||
payment_method: draft.payment_method,
|
||||
payment_recipient: draft.payment_recipient,
|
||||
payout_method: draft.payout_method,
|
||||
note: draft.note,
|
||||
verified: draft.verified,
|
||||
};
|
||||
const items = [draft, ...(draft.extra_products || [])].map(row => {
|
||||
const single = recoveryInput(
|
||||
{
|
||||
...recoveryDefaults('exchange'),
|
||||
...row,
|
||||
...common,
|
||||
independent_products: false,
|
||||
extra_products: [],
|
||||
charges: [],
|
||||
fee_items: [],
|
||||
charge_amount: '0',
|
||||
fee_amount: '0',
|
||||
discount: '0',
|
||||
rounding_mode: 'cent',
|
||||
},
|
||||
{ quote },
|
||||
);
|
||||
return {
|
||||
...(single.surplus_mode ? { surplus_mode: single.surplus_mode, surplus_memo: single.surplus_memo } : {}),
|
||||
...(single.old_source
|
||||
? { old_source: single.old_source, deposit_id: single.deposit_id, deposit_weight: single.deposit_weight }
|
||||
: {}),
|
||||
old_lines: single.old_lines,
|
||||
old_pocket: single.old_pocket,
|
||||
...(single.old_stock_count == null ? {} : { old_stock_count: single.old_stock_count }),
|
||||
buy_rate: single.buy_rate,
|
||||
...(single.buy_total == null ? {} : { buy_total: single.buy_total }),
|
||||
exchange: single.exchange,
|
||||
};
|
||||
});
|
||||
const first = recoveryInput(
|
||||
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
|
||||
{ quote: true },
|
||||
),
|
||||
input = {
|
||||
...first,
|
||||
old_lines: items.flatMap(row => row.old_lines),
|
||||
verified: !quote && draft.verified === true,
|
||||
exchange: {
|
||||
items,
|
||||
charges: first.exchange.charges,
|
||||
fee_items: first.exchange.fee_items,
|
||||
discount: draft.discount || '0',
|
||||
rounding_mode: draft.rounding_mode || 'yuan',
|
||||
},
|
||||
};
|
||||
delete input.old_source;
|
||||
delete input.deposit_id;
|
||||
delete input.deposit_weight;
|
||||
delete input.surplus_mode;
|
||||
delete input.surplus_memo;
|
||||
const q = recoveryCalculate(input);
|
||||
input.payment_account =
|
||||
q.netSettlement > 0
|
||||
? draft.payment_method === '信用卡'
|
||||
? '麦麦信用卡'
|
||||
: (draft.payment_recipient || recoveryPrefix(draft.member)) + (draft.payment_method || '微信')
|
||||
: recoveryPrefix(draft.payer || draft.member) + (draft.payout_method || '微信');
|
||||
return input;
|
||||
}
|
||||
function recoveryItemsCalculate(input) {
|
||||
const parts = input.exchange.items.map(row =>
|
||||
recoveryCalculate({
|
||||
...input,
|
||||
...row,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
surplus_mode: row.surplus_mode,
|
||||
surplus_memo: row.surplus_memo,
|
||||
mode: 'exchange',
|
||||
exchange: row.exchange,
|
||||
}),
|
||||
);
|
||||
const q = { mode: 'exchange', old_lines: parts.flatMap(p => p.old_lines), exchangeItems: parts };
|
||||
for (const key of [
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'matchedMg',
|
||||
'differenceMg',
|
||||
'surplusMg',
|
||||
'depositMg',
|
||||
'purchaseMg',
|
||||
'goldAmount',
|
||||
'laborAmount',
|
||||
'depreciationMg',
|
||||
'depreciationAmount',
|
||||
'purchaseAmount',
|
||||
'defaultPurchaseAmount',
|
||||
])
|
||||
q[key] = recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
||||
q.chargesAmount = recoveryLimit(
|
||||
(input.exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
||||
);
|
||||
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
|
||||
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
||||
q.receivable = input.exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
q.roundingAdjustment = q.receivable - before;
|
||||
q.netSettlement = q.receivable - q.purchaseAmount;
|
||||
q.cashReceipt = Math.max(0, q.netSettlement);
|
||||
q.cashPayment = Math.max(0, -q.netSettlement);
|
||||
return q;
|
||||
}
|
||||
function recoveryItemsFormDraft(form) {
|
||||
const read = (scope, name) => recoveryText(recoveryField(scope, name)?.value),
|
||||
flat = Object.fromEntries(recoveryDraftFields.map(k => [k, read(form, k)]));
|
||||
@@ -2021,11 +1478,6 @@ function customerMaterialSyncFields(scope, row, prefix = '') {
|
||||
}
|
||||
}
|
||||
}
|
||||
function customerMaterialOldLines(draft) {
|
||||
return [
|
||||
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
|
||||
];
|
||||
}
|
||||
function customerMaterialPanelHTML() {
|
||||
return `<section class="panel" id="customer-material-panel"><div class="panel-title"><h2>客户寄存料</h2><div class="actions">${button('寄存,暂不结算', 'customer-material-new')}${button('刷新寄存记录', 'customer-material-refresh', 'quiet')}</div></div><p class="small muted">公共寄存台账,仅按克重和备忘记录;不计入自有库存、购料成本或可用料池。</p><div id="customer-material-list">正在读取寄存记录…</div></section>`;
|
||||
}
|
||||
|
||||
@@ -20,72 +20,11 @@ function invalidateRecoveryChangeViews() {
|
||||
recoveryReviewEntry = null;
|
||||
$('#recovery-change-dialog')?.close();
|
||||
}
|
||||
function recoveryInputShape(input) {
|
||||
return (
|
||||
input &&
|
||||
Object.hasOwn(recoveryModeNames, input.mode) &&
|
||||
validOrderDate(input.date) &&
|
||||
typeof input.customer === 'string' &&
|
||||
typeof input.salesperson === 'string' &&
|
||||
teamMemberKeys().includes(input.member) &&
|
||||
Array.isArray(input.old_lines) &&
|
||||
input.old_lines.length > 0 &&
|
||||
input.old_lines.every(
|
||||
row => row && ['name', 'incoming_weight', 'melted_weight', 'purity'].every(key => typeof row[key] === 'string'),
|
||||
) &&
|
||||
(input.mode === 'direct' ||
|
||||
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
|
||||
);
|
||||
}
|
||||
function validateRecoveryEditDetail(data, id) {
|
||||
if (
|
||||
!data ||
|
||||
data.id !== id ||
|
||||
data.record?.id !== id ||
|
||||
!Number.isSafeInteger(data.revision) ||
|
||||
data.revision < 1 ||
|
||||
!['active', 'cancelled'].includes(data.status) ||
|
||||
!recoveryInputShape(data.inputs) ||
|
||||
!data.permissions ||
|
||||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
|
||||
key => typeof data.permissions[key] === 'boolean',
|
||||
) ||
|
||||
!Array.isArray(data.blockedUsages) ||
|
||||
!Array.isArray(data.history) ||
|
||||
(state.user.role !== 'owner' && data.inputs.member !== currentMember())
|
||||
)
|
||||
throw new Error('回收更正资料未完整返回或不属于当前成员,请重新读取。');
|
||||
if (data.record.member !== data.inputs.member || data.record.mode !== data.inputs.mode)
|
||||
throw new Error('回收记录身份与修改资料不一致。');
|
||||
if (data.pending && validateRecoveryChangeRequest(data.pending).recoveryId !== id)
|
||||
throw new Error('回收申请不属于当前记录。');
|
||||
if (data.history.some(row => validateRecoveryChangeRequest(row).recoveryId !== id))
|
||||
throw new Error('回收更正历史不属于当前记录。');
|
||||
return data;
|
||||
return recoveryPageRules.checkEdit(data, id);
|
||||
}
|
||||
function validateRecoveryChangeRequest(request) {
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
!request.id ||
|
||||
typeof request.recoveryId !== 'string' ||
|
||||
!Number.isSafeInteger(request.revision) ||
|
||||
request.revision < 1 ||
|
||||
!Number.isSafeInteger(request.recoveryRevision) ||
|
||||
request.recoveryRevision < 1 ||
|
||||
!['update', 'cancel'].includes(request.action) ||
|
||||
!['pending', 'approved', 'rejected'].includes(request.status) ||
|
||||
!recoveryInputShape(request.before) ||
|
||||
(request.action === 'update' && !recoveryInputShape(request.after)) ||
|
||||
(request.action === 'cancel' && request.after !== null) ||
|
||||
typeof request.canApprove !== 'boolean' ||
|
||||
!request.summary ||
|
||||
request.member !== request.before.member ||
|
||||
(request.after && (request.after.member !== request.member || request.after.mode !== request.before.mode)) ||
|
||||
(state.user.role !== 'owner' && request.member !== currentMember())
|
||||
)
|
||||
throw new Error('回收更正申请未完整返回或不属于当前成员,请重新读取。');
|
||||
return request;
|
||||
return recoveryPageRules.checkRequest(request);
|
||||
}
|
||||
function recoveryDetailChangeActionsHTML(value) {
|
||||
const info = recoveryDetailEdit;
|
||||
@@ -114,93 +53,7 @@ function recoveryEditPanelHTML(data) {
|
||||
return `${data.status === 'cancelled' ? '<div class="note">本单已取消,原记录和更正历史保留。</div>' : ''}${data.permissions.reason ? `<p class="small muted">${e(data.permissions.reason)}</p>` : ''}${recoveryMaterialBatchHTML(data.record.materialBatch)}${recoveryBlockedHTML(data.blockedUsages)}${data.permissions.canCancel && data.blockedUsages.length ? recoveryCancellationMaterialHTML() : ''}${data.pending ? `<section class="panel recovery-change-pending"><h3>待店主复核</h3><p class="small muted">原记录仍生效,申请尚未记账。</p>${recoveryChangeComparisonHTML(data.pending)}${button(state.user.role === 'owner' ? '查看并复核' : '查看申请', 'recovery-change-open', '', `data-id="${e(data.pending.id)}"`)}</section>` : ''}${data.history.length ? `<details><summary>更正与取消记录(${data.history.length})</summary><ul class="timeline">${data.history.map(row => `<li>${e(recoveryChangeStatus(row))} · ${e(row.requesterName || '未提供')}${row.reviewerName ? ' · ' + e(row.reviewerName) + '复核' : ''}${row.note ? '<p>' + e(row.note) + '</p>' : ''}${button('查看前后内容', 'recovery-change-open', 'quiet', `data-id="${e(row.id)}"`)}</li>`).join('')}</ul></details>` : ''}`;
|
||||
}
|
||||
function recoveryEditDraft(input) {
|
||||
if (input.exchange?.items) {
|
||||
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
|
||||
first = rows[0],
|
||||
x = input.exchange;
|
||||
return {
|
||||
...first,
|
||||
independent_products: rows.length > 1,
|
||||
extra_products: rows.slice(1),
|
||||
charges: x.charges,
|
||||
charge_name: x.charges[0]?.name || '其他收费',
|
||||
charge_amount: x.charges[0]?.amount || '0',
|
||||
fee_items: x.fee_items,
|
||||
fee_note: x.fee_items[0]?.note || '其他费用',
|
||||
fee_amount: x.fee_items[0]?.amount || '0',
|
||||
fee_payer: x.fee_items[0]?.payer || input.member,
|
||||
discount: x.discount,
|
||||
rounding_mode: x.rounding_mode,
|
||||
};
|
||||
}
|
||||
const first = input.old_lines[0],
|
||||
x = input.exchange || {},
|
||||
charge = x.charges?.[0],
|
||||
fee = x.fee_items?.[0],
|
||||
account = input.payment_account || '',
|
||||
identity = accountIdentity(account),
|
||||
recipient = identity ? memberAccountPrefix(identity.member) : recoveryPrefix(input.member),
|
||||
method = identity?.channel || '微信';
|
||||
return {
|
||||
...recoveryDefaults(input.mode),
|
||||
mode: input.mode,
|
||||
surplus_mode: input.surplus_mode || 'buy',
|
||||
surplus_memo: input.surplus_memo || '',
|
||||
old_source: input.old_source || 'incoming',
|
||||
deposit_id: input.deposit_id || '',
|
||||
deposit_weight: input.deposit_weight || '',
|
||||
date: input.date,
|
||||
customer: input.customer,
|
||||
salesperson: input.salesperson,
|
||||
member: input.member,
|
||||
note: input.note || '',
|
||||
old_pocket: input.old_pocket ?? '回收旧料',
|
||||
old_stock_count: input.old_stock_count ?? '',
|
||||
old_name: first.name,
|
||||
incoming_weight: first.incoming_weight,
|
||||
melted_weight: first.melted_weight,
|
||||
purity: first.purity,
|
||||
old_lines: JSON.parse(JSON.stringify(input.old_lines)),
|
||||
buy_rate: input.buy_rate,
|
||||
buy_total: input.buy_total ?? '',
|
||||
buy_total_manual: Object.hasOwn(input, 'buy_total'),
|
||||
melted_manual: true,
|
||||
depreciation_manual: Object.hasOwn(x, 'depreciation_weight'),
|
||||
payer: input.payer,
|
||||
payment_method: method,
|
||||
payment_recipient: recipient,
|
||||
payout_method: method === '信用卡' ? '微信' : method,
|
||||
new_name: x.name || '足金999',
|
||||
new_quantity: x.quantity || '',
|
||||
pocket: x.pocket ?? state.pockets[0] ?? '',
|
||||
stockCount: x.stockCount ?? '',
|
||||
gold_price: x.gold_price || '0',
|
||||
labor_mode: x.labor_mode || 'gram',
|
||||
labor_rate: x.labor_rate || '0',
|
||||
depreciation_weight: x.depreciation_weight ?? '',
|
||||
depreciation_rate: x.depreciation_rate || '0',
|
||||
charge_name: charge?.name || '其他收费',
|
||||
charge_amount: charge?.amount || '0',
|
||||
charges: JSON.parse(JSON.stringify(x.charges || [])),
|
||||
discount: x.discount || '0',
|
||||
rounding_mode: x.rounding_mode || 'cent',
|
||||
material_source: x.cost_material?.mode === 'pool' ? 'pool' : 'manual',
|
||||
material_pool_id: x.cost_material?.poolId || input.date,
|
||||
material_rate: x.cost_material?.rate || '',
|
||||
material_payer: x.cost_material_payer || input.member,
|
||||
cost_labor_mode: x.cost_labor?.mode || 'total',
|
||||
cost_labor_value: x.cost_labor?.mode === 'gram' ? x.cost_labor.rate : (x.cost_labor?.amount ?? ''),
|
||||
cost_payer: x.cost_payer || input.member,
|
||||
labor_payer: x.cost_labor_payer || x.cost_payer || input.member,
|
||||
fee_note: fee?.note || '其他费用',
|
||||
fee_amount: fee?.amount || '0',
|
||||
fee_payer: fee?.payer || input.member,
|
||||
fee_items: JSON.parse(JSON.stringify(x.fee_items || [])),
|
||||
...(x.products
|
||||
? { ...recoveryProductDraft(x.products[0]), extra_products: x.products.slice(1).map(recoveryProductDraft) }
|
||||
: {}),
|
||||
verified: false,
|
||||
};
|
||||
return recoveryPageRules.forEdit(input);
|
||||
}
|
||||
function recoveryEditFormDraft(form, flat) {
|
||||
const entry = recoveryEditEntry;
|
||||
|
||||
@@ -0,0 +1,789 @@
|
||||
'use strict';
|
||||
// 两种前端共用的回收规则。金额为分、重量为毫克,新版与历史两种多件置换格式分别结算。
|
||||
(function (root) {
|
||||
const recoveryModeNames = { direct: '直接回收', exchange: '置换' };
|
||||
const recoveryText = value => String(value ?? '').trim();
|
||||
const recoveryProductFields = [
|
||||
'new_name',
|
||||
'new_quantity',
|
||||
'pocket',
|
||||
'stockCount',
|
||||
'labor_mode',
|
||||
'labor_rate',
|
||||
'cost_labor_mode',
|
||||
'cost_labor_value',
|
||||
'labor_payer',
|
||||
];
|
||||
|
||||
function recoveryUnits(value, places, title, { zero = true } = {}) {
|
||||
const raw = recoveryText(value),
|
||||
pattern = new RegExp('^\\d+(?:\\.\\d{1,' + places + '})?$');
|
||||
if (!pattern.test(raw))
|
||||
throw new Error(`${title}请填写${zero ? '不小于0' : '大于0'}的数字,最多保留${places}位小数。`);
|
||||
const [whole, fraction = ''] = raw.split('.'),
|
||||
units = BigInt(whole) * 10n ** BigInt(places) + BigInt(fraction.padEnd(places, '0'));
|
||||
if (units > 100000000000n || (!zero && units === 0n)) throw new Error(`${title}超出范围或尚未填写。`);
|
||||
return Number(units);
|
||||
}
|
||||
|
||||
function recoveryLimit(value, title = '回收/置换合计') {
|
||||
if (!Number.isSafeInteger(value) || Math.abs(value) > 100000000000)
|
||||
throw new Error(title + '超出支持范围,请核对。');
|
||||
return value;
|
||||
}
|
||||
|
||||
function recoveryMul(weight, rate) {
|
||||
return recoveryLimit(Number((BigInt(weight) * BigInt(rate) + 500n) / 1000n));
|
||||
}
|
||||
|
||||
function recoveryProductDraft(row) {
|
||||
return {
|
||||
new_name: row.name,
|
||||
new_quantity: row.quantity,
|
||||
pocket: row.pocket,
|
||||
stockCount: row.stockCount ?? '',
|
||||
labor_mode: row.labor_mode,
|
||||
labor_rate: row.labor_rate,
|
||||
cost_labor_mode: row.cost_labor?.mode || 'total',
|
||||
cost_labor_value: row.cost_labor?.mode === 'gram' ? row.cost_labor.rate : (row.cost_labor?.amount ?? ''),
|
||||
labor_payer: row.cost_labor_payer,
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryNewWeight(draft) {
|
||||
return [draft, ...(draft.extra_products || [])].reduce(
|
||||
(n, row) => recoveryLimit(n + recoveryUnits(row.new_quantity, 3, '新货克重', { zero: false })),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
function recoverySharedOldDraft(draft) {
|
||||
if (!draft.independent_products) return draft;
|
||||
return {
|
||||
...draft,
|
||||
independent_products: false,
|
||||
extra_products: (draft.extra_products || []).map(row =>
|
||||
Object.fromEntries(recoveryProductFields.map(k => [k, row[k]])),
|
||||
),
|
||||
...(draft.extra_products?.length ? { buy_total_manual: false, buy_total: '', depreciation_manual: false } : {}),
|
||||
verified: false,
|
||||
shared_old_notice: draft.extra_products?.length ? '已恢复为一份来料,沿用上方第一份来料;请核对实际总克重。' : '',
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryCalculate(input) {
|
||||
if (input.mode === 'exchange' && input.exchange?.items) return recoveryItemsCalculate(input);
|
||||
if (!Object.hasOwn(recoveryModeNames, input.mode)) throw new Error('请选择直接回收或置换。');
|
||||
const oldLines = (input.old_lines || []).map(line => {
|
||||
const incomingMg = recoveryUnits(line.incoming_weight, 3, '来料重量', { zero: false }),
|
||||
meltedMg = recoveryUnits(line.melted_weight, 3, '熔后重量', { zero: false }),
|
||||
purity = recoveryUnits(line.purity, 3, '成色', { zero: false });
|
||||
if (meltedMg > incomingMg) throw new Error('熔后重量不能大于来料重量,请核对。');
|
||||
if (purity > 100000) throw new Error('成色请填写0到100之间的百分数,例如99表示99%。');
|
||||
const foldedMg = Number((BigInt(meltedMg) * BigInt(purity) + 50000n) / 100000n);
|
||||
if (foldedMg <= 0) throw new Error('折后重量须至少为0.001g,请核对重量和成色。');
|
||||
return { ...line, incomingMg, meltedMg, purity: purity / 1000, foldedMg };
|
||||
});
|
||||
if (!oldLines.length) throw new Error('请填写旧料重量。');
|
||||
const oldMg = recoveryLimit(
|
||||
oldLines.reduce((sum, line) => sum + line.foldedMg, 0),
|
||||
'旧料总重量',
|
||||
),
|
||||
buyRate = recoveryUnits(input.buy_rate, 2, '回收单价');
|
||||
let newMg = 0,
|
||||
matchedMg = 0,
|
||||
differenceMg = 0,
|
||||
surplusMg = oldMg,
|
||||
goldAmount = 0,
|
||||
laborAmount = 0,
|
||||
depreciationMg = 0,
|
||||
depreciationAmount = 0,
|
||||
chargesAmount = 0,
|
||||
discount = 0,
|
||||
receivable = 0,
|
||||
roundingAdjustment = 0;
|
||||
if (input.mode === 'exchange') {
|
||||
const x = input.exchange || {};
|
||||
newMg = x.products
|
||||
? recoveryLimit(
|
||||
x.products.reduce((n, row) => n + recoveryUnits(row.quantity, 3, '新货克重', { zero: false }), 0),
|
||||
)
|
||||
: recoveryUnits(x.quantity, 3, '新货克重', { zero: false });
|
||||
matchedMg = Math.min(oldMg, newMg);
|
||||
differenceMg = Math.max(0, newMg - oldMg);
|
||||
surplusMg = Math.max(0, oldMg - newMg);
|
||||
const goldPrice = differenceMg > 0 ? recoveryUnits(x.gold_price, 2, '当天销售金价') : 0,
|
||||
laborRate = recoveryUnits(x.labor_rate, 2, '销售工费'),
|
||||
depreciationRate = recoveryUnits(x.depreciation_rate ?? '10', 2, '折旧费单价');
|
||||
if (differenceMg > 0 && goldPrice <= 0) throw new Error('有补金差重时,请填写大于0的当天销售金价。');
|
||||
goldAmount = recoveryMul(differenceMg, goldPrice);
|
||||
laborAmount = x.products
|
||||
? recoveryLimit(
|
||||
x.products.reduce((n, row) => {
|
||||
const rate = recoveryUnits(row.labor_rate, 2, '销售工费');
|
||||
return (
|
||||
n + (row.labor_mode === 'total' ? rate : recoveryMul(recoveryUnits(row.quantity, 3, '新货克重'), rate))
|
||||
);
|
||||
}, 0),
|
||||
)
|
||||
: x.labor_mode === 'total'
|
||||
? laborRate
|
||||
: recoveryMul(newMg, laborRate);
|
||||
depreciationMg =
|
||||
x.depreciation_weight == null ? matchedMg : recoveryUnits(x.depreciation_weight, 3, '折旧费计费克重');
|
||||
depreciationAmount = recoveryMul(depreciationMg, depreciationRate);
|
||||
chargesAmount = recoveryLimit(
|
||||
(x.charges || []).reduce((sum, row) => sum + recoveryUnits(row.amount, 2, '其他收费'), 0),
|
||||
);
|
||||
discount = recoveryUnits(x.discount || '0', 2, '优惠金额');
|
||||
const before = recoveryLimit(goldAmount + laborAmount + depreciationAmount + chargesAmount) - discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于本次置换费用。');
|
||||
receivable = x.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
roundingAdjustment = receivable - before;
|
||||
}
|
||||
const depositMg = input.mode === 'exchange' && input.surplus_mode === 'deposit' ? surplusMg : 0,
|
||||
purchaseMg = surplusMg - depositMg;
|
||||
if (purchaseMg > 0 && buyRate <= 0) throw new Error('有回收旧料或余料时,请填写大于0的回收单价。');
|
||||
const defaultPurchaseAmount = recoveryMul(purchaseMg, buyRate),
|
||||
purchaseAmount = depositMg
|
||||
? 0
|
||||
: input.buy_total == null
|
||||
? defaultPurchaseAmount
|
||||
: recoveryUnits(input.buy_total, 2, input.mode === 'direct' ? '回收结算额' : '余料回收款');
|
||||
if (purchaseMg > 0 && purchaseAmount <= 0) throw new Error('回收结算金额须大于0,请核对。');
|
||||
if (!surplusMg && purchaseAmount) throw new Error('本次没有余料,余料回收款应为0。');
|
||||
const netSettlement = recoveryLimit(receivable - purchaseAmount);
|
||||
return {
|
||||
mode: input.mode,
|
||||
old_lines: oldLines,
|
||||
oldMg,
|
||||
newMg,
|
||||
matchedMg,
|
||||
differenceMg,
|
||||
surplusMg,
|
||||
depositMg,
|
||||
purchaseMg,
|
||||
goldAmount,
|
||||
laborAmount,
|
||||
depreciationMg,
|
||||
depreciationAmount,
|
||||
chargesAmount,
|
||||
discount,
|
||||
receivable,
|
||||
purchaseAmount,
|
||||
defaultPurchaseAmount,
|
||||
roundingAdjustment,
|
||||
netSettlement,
|
||||
cashReceipt: Math.max(0, netSettlement),
|
||||
cashPayment: Math.max(0, -netSettlement),
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryItemsCalculate(input) {
|
||||
const parts = input.exchange.items.map(row =>
|
||||
recoveryCalculate({
|
||||
...input,
|
||||
...row,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
surplus_mode: row.surplus_mode,
|
||||
surplus_memo: row.surplus_memo,
|
||||
mode: 'exchange',
|
||||
exchange: row.exchange,
|
||||
}),
|
||||
);
|
||||
const q = { mode: 'exchange', old_lines: parts.flatMap(p => p.old_lines), exchangeItems: parts };
|
||||
for (const key of [
|
||||
'oldMg',
|
||||
'newMg',
|
||||
'matchedMg',
|
||||
'differenceMg',
|
||||
'surplusMg',
|
||||
'depositMg',
|
||||
'purchaseMg',
|
||||
'goldAmount',
|
||||
'laborAmount',
|
||||
'depreciationMg',
|
||||
'depreciationAmount',
|
||||
'purchaseAmount',
|
||||
'defaultPurchaseAmount',
|
||||
])
|
||||
q[key] = recoveryLimit(parts.reduce((n, p) => n + p[key], 0));
|
||||
q.chargesAmount = recoveryLimit(
|
||||
(input.exchange.charges || []).reduce((n, r) => n + recoveryUnits(r.amount, 2, '其他收费'), 0),
|
||||
);
|
||||
q.discount = recoveryUnits(input.exchange.discount || '0', 2, '整单优惠');
|
||||
const before = recoveryLimit(q.goldAmount + q.laborAmount + q.depreciationAmount + q.chargesAmount) - q.discount;
|
||||
if (before < 0) throw new Error('优惠金额不能大于置换费用');
|
||||
q.receivable = input.exchange.rounding_mode === 'yuan' ? Math.floor((before + 50) / 100) * 100 : before;
|
||||
q.roundingAdjustment = q.receivable - before;
|
||||
q.netSettlement = q.receivable - q.purchaseAmount;
|
||||
q.cashReceipt = Math.max(0, q.netSettlement);
|
||||
q.cashPayment = Math.max(0, -q.netSettlement);
|
||||
return q;
|
||||
}
|
||||
|
||||
function customerMaterialOldLines(draft) {
|
||||
return [
|
||||
{ name: '客户寄存料', incoming_weight: draft.deposit_weight, melted_weight: draft.deposit_weight, purity: '100' },
|
||||
];
|
||||
}
|
||||
|
||||
// 页面的成员、货盘和账户策略由调用方提供。originalInput 只在编辑既有单据时参与历史值校验。
|
||||
function createModel(context) {
|
||||
function recoveryProductInput(draft) {
|
||||
return {
|
||||
name: draft.new_name,
|
||||
quantity: draft.new_quantity,
|
||||
pocket: draft.pocket,
|
||||
...(context.pocketCountsEnabled(draft.pocket) ? { stockCount: draft.stockCount || null } : {}),
|
||||
labor_mode: draft.labor_mode,
|
||||
labor_rate: draft.labor_rate,
|
||||
...(draft.cost_labor_value !== ''
|
||||
? {
|
||||
cost_labor:
|
||||
draft.cost_labor_mode === 'total'
|
||||
? { mode: 'total', amount: draft.cost_labor_value }
|
||||
: { mode: 'gram', rate: draft.cost_labor_value },
|
||||
}
|
||||
: {}),
|
||||
cost_labor_payer: draft.labor_payer,
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryDefaults(mode = 'direct') {
|
||||
const member = context.currentMember();
|
||||
return {
|
||||
independent_products: false,
|
||||
surplus_mode: 'buy',
|
||||
surplus_memo: '',
|
||||
old_source: 'incoming',
|
||||
deposit_id: '',
|
||||
deposit_weight: '',
|
||||
mode,
|
||||
date: context.state.today,
|
||||
customer: '',
|
||||
salesperson: context.defaultSalesperson(),
|
||||
member,
|
||||
old_name: 'Au旧料',
|
||||
incoming_weight: '',
|
||||
melted_weight: '',
|
||||
purity: '100',
|
||||
old_pocket: '回收旧料',
|
||||
old_stock_count: '',
|
||||
buy_rate: '',
|
||||
buy_total: '',
|
||||
new_name: '足金999',
|
||||
new_quantity: '',
|
||||
pocket: '现货',
|
||||
stockCount: '',
|
||||
gold_price: '',
|
||||
labor_mode: 'gram',
|
||||
labor_rate: '',
|
||||
depreciation_weight: '',
|
||||
depreciation_rate: '10',
|
||||
charge_name: '其他收费',
|
||||
charge_amount: '0',
|
||||
discount: '0',
|
||||
rounding_mode: 'yuan',
|
||||
material_source: 'pool',
|
||||
material_pool_id: context.state.today,
|
||||
material_rate: '',
|
||||
material_payer: member,
|
||||
cost_labor_mode: 'gram',
|
||||
cost_labor_value: '',
|
||||
labor_payer: member,
|
||||
fee_note: '其他费用',
|
||||
fee_amount: '0',
|
||||
fee_payer: member,
|
||||
payment_method: '微信',
|
||||
payment_recipient: context.memberAccountPrefix(member),
|
||||
payout_method: '微信',
|
||||
payer: member,
|
||||
note: '',
|
||||
buy_total_manual: false,
|
||||
depreciation_manual: false,
|
||||
melted_manual: false,
|
||||
};
|
||||
}
|
||||
|
||||
function recoveryInput(draft, { quote = false } = {}) {
|
||||
if (draft.mode === 'exchange' && draft.independent_products) return recoveryItemsInput(draft, { quote });
|
||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||
draft = { ...draft, old_lines: customerMaterialOldLines(draft) };
|
||||
const member = context.state.user.role === 'owner' ? draft.member : context.currentMember();
|
||||
const input = {
|
||||
mode: draft.mode,
|
||||
date: draft.date,
|
||||
customer: draft.customer,
|
||||
customer_type: draft.customer_type,
|
||||
salesperson: draft.salesperson,
|
||||
member,
|
||||
note: draft.note,
|
||||
old_pocket: draft.old_pocket ?? '回收旧料',
|
||||
...(context.pocketCountsEnabled(draft.old_pocket)
|
||||
? { old_stock_count: recoveryText(draft.old_stock_count) || null }
|
||||
: {}),
|
||||
old_lines: Array.isArray(draft.old_lines)
|
||||
? draft.old_lines
|
||||
: [
|
||||
{
|
||||
name: draft.old_name || 'Au旧料',
|
||||
incoming_weight: draft.incoming_weight,
|
||||
melted_weight: draft.melted_weight,
|
||||
purity: draft.purity,
|
||||
},
|
||||
],
|
||||
buy_rate: draft.buy_rate,
|
||||
payer: draft.payer || member,
|
||||
payment_account: context.memberAccountPrefix(draft.payer || member) + (draft.payout_method || '微信'),
|
||||
verified: !quote && draft.verified === true,
|
||||
};
|
||||
if (draft.mode === 'exchange' && draft.old_source === 'deposit')
|
||||
Object.assign(input, {
|
||||
old_source: 'deposit',
|
||||
deposit_id: draft.deposit_id,
|
||||
deposit_weight: draft.deposit_weight,
|
||||
});
|
||||
if (draft.buy_total_manual && draft.buy_total !== '') input.buy_total = draft.buy_total;
|
||||
if (draft.mode === 'exchange' && draft.surplus_mode === 'deposit')
|
||||
Object.assign(input, {
|
||||
surplus_mode: 'deposit',
|
||||
surplus_memo: draft.surplus_memo || '',
|
||||
buy_rate: '0',
|
||||
buy_total: '0',
|
||||
});
|
||||
if (draft.mode === 'exchange') {
|
||||
const costLabor =
|
||||
draft.cost_labor_value === ''
|
||||
? undefined
|
||||
: draft.cost_labor_mode === 'total'
|
||||
? { mode: 'total', amount: draft.cost_labor_value }
|
||||
: { mode: 'gram', rate: draft.cost_labor_value };
|
||||
const costMaterial =
|
||||
draft.material_source === 'pool'
|
||||
? { mode: 'pool', poolId: draft.material_pool_id || draft.date }
|
||||
: draft.material_rate === ''
|
||||
? undefined
|
||||
: { mode: 'gram', rate: draft.material_rate };
|
||||
input.exchange = {
|
||||
name: draft.new_name,
|
||||
quantity: draft.new_quantity,
|
||||
pocket: draft.pocket,
|
||||
...(context.pocketCountsEnabled(draft.pocket)
|
||||
? {
|
||||
stockCount:
|
||||
draft.stockCount == null || String(draft.stockCount).trim() === '' ? null : draft.stockCount,
|
||||
}
|
||||
: {}),
|
||||
gold_price: draft.gold_price,
|
||||
labor_mode: draft.labor_mode,
|
||||
labor_rate: draft.labor_rate,
|
||||
depreciation_rate: draft.depreciation_rate || '0',
|
||||
...(draft.depreciation_manual ? { depreciation_weight: draft.depreciation_weight } : {}),
|
||||
...(costMaterial ? { cost_material: costMaterial } : {}),
|
||||
...(costLabor ? { cost_labor: costLabor } : {}),
|
||||
cost_payer: draft.cost_payer || draft.labor_payer || member,
|
||||
cost_material_payer: draft.material_payer || member,
|
||||
cost_labor_payer: draft.labor_payer || member,
|
||||
charges: Array.isArray(draft.charges)
|
||||
? draft.charges
|
||||
: recoveryText(draft.charge_amount) && recoveryUnits(draft.charge_amount, 2, '其他收费') > 0
|
||||
? [{ name: draft.charge_name || '其他收费', amount: draft.charge_amount }]
|
||||
: [],
|
||||
fee_items: Array.isArray(draft.fee_items)
|
||||
? draft.fee_items
|
||||
: recoveryText(draft.fee_amount) && recoveryUnits(draft.fee_amount, 2, '其他内部费用') > 0
|
||||
? [
|
||||
{
|
||||
key: 'other',
|
||||
note: draft.fee_note || '其他费用',
|
||||
amount: draft.fee_amount,
|
||||
payer: draft.fee_payer || member,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
discount: draft.discount || '0',
|
||||
rounding_mode: draft.rounding_mode || 'yuan',
|
||||
};
|
||||
if (draft.extra_products?.length)
|
||||
input.exchange.products = [draft, ...draft.extra_products].map(recoveryProductInput);
|
||||
const old = recoveryCalculate({ ...input, mode: 'direct', buy_rate: '1', buy_total: '1' }),
|
||||
newMg = recoveryNewWeight(draft);
|
||||
if (newMg >= old.oldMg) {
|
||||
input.buy_rate = '0';
|
||||
input.buy_total = '0';
|
||||
}
|
||||
if (newMg <= old.oldMg) {
|
||||
input.exchange.gold_price = '0';
|
||||
delete input.exchange.cost_material;
|
||||
}
|
||||
const calculation = recoveryCalculate(input);
|
||||
if (calculation.netSettlement > 0)
|
||||
input.payment_account =
|
||||
draft.payment_method === '信用卡'
|
||||
? '麦麦信用卡'
|
||||
: (draft.payment_recipient || context.memberAccountPrefix(member)) + (draft.payment_method || '微信');
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function validateRecoveryInput(input) {
|
||||
if (input.exchange?.items) {
|
||||
for (const [index, row] of input.exchange.items.entries())
|
||||
validateRecoveryInput({
|
||||
...input,
|
||||
...row,
|
||||
_recoveryItemIndex: index,
|
||||
buy_total: row.buy_total,
|
||||
buy_rate: row.buy_rate,
|
||||
exchange: row.exchange,
|
||||
payment_account: context.memberAccountPrefix(input.payer) + '微信',
|
||||
});
|
||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效收付款账户');
|
||||
return input;
|
||||
}
|
||||
if (!context.validOrderDate(input.date) || input.date > context.state.today)
|
||||
throw new Error('业务日期请选择今天或之前的有效日期。');
|
||||
if (!input.customer || input.customer.length > 60) throw new Error('请填写1~60字的客户称呼或代号。');
|
||||
if (!input.salesperson || input.salesperson.length > 30) throw new Error('请填写1~30字的开单人。');
|
||||
if (input.note.length > 240) throw new Error('备注最多填写240字。');
|
||||
if (!context.teamMemberKeys().includes(input.member) || !context.teamMemberKeys().includes(input.payer))
|
||||
throw new Error('请选择归属成员和实际付款人。');
|
||||
const calculation = recoveryCalculate(input);
|
||||
const source = context.originalInput,
|
||||
item = source?.exchange?.items?.[input._recoveryItemIndex],
|
||||
oldOriginal = item ? { ...source, ...item } : source;
|
||||
const oldPocket = input.old_pocket ?? '回收旧料';
|
||||
if (
|
||||
!context.activePocketKeys().includes(oldPocket) &&
|
||||
!(oldOriginal && (oldOriginal.old_pocket ?? '回收旧料') === oldPocket)
|
||||
)
|
||||
throw new Error('请选择旧料实际入库的已启用货盘。');
|
||||
if (context.pocketCountsEnabled(oldPocket)) {
|
||||
context.stockCountValue(input.old_stock_count, {
|
||||
optional:
|
||||
!!oldOriginal &&
|
||||
oldOriginal.old_stock_count == null &&
|
||||
(oldOriginal.old_pocket ?? '回收旧料') === oldPocket,
|
||||
title: '旧料入库数量(对)',
|
||||
});
|
||||
const since = context.state.pocketCatalog?.find(row => row.key === oldPocket)?.countSince;
|
||||
if (input.old_stock_count != null && String(input.old_stock_count).trim() !== '' && since && input.date < since)
|
||||
throw new Error('旧料入库日期不能早于' + since + '对数盘点基准。');
|
||||
}
|
||||
if (input.old_source === 'deposit') {
|
||||
if (!input.deposit_id) throw new Error('请选择寄存记录');
|
||||
if (recoveryUnits(input.deposit_weight, 3, '使用寄存克重', { zero: false }) > calculation.newMg)
|
||||
throw new Error('本次寄存用量不能超过新货克重,剩余继续寄存');
|
||||
}
|
||||
if (input.mode === 'exchange') {
|
||||
const x = input.exchange,
|
||||
original = oldOriginal?.exchange;
|
||||
if (context.pocketCountsEnabled(x.pocket))
|
||||
context.stockCountValue(x.stockCount, {
|
||||
optional:
|
||||
!!original &&
|
||||
original.stockCount == null &&
|
||||
original.pocket === x.pocket &&
|
||||
Number(original.quantity) === Number(x.quantity),
|
||||
title: '新货出库数量(对)',
|
||||
});
|
||||
if (!x.name || x.name.length > 60) throw new Error('请填写1~60字的新货商品名称。');
|
||||
if (
|
||||
x.pocket !== '' &&
|
||||
!context.activePocketKeys().includes(x.pocket) &&
|
||||
!(source && original?.pocket === x.pocket)
|
||||
)
|
||||
throw new Error('请选择新货实际出库的已启用货盘。');
|
||||
for (const [index, row] of (x.products || []).entries()) {
|
||||
const original = source ? (source.exchange?.products ?? [source.exchange])[index] : null;
|
||||
if (!row.name || row.name.length > 60 || context.isSilver(row.name))
|
||||
throw new Error('请逐件填写黄金商品名称。');
|
||||
if (row.pocket !== '' && !context.activePocketKeys().includes(row.pocket) && row.pocket !== original?.pocket)
|
||||
throw new Error('请选择已启用货盘或外配。');
|
||||
if (context.pocketCountsEnabled(row.pocket))
|
||||
context.stockCountValue(row.stockCount, {
|
||||
optional:
|
||||
!!original &&
|
||||
original.stockCount == null &&
|
||||
original.pocket === row.pocket &&
|
||||
original.quantity === row.quantity,
|
||||
});
|
||||
if (!row.cost_labor) throw new Error('请逐件填写进货工费,没有发生填0。');
|
||||
recoveryUnits(row.cost_labor.mode === 'gram' ? row.cost_labor.rate : row.cost_labor.amount, 2, '进货工费');
|
||||
if (!context.teamMemberKeys().includes(row.cost_labor_payer)) throw new Error('请选择工费付款人。');
|
||||
}
|
||||
if (!x.cost_labor) throw new Error('请填写进货工费,没有发生请明确填0。');
|
||||
recoveryUnits(x.cost_labor.mode === 'total' ? x.cost_labor.amount : x.cost_labor.rate, 2, '进货工费');
|
||||
if (calculation.differenceMg > 0) {
|
||||
if (!x.cost_material) throw new Error('请填写差重进货料价,或选择每日料池。');
|
||||
if (x.cost_material.mode === 'gram') {
|
||||
if (recoveryUnits(x.cost_material.rate, 2, '差重进货料价') <= 0) throw new Error('差重进货料价须大于0。');
|
||||
} else if (!context.validOrderDate(x.cost_material.poolId) || x.cost_material.poolId > input.date)
|
||||
throw new Error('料池日期不能晚于业务日期。');
|
||||
}
|
||||
for (const payer of [x.cost_material_payer, x.cost_labor_payer, ...x.fee_items.map(row => row.payer)])
|
||||
if (!context.teamMemberKeys().includes(payer)) throw new Error('请选择内部成本的实际付款人。');
|
||||
}
|
||||
if (calculation.netSettlement < 0 && context.isCreditCardAccount(input.payment_account))
|
||||
throw new Error('向客户付款不能使用信用卡收款账户。');
|
||||
if (!context.state.accounts.includes(input.payment_account)) throw new Error('请选择有效的收付款方式。');
|
||||
if (input.verified !== true) throw new Error('请核实重量、结算金额和实际收付款后,勾选确认再保存。');
|
||||
return input;
|
||||
}
|
||||
|
||||
function recoveryItemsInput(draft, { quote = false } = {}) {
|
||||
const common = {
|
||||
mode: 'exchange',
|
||||
date: draft.date,
|
||||
customer: draft.customer,
|
||||
customer_type: draft.customer_type,
|
||||
salesperson: draft.salesperson,
|
||||
member: draft.member,
|
||||
payer: draft.payer,
|
||||
payment_method: draft.payment_method,
|
||||
payment_recipient: draft.payment_recipient,
|
||||
payout_method: draft.payout_method,
|
||||
note: draft.note,
|
||||
verified: draft.verified,
|
||||
};
|
||||
const items = [draft, ...(draft.extra_products || [])].map(row => {
|
||||
const single = recoveryInput(
|
||||
{
|
||||
...recoveryDefaults('exchange'),
|
||||
...row,
|
||||
...common,
|
||||
independent_products: false,
|
||||
extra_products: [],
|
||||
charges: [],
|
||||
fee_items: [],
|
||||
charge_amount: '0',
|
||||
fee_amount: '0',
|
||||
discount: '0',
|
||||
rounding_mode: 'cent',
|
||||
},
|
||||
{ quote },
|
||||
);
|
||||
return {
|
||||
...(single.surplus_mode ? { surplus_mode: single.surplus_mode, surplus_memo: single.surplus_memo } : {}),
|
||||
...(single.old_source
|
||||
? { old_source: single.old_source, deposit_id: single.deposit_id, deposit_weight: single.deposit_weight }
|
||||
: {}),
|
||||
old_lines: single.old_lines,
|
||||
old_pocket: single.old_pocket,
|
||||
...(single.old_stock_count == null ? {} : { old_stock_count: single.old_stock_count }),
|
||||
buy_rate: single.buy_rate,
|
||||
...(single.buy_total == null ? {} : { buy_total: single.buy_total }),
|
||||
exchange: single.exchange,
|
||||
};
|
||||
});
|
||||
const first = recoveryInput(
|
||||
{ ...draft, independent_products: false, extra_products: [], discount: '0', rounding_mode: 'cent' },
|
||||
{ quote: true },
|
||||
),
|
||||
input = {
|
||||
...first,
|
||||
old_lines: items.flatMap(row => row.old_lines),
|
||||
verified: !quote && draft.verified === true,
|
||||
exchange: {
|
||||
items,
|
||||
charges: first.exchange.charges,
|
||||
fee_items: first.exchange.fee_items,
|
||||
discount: draft.discount || '0',
|
||||
rounding_mode: draft.rounding_mode || 'yuan',
|
||||
},
|
||||
};
|
||||
delete input.old_source;
|
||||
delete input.deposit_id;
|
||||
delete input.deposit_weight;
|
||||
delete input.surplus_mode;
|
||||
delete input.surplus_memo;
|
||||
const q = recoveryCalculate(input);
|
||||
input.payment_account =
|
||||
q.netSettlement > 0
|
||||
? draft.payment_method === '信用卡'
|
||||
? '麦麦信用卡'
|
||||
: (draft.payment_recipient || context.memberAccountPrefix(draft.member)) + (draft.payment_method || '微信')
|
||||
: context.memberAccountPrefix(draft.payer || draft.member) + (draft.payout_method || '微信');
|
||||
return input;
|
||||
}
|
||||
|
||||
function recoveryInputShape(input) {
|
||||
return (
|
||||
input &&
|
||||
Object.hasOwn(recoveryModeNames, input.mode) &&
|
||||
context.validOrderDate(input.date) &&
|
||||
typeof input.customer === 'string' &&
|
||||
typeof input.salesperson === 'string' &&
|
||||
context.teamMemberKeys().includes(input.member) &&
|
||||
Array.isArray(input.old_lines) &&
|
||||
input.old_lines.length > 0 &&
|
||||
input.old_lines.every(
|
||||
row =>
|
||||
row && ['name', 'incoming_weight', 'melted_weight', 'purity'].every(key => typeof row[key] === 'string'),
|
||||
) &&
|
||||
(input.mode === 'direct' ||
|
||||
(input.exchange && Array.isArray(input.exchange.charges) && Array.isArray(input.exchange.fee_items)))
|
||||
);
|
||||
}
|
||||
|
||||
function validateRecoveryEditDetail(data, id) {
|
||||
if (
|
||||
!data ||
|
||||
data.id !== id ||
|
||||
data.record?.id !== id ||
|
||||
!Number.isSafeInteger(data.revision) ||
|
||||
data.revision < 1 ||
|
||||
!['active', 'cancelled'].includes(data.status) ||
|
||||
!recoveryInputShape(data.inputs) ||
|
||||
!data.permissions ||
|
||||
!['canEdit', 'canCancel', 'canDirect', 'requiresApproval'].every(
|
||||
key => typeof data.permissions[key] === 'boolean',
|
||||
) ||
|
||||
!Array.isArray(data.blockedUsages) ||
|
||||
!Array.isArray(data.history) ||
|
||||
(context.state.user.role !== 'owner' && data.inputs.member !== context.currentMember())
|
||||
)
|
||||
throw new Error('回收更正资料未完整返回或不属于当前成员,请重新读取。');
|
||||
if (data.record.member !== data.inputs.member || data.record.mode !== data.inputs.mode)
|
||||
throw new Error('回收记录身份与修改资料不一致。');
|
||||
if (data.pending && validateRecoveryChangeRequest(data.pending).recoveryId !== id)
|
||||
throw new Error('回收申请不属于当前记录。');
|
||||
if (data.history.some(row => validateRecoveryChangeRequest(row).recoveryId !== id))
|
||||
throw new Error('回收更正历史不属于当前记录。');
|
||||
return data;
|
||||
}
|
||||
|
||||
function validateRecoveryChangeRequest(request) {
|
||||
if (
|
||||
!request ||
|
||||
typeof request.id !== 'string' ||
|
||||
!request.id ||
|
||||
typeof request.recoveryId !== 'string' ||
|
||||
!Number.isSafeInteger(request.revision) ||
|
||||
request.revision < 1 ||
|
||||
!Number.isSafeInteger(request.recoveryRevision) ||
|
||||
request.recoveryRevision < 1 ||
|
||||
!['update', 'cancel'].includes(request.action) ||
|
||||
!['pending', 'approved', 'rejected'].includes(request.status) ||
|
||||
!recoveryInputShape(request.before) ||
|
||||
(request.action === 'update' && !recoveryInputShape(request.after)) ||
|
||||
(request.action === 'cancel' && request.after !== null) ||
|
||||
typeof request.canApprove !== 'boolean' ||
|
||||
!request.summary ||
|
||||
request.member !== request.before.member ||
|
||||
(request.after && (request.after.member !== request.member || request.after.mode !== request.before.mode)) ||
|
||||
(context.state.user.role !== 'owner' && request.member !== context.currentMember())
|
||||
)
|
||||
throw new Error('回收更正申请未完整返回或不属于当前成员,请重新读取。');
|
||||
return request;
|
||||
}
|
||||
|
||||
function recoveryEditDraft(input) {
|
||||
if (input.exchange?.items) {
|
||||
const rows = input.exchange.items.map(row => recoveryEditDraft({ ...input, ...row, exchange: row.exchange })),
|
||||
first = rows[0],
|
||||
x = input.exchange;
|
||||
return {
|
||||
...first,
|
||||
independent_products: rows.length > 1,
|
||||
extra_products: rows.slice(1),
|
||||
charges: x.charges,
|
||||
charge_name: x.charges[0]?.name || '其他收费',
|
||||
charge_amount: x.charges[0]?.amount || '0',
|
||||
fee_items: x.fee_items,
|
||||
fee_note: x.fee_items[0]?.note || '其他费用',
|
||||
fee_amount: x.fee_items[0]?.amount || '0',
|
||||
fee_payer: x.fee_items[0]?.payer || input.member,
|
||||
discount: x.discount,
|
||||
rounding_mode: x.rounding_mode,
|
||||
};
|
||||
}
|
||||
const first = input.old_lines[0],
|
||||
x = input.exchange || {},
|
||||
charge = x.charges?.[0],
|
||||
fee = x.fee_items?.[0],
|
||||
account = input.payment_account || '',
|
||||
identity = context.accountIdentity(account),
|
||||
recipient = identity ? context.memberAccountPrefix(identity.member) : context.memberAccountPrefix(input.member),
|
||||
method = identity?.channel || '微信';
|
||||
return {
|
||||
...recoveryDefaults(input.mode),
|
||||
mode: input.mode,
|
||||
surplus_mode: input.surplus_mode || 'buy',
|
||||
surplus_memo: input.surplus_memo || '',
|
||||
old_source: input.old_source || 'incoming',
|
||||
deposit_id: input.deposit_id || '',
|
||||
deposit_weight: input.deposit_weight || '',
|
||||
date: input.date,
|
||||
customer: input.customer,
|
||||
salesperson: input.salesperson,
|
||||
member: input.member,
|
||||
note: input.note || '',
|
||||
old_pocket: input.old_pocket ?? '回收旧料',
|
||||
old_stock_count: input.old_stock_count ?? '',
|
||||
old_name: first.name,
|
||||
incoming_weight: first.incoming_weight,
|
||||
melted_weight: first.melted_weight,
|
||||
purity: first.purity,
|
||||
old_lines: JSON.parse(JSON.stringify(input.old_lines)),
|
||||
buy_rate: input.buy_rate,
|
||||
buy_total: input.buy_total ?? '',
|
||||
buy_total_manual: Object.hasOwn(input, 'buy_total'),
|
||||
melted_manual: true,
|
||||
depreciation_manual: Object.hasOwn(x, 'depreciation_weight'),
|
||||
payer: input.payer,
|
||||
payment_method: method,
|
||||
payment_recipient: recipient,
|
||||
payout_method: method === '信用卡' ? '微信' : method,
|
||||
new_name: x.name || '足金999',
|
||||
new_quantity: x.quantity || '',
|
||||
pocket: x.pocket ?? context.state.pockets[0] ?? '',
|
||||
stockCount: x.stockCount ?? '',
|
||||
gold_price: x.gold_price || '0',
|
||||
labor_mode: x.labor_mode || 'gram',
|
||||
labor_rate: x.labor_rate || '0',
|
||||
depreciation_weight: x.depreciation_weight ?? '',
|
||||
depreciation_rate: x.depreciation_rate || '0',
|
||||
charge_name: charge?.name || '其他收费',
|
||||
charge_amount: charge?.amount || '0',
|
||||
charges: JSON.parse(JSON.stringify(x.charges || [])),
|
||||
discount: x.discount || '0',
|
||||
rounding_mode: x.rounding_mode || 'cent',
|
||||
material_source: x.cost_material?.mode === 'pool' ? 'pool' : 'manual',
|
||||
material_pool_id: x.cost_material?.poolId || input.date,
|
||||
material_rate: x.cost_material?.rate || '',
|
||||
material_payer: x.cost_material_payer || input.member,
|
||||
cost_labor_mode: x.cost_labor?.mode || 'total',
|
||||
cost_labor_value: x.cost_labor?.mode === 'gram' ? x.cost_labor.rate : (x.cost_labor?.amount ?? ''),
|
||||
cost_payer: x.cost_payer || input.member,
|
||||
labor_payer: x.cost_labor_payer || x.cost_payer || input.member,
|
||||
fee_note: fee?.note || '其他费用',
|
||||
fee_amount: fee?.amount || '0',
|
||||
fee_payer: fee?.payer || input.member,
|
||||
fee_items: JSON.parse(JSON.stringify(x.fee_items || [])),
|
||||
...(x.products
|
||||
? { ...recoveryProductDraft(x.products[0]), extra_products: x.products.slice(1).map(recoveryProductDraft) }
|
||||
: {}),
|
||||
verified: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
defaults: recoveryDefaults,
|
||||
forEdit: recoveryEditDraft,
|
||||
sharedDraft: recoverySharedOldDraft,
|
||||
input: recoveryInput,
|
||||
calculate: recoveryCalculate,
|
||||
validate: validateRecoveryInput,
|
||||
newWeight: recoveryNewWeight,
|
||||
units: recoveryUnits,
|
||||
multiply: recoveryMul,
|
||||
checkEdit: validateRecoveryEditDetail,
|
||||
checkRequest: validateRecoveryChangeRequest,
|
||||
};
|
||||
}
|
||||
const api = { createModel, recoveryModeNames, recoveryProductFields, customerMaterialOldLines };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.RecoveryRules = api;
|
||||
})(typeof globalThis === 'object' ? globalThis : this);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,34 +12,7 @@ const teamFundsKinds = {
|
||||
reimbursement: '已批报销',
|
||||
};
|
||||
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;
|
||||
return currentReportRules().validateTeamFunds(report);
|
||||
}
|
||||
function teamSignedAmount(pair, value) {
|
||||
if (!Number.isSafeInteger(value)) return '未提供';
|
||||
|
||||
Reference in new issue
Block a user