将账本业务页面、表单与审批迁移到 React,并加入旧版对照验收
This commit is contained in:
1 parent
f1a4e69f0d
commit
00dd683116
107 files changed
+31755
-191
No files matched your search
@@ -0,0 +1,708 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Calc, Model } from '../../shared';
|
||||
import { Button, Choice, Dialog, Field } from '../Settings/controls';
|
||||
import { errorText } from '../Settings/settingsModel';
|
||||
|
||||
const draftsByClient = new WeakMap();
|
||||
function draftsFor(client, user) {
|
||||
const current = draftsByClient.get(client);
|
||||
if (current?.user === user) return current;
|
||||
const drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
||||
draftsByClient.set(client, drafts);
|
||||
return drafts;
|
||||
}
|
||||
function newItem(team) {
|
||||
return {
|
||||
name: '',
|
||||
amount: '',
|
||||
...(team ? { member: 'owner', sourceType: 'independent', sourceKey: crypto.randomUUID() } : {}),
|
||||
};
|
||||
}
|
||||
function PendingList({ client, view, close, openDate }) {
|
||||
const [query, setQuery] = useState({ offset: 0 }),
|
||||
[result, setResult] = useState(null);
|
||||
const validate = useRef(view.validateDailyReimbursements);
|
||||
validate.current = view.validateDailyReimbursements;
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
.api(
|
||||
'/api/reimbursements?' + new URLSearchParams({ status: 'pending', limit: '50', offset: String(query.offset) }),
|
||||
)
|
||||
.then(data => {
|
||||
const list = validate.current(data);
|
||||
if (current) setResult({ query, list });
|
||||
})
|
||||
.catch(error => {
|
||||
if (current) setResult({ query, error: errorText(error) });
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [client, query]);
|
||||
const list = result?.query === query ? result.list : null,
|
||||
error = result?.query === query ? result.error : '';
|
||||
return (
|
||||
<Dialog id="daily-reimbursements-dialog" close={close}>
|
||||
<Button className="dialog-close" action="reimbursement-close-list" aria-label="关闭待复核报销单" onClick={close}>
|
||||
×
|
||||
</Button>
|
||||
<div id="daily-reimbursements-list" aria-live="polite">
|
||||
{error ? (
|
||||
<div className="error">
|
||||
{error}{' '}
|
||||
<Button action="reimbursement-list-retry" onClick={() => setQuery({ ...query })}>
|
||||
重新读取
|
||||
</Button>
|
||||
</div>
|
||||
) : !list ? (
|
||||
<p className="small muted" role="status">
|
||||
正在读取所有日期的待复核报销单…
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<h2>所有日期待复核报销单({list.counts.pending})</h2>
|
||||
<p className="small muted">点击原报销日期查看并复核;批准后回到该日期的应转合计。</p>
|
||||
<div className="table-wrap">
|
||||
<table className="daily-reimbursements-global-table" aria-label="所有日期待复核报销单">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>报销日期</th>
|
||||
<th>提交人/项目</th>
|
||||
<th className="number">合计</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{list.requests.length ? (
|
||||
list.requests.map(row => (
|
||||
<tr key={row.id}>
|
||||
<td>{row.date}</td>
|
||||
<td>
|
||||
{row.requester_name}
|
||||
<div className="small muted">{row.items.map(i => i.name).join('、')}</div>
|
||||
</td>
|
||||
<td className="number">¥{Model.yuan(row.total)}</td>
|
||||
<td>
|
||||
<Button
|
||||
action="reimbursement-open-date"
|
||||
data-date={row.date}
|
||||
data-id={row.id}
|
||||
onClick={() => openDate(row)}
|
||||
>
|
||||
{row.canApprove ? '查看并复核' : '查看原日期'}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={4} className="muted">
|
||||
目前没有待复核的报销单。
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="form-actions">
|
||||
<span className="small muted">
|
||||
共 {list.total} 张 · 当前 {list.offset + 1}~{Math.min(list.offset + list.requests.length, list.total)}
|
||||
</span>
|
||||
<div className="actions">
|
||||
<Button
|
||||
action="reimbursement-list-page"
|
||||
data-offset={Math.max(0, list.offset - list.limit)}
|
||||
disabled={list.offset === 0}
|
||||
onClick={() => setQuery({ offset: Math.max(0, list.offset - list.limit) })}
|
||||
>
|
||||
上一页
|
||||
</Button>
|
||||
<Button
|
||||
action="reimbursement-list-page"
|
||||
data-offset={list.offset + list.limit}
|
||||
disabled={!list.hasMore}
|
||||
onClick={() => setQuery({ offset: list.offset + list.limit })}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }) {
|
||||
const cache = draftsFor(client, state.user.id),
|
||||
key = [state.user.id, query.from, query.date, query.month].join('|');
|
||||
const [, setTick] = useState(0),
|
||||
[list, setList] = useState(false),
|
||||
[error, setError] = useState(null);
|
||||
const redraw = () => setTick(v => v + 1);
|
||||
const team = view.teamMode(),
|
||||
owner = state.user.role === 'owner',
|
||||
month = query.month || data?.readOnly;
|
||||
const blocked = client.busy || !!client.pending() || !data;
|
||||
const formKey = cache.editors.get(key),
|
||||
draft = cache.forms.get(formKey),
|
||||
review = cache.reviews.get(key);
|
||||
const row = data?.reimbursements.find(r => r.id === review?.id),
|
||||
active = state.user.member || view.currentMember();
|
||||
const memberOptions = view.teamMemberOptions(),
|
||||
memberName = id => (state.members || []).find(m => m.member === id)?.label || id;
|
||||
const period = query.month ? query.from + ' 至 ' + query.date : query.date;
|
||||
const currentView = useRef(key);
|
||||
currentView.current = key;
|
||||
const out = cache.outlays.get(key);
|
||||
useEffect(() => {
|
||||
if (!data) return;
|
||||
const review = cache.reviews.get(key);
|
||||
if (review) review.verified = false;
|
||||
if (!data.team && !query.month) {
|
||||
const rev = data.confirmation?.revision || 0,
|
||||
src = data.sources.revision;
|
||||
const prior = cache.outlays.get(key);
|
||||
if (!prior)
|
||||
cache.outlays.set(key, {
|
||||
amount: ((data.confirmation?.amount ?? Math.max(0, data.sources.total)) / 100).toFixed(2),
|
||||
note: data.confirmation?.note || '',
|
||||
verified: false,
|
||||
editing: !data.ready,
|
||||
revision: rev,
|
||||
sourceRevision: src,
|
||||
});
|
||||
else {
|
||||
prior.verified = false;
|
||||
if (data.confirmation?.stale || prior.revision !== rev || prior.sourceRevision !== src) prior.editing = true;
|
||||
prior.revision = rev;
|
||||
prior.sourceRevision = src;
|
||||
}
|
||||
}
|
||||
if (query.reviewId && owner) {
|
||||
const item = data.reimbursements.find(r => r.id === query.reviewId && r.canApprove);
|
||||
if (item)
|
||||
cache.reviews.set(key, { id: item.id, revision: item.revision, kind: 'approve', note: '', verified: false });
|
||||
}
|
||||
redraw();
|
||||
}, [data, key, cache, owner, query.month, query.reviewId]);
|
||||
function action({ action, id, date }) {
|
||||
if (action === 'daily-funds-open-date') {
|
||||
changeDate(date);
|
||||
return;
|
||||
}
|
||||
if (action === 'reimbursement-open-list') {
|
||||
setList(true);
|
||||
return;
|
||||
}
|
||||
if (!data || month || blocked) return;
|
||||
const record = data.reimbursements.find(r => r.id === id);
|
||||
setError(null);
|
||||
if (action === 'reimbursement-new' || action === 'reimbursement-edit') {
|
||||
if (action === 'reimbursement-edit' && (!record?.canEdit || record.status === 'approved')) return;
|
||||
const idKey = record?.id || 'new';
|
||||
if (!cache.forms.has(idKey))
|
||||
cache.forms.set(
|
||||
idKey,
|
||||
record
|
||||
? {
|
||||
id: record.id,
|
||||
revision: record.revision,
|
||||
date: record.date,
|
||||
items: record.items.map(i => ({ ...i, amount: (i.amount / 100).toFixed(2) })),
|
||||
payer: record.payer,
|
||||
note: record.note || '',
|
||||
}
|
||||
: { id: '', date: state.today, items: [newItem(team)], payer: active, note: '' },
|
||||
);
|
||||
cache.editors.set(key, idKey);
|
||||
}
|
||||
if (action === 'reimbursement-close') cache.editors.delete(key);
|
||||
if (action === 'reimbursement-review-close') cache.reviews.delete(key);
|
||||
if (action === 'reimbursement-approve' || action === 'reimbursement-reject') {
|
||||
if (!owner || !record?.canApprove || record.status !== 'pending') return;
|
||||
cache.reviews.set(key, {
|
||||
id,
|
||||
revision: record.revision,
|
||||
kind: action === 'reimbursement-approve' ? 'approve' : 'reject',
|
||||
note: '',
|
||||
verified: false,
|
||||
});
|
||||
}
|
||||
if (out && action === 'daily-outlay-edit') {
|
||||
out.editing = true;
|
||||
out.verified = false;
|
||||
}
|
||||
if (out && action === 'daily-outlay-close') out.editing = false;
|
||||
redraw();
|
||||
}
|
||||
useEffect(() => {
|
||||
actionRef.current = action;
|
||||
return () => {
|
||||
actionRef.current = null;
|
||||
};
|
||||
});
|
||||
function set(obj, field, value) {
|
||||
obj[field] = value;
|
||||
redraw();
|
||||
}
|
||||
async function submit(event, kind) {
|
||||
event.preventDefault();
|
||||
if (blocked || month) return;
|
||||
let url, input, notice;
|
||||
try {
|
||||
if (kind === 'outlay') {
|
||||
if (!owner || !out) throw new Error('完整支出由店主确认。');
|
||||
const amount = out.amount.trim();
|
||||
Calc.cents(amount, '完整对外支出');
|
||||
if (!out.verified) throw new Error('请核对当天完整支出并勾选确认,0 元也需要确认。');
|
||||
url = '/api/daily-funds/confirm';
|
||||
input = {
|
||||
date: query.date,
|
||||
amount,
|
||||
revision: out.revision,
|
||||
sourceRevision: out.sourceRevision,
|
||||
note: out.note.trim(),
|
||||
verified: true,
|
||||
};
|
||||
notice = '当天完整支出已确认';
|
||||
} else if (kind === 'draft') {
|
||||
if (!draft || !view.validOrderDate(draft.date) || draft.date > state.today)
|
||||
throw new Error('报销日期请选择今天或之前的有效日期。');
|
||||
if (!draft.items.length || draft.items.length > 60) throw new Error('每张报销单需要 1~60 个项目。');
|
||||
const items = draft.items.map(item => {
|
||||
const name = item.name.trim(),
|
||||
amount = item.amount.trim();
|
||||
if (!name || name.length > 100) throw new Error('每项报销名称请填写 1~100 字。');
|
||||
if (Calc.cents(amount, '报销金额') <= 0) throw new Error('每项报销金额必须大于 0。');
|
||||
return {
|
||||
name,
|
||||
amount,
|
||||
...(team
|
||||
? {
|
||||
...(item.id ? { id: item.id } : {}),
|
||||
member: item.member || 'owner',
|
||||
sourceType: 'independent',
|
||||
sourceKey: item.sourceKey || crypto.randomUUID(),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
if (draft.note.length > 300) throw new Error('备注最多 300 字。');
|
||||
if (draft.id) {
|
||||
const r = data.reimbursements.find(r => r.id === draft.id);
|
||||
if (!r?.canEdit || r.status === 'approved' || r.revision !== draft.revision)
|
||||
throw new Error('报销单已变化或已批准,请重新读取后核对。');
|
||||
}
|
||||
url = draft.id ? '/api/reimbursements/' + encodeURIComponent(draft.id) + '/update' : '/api/reimbursements';
|
||||
input = {
|
||||
...(team ? { payer: owner ? draft.payer || active : active } : {}),
|
||||
date: draft.date,
|
||||
items,
|
||||
note: draft.note.trim(),
|
||||
...(draft.id ? { revision: draft.revision } : {}),
|
||||
};
|
||||
notice = '报销单已提交,等待店主复核';
|
||||
} else {
|
||||
if (!owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
|
||||
throw new Error('报销单已变化,请重新读取后复核。');
|
||||
const note = review.note.trim();
|
||||
if (note.length > 300 || (review.kind === 'reject' && !note))
|
||||
throw new Error(review.kind === 'reject' ? '请填写 1~300 字的驳回原因。' : '复核备注最多 300 字。');
|
||||
if (review.kind === 'approve' && !review.verified) throw new Error('请核对报销项目和金额,并勾选复核确认。');
|
||||
url = '/api/reimbursements/' + encodeURIComponent(row.id) + '/' + review.kind;
|
||||
input = { revision: review.revision, note, ...(review.kind === 'approve' ? { verified: true } : {}) };
|
||||
notice =
|
||||
review.kind === 'reject'
|
||||
? '报销已驳回,原原因保留'
|
||||
: team
|
||||
? '报销已批准,成员往来已更新'
|
||||
: '报销已批准,已计入报销日期的应转合计';
|
||||
}
|
||||
setError(null);
|
||||
const result = await client.mutate(url, input);
|
||||
if (kind === 'draft') {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
if (kind === 'outlay') {
|
||||
out.editing = false;
|
||||
out.verified = false;
|
||||
out.revision = result.confirmation.revision;
|
||||
out.sourceRevision = result.confirmation.sourceRevision;
|
||||
}
|
||||
reload();
|
||||
const date = result.reimbursement?.date || result.date || input.date;
|
||||
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
|
||||
} catch (err) {
|
||||
if (currentView.current !== key) return;
|
||||
setError({ kind, text: errorText(err), conflict: err.status === 409 });
|
||||
notify(errorText(err), true);
|
||||
if (err.status === 409) {
|
||||
if (review) review.verified = false;
|
||||
reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
const errBox = (id, kind) => (
|
||||
<div id={id} aria-live="polite">
|
||||
{error?.kind === kind && (
|
||||
<div className="error">
|
||||
{error.text}
|
||||
{client.pending() ? (
|
||||
<Button
|
||||
action="retry"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await client.retryPending();
|
||||
if (kind === 'draft') {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
setError(null);
|
||||
reload();
|
||||
} catch (err) {
|
||||
notify(errorText(err), true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
恢复原操作
|
||||
</Button>
|
||||
) : error.conflict ? (
|
||||
' 请重新核对后再提交。'
|
||||
) : (
|
||||
<Button action="daily-funds-retry" onClick={reload}>
|
||||
重新读取资料
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
const btn = (text, name, primary = false) => (
|
||||
<Button
|
||||
className={primary ? 'primary' : 'quiet'}
|
||||
action={name}
|
||||
disabled={name.endsWith('close') ? client.busy : blocked}
|
||||
onClick={() => action({ action: name })}
|
||||
>
|
||||
{text}
|
||||
</Button>
|
||||
);
|
||||
const total = draft ? view.reimbursementDraftTotal(draft.items) : null;
|
||||
return (
|
||||
<>
|
||||
{!team && (
|
||||
<section className="panel daily-transfer" aria-label="每天转账核对">
|
||||
<div className="panel-title">
|
||||
<h2>每天转账核对</h2>
|
||||
<span className="small muted">
|
||||
{period}
|
||||
{month ? ' · 只读汇总' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<p className="small muted">
|
||||
普通收退款按开单日期归集,锁价收退款按实际发生日期归集。报销与支出确认只用于转账核对。
|
||||
</p>
|
||||
{data && (
|
||||
<>
|
||||
{view.renderDailyTransferResult(data, month)}
|
||||
{month ? view.renderDailyFundsMonth(data) : view.renderDailyFundsSources(data)}
|
||||
</>
|
||||
)}
|
||||
{data && !month && data.confirmation && !data.confirmation.stale && (
|
||||
<div className="daily-confirmed-note small muted">
|
||||
{data.confirmation.actor || memberName('owner')}已确认 ¥{Model.yuan(data.confirmation.amount)}
|
||||
{owner && btn('修改支出确认', 'daily-outlay-edit')}
|
||||
</div>
|
||||
)}
|
||||
{owner && !month && out?.editing && (
|
||||
<form
|
||||
id="daily-outlay-form"
|
||||
className="daily-outlay-form"
|
||||
data-view-key={key}
|
||||
onSubmit={e => submit(e, 'outlay')}
|
||||
>
|
||||
<div className="daily-outlay-inputs">
|
||||
<Field
|
||||
label={memberName('owner') + '当天完整实际对外支出(元)'}
|
||||
name="amount"
|
||||
value={out.amount}
|
||||
onChange={e => {
|
||||
out.verified = false;
|
||||
set(out, 'amount', e.target.value);
|
||||
}}
|
||||
type="number"
|
||||
min={0}
|
||||
step="0.01"
|
||||
required
|
||||
inputMode="decimal"
|
||||
disabled={blocked}
|
||||
/>
|
||||
<Field
|
||||
label="确认备注(选填)"
|
||||
name="note"
|
||||
value={out.note}
|
||||
onChange={e => {
|
||||
out.verified = false;
|
||||
set(out, 'note', e.target.value);
|
||||
}}
|
||||
maxLength={300}
|
||||
disabled={blocked}
|
||||
/>
|
||||
</div>
|
||||
<p className="small muted">
|
||||
含未售现货采购及当天实际对外付款。不含客户退款(已从净收款扣除)、双方互转或报销转账。之前已经支付的货品,后续卖出不算一笔新支出。
|
||||
</p>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="verified"
|
||||
checked={out.verified}
|
||||
onChange={e => set(out, 'verified', e.target.checked)}
|
||||
required
|
||||
disabled={blocked}
|
||||
/>
|
||||
已核对完整支出;没有发生的,明确按 0 元确认。
|
||||
</label>
|
||||
{errBox('daily-outlay-error', 'outlay')}
|
||||
<div className="actions">
|
||||
<button type="submit" className="primary" disabled={blocked}>
|
||||
确认当天支出
|
||||
</button>
|
||||
{data?.ready && btn('收起', 'daily-outlay-close')}
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{!month && !owner && <p className="small muted">当天完整对外支出由{memberName('owner')}确认。</p>}
|
||||
</section>
|
||||
)}
|
||||
<section className="panel daily-reimbursements" aria-label="每日报销单">
|
||||
<div className="panel-title">
|
||||
<h2>每日报销单</h2>
|
||||
{team && (
|
||||
<span className="small muted">
|
||||
{period}
|
||||
{month ? ' · 只读汇总' : ''}
|
||||
</span>
|
||||
)}
|
||||
<div className="actions">
|
||||
{data && (
|
||||
<Button action="reimbursement-open-list" onClick={() => setList(true)}>
|
||||
待复核({data.pendingCount})
|
||||
</Button>
|
||||
)}
|
||||
{data && !month && btn('新增报销单', 'reimbursement-new', true)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="small muted">
|
||||
{team
|
||||
? '每项单独指定承担人;已批准报销只读。请勿将已经计入订单、购料或其他付款记录的支出再次提交。'
|
||||
: '按报销日期归集。待复核或被驳回的单据可修改后再提交;已批准单据只读,不能直接修改。'}
|
||||
</p>
|
||||
{!month && draft && (
|
||||
<form
|
||||
id="reimbursement-form"
|
||||
className="reimbursement-form"
|
||||
data-view-key={key}
|
||||
data-draft-key={formKey}
|
||||
onSubmit={e => submit(e, 'draft')}
|
||||
>
|
||||
<div className="panel-title">
|
||||
<h3>{draft.id ? '修改报销单' : '新增报销单'}</h3>
|
||||
{btn('收起', 'reimbursement-close')}
|
||||
</div>
|
||||
<Field
|
||||
label="报销日期"
|
||||
name="date"
|
||||
type="date"
|
||||
required
|
||||
max={state.today}
|
||||
value={draft.date}
|
||||
onChange={e => set(draft, 'date', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
{team &&
|
||||
(owner ? (
|
||||
<Choice
|
||||
label="实际付款人"
|
||||
name="reimbursementPayer"
|
||||
options={memberOptions}
|
||||
value={draft.payer || active}
|
||||
onChange={e => set(draft, 'payer', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
) : (
|
||||
<p className="small muted">实际付款人:{memberName(active)}</p>
|
||||
))}
|
||||
<div className="reimbursement-item-labels">
|
||||
<span>报销项目</span>
|
||||
<span>金额(元)</span>
|
||||
<span />
|
||||
</div>
|
||||
<div id="reimbursement-items">
|
||||
{draft.items.map((item, i) => (
|
||||
<div className="reimbursement-item-row" data-index={i} key={item.id || item.sourceKey || i}>
|
||||
<label>
|
||||
<span className="sr-only">项目 {i + 1}</span>
|
||||
<input
|
||||
name="itemName"
|
||||
value={item.name}
|
||||
required
|
||||
maxLength={100}
|
||||
placeholder="例如:进货工费、快递"
|
||||
aria-label={'报销项目 ' + (i + 1)}
|
||||
onChange={e => set(item, 'name', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span className="sr-only">金额 {i + 1}</span>
|
||||
<input
|
||||
name="itemAmount"
|
||||
value={item.amount}
|
||||
type="number"
|
||||
min="0.01"
|
||||
step="0.01"
|
||||
inputMode="decimal"
|
||||
required
|
||||
aria-label={'报销金额 ' + (i + 1)}
|
||||
onChange={e => set(item, 'amount', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
</label>
|
||||
{team && (
|
||||
<Choice
|
||||
label="由谁承担"
|
||||
name="itemMember"
|
||||
options={memberOptions}
|
||||
value={item.member || 'owner'}
|
||||
onChange={e => set(item, 'member', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
action="reimbursement-remove-item"
|
||||
className="quiet"
|
||||
data-index={i}
|
||||
disabled={blocked || draft.items.length <= 1}
|
||||
onClick={() => {
|
||||
draft.items.splice(i, 1);
|
||||
redraw();
|
||||
}}
|
||||
>
|
||||
移除
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button
|
||||
action="reimbursement-add-item"
|
||||
disabled={blocked}
|
||||
onClick={() => {
|
||||
if (draft.items.length >= 60) {
|
||||
setError({ kind: 'draft', text: '每张报销单最多 60 个项目。' });
|
||||
return;
|
||||
}
|
||||
draft.items.push(newItem(team));
|
||||
redraw();
|
||||
}}
|
||||
>
|
||||
+ 添加项目
|
||||
</Button>
|
||||
<p className="reimbursement-edit-total" id="reimbursement-edit-total">
|
||||
{total.complete ? total.formula + ' = ' : '已填合计 '}
|
||||
<strong>¥{Model.yuan(total.total)}</strong>
|
||||
</p>
|
||||
<Field
|
||||
label="备注(选填)"
|
||||
name="note"
|
||||
maxLength={300}
|
||||
value={draft.note}
|
||||
onChange={e => set(draft, 'note', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
<p className="small muted">
|
||||
{team
|
||||
? '提交实际付款项目,逐项确认承担人。' +
|
||||
memberName('owner') +
|
||||
'批准后只按付款人与承担人的差额形成成员往来;这次提交不会再次记录付款。'
|
||||
: '报销单通过店主复核后,才计入报销日期的应转合计;这次提交不扣当天利润。'}
|
||||
</p>
|
||||
{errBox('reimbursement-error', 'draft')}
|
||||
<div className="actions">
|
||||
<button className="primary" type="submit" disabled={blocked}>
|
||||
{draft.id ? '保存并重新提交复核' : '提交店主复核'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{!month && review && row && (
|
||||
<form
|
||||
id="reimbursement-review-form"
|
||||
className="reimbursement-review-form"
|
||||
data-view-key={key}
|
||||
onSubmit={e => submit(e, 'review')}
|
||||
>
|
||||
<div className="panel-title">
|
||||
<h3>{review.kind === 'approve' ? '复核报销单' : '驳回报销单'}</h3>
|
||||
{btn('收起', 'reimbursement-review-close')}
|
||||
</div>
|
||||
<p>
|
||||
{row.date} · {row.requester_name}提交 · 合计 <strong>¥{Model.yuan(row.total)}</strong>
|
||||
</p>
|
||||
{view.renderReimbursementItems(row)}
|
||||
<label>
|
||||
{review.kind === 'reject' ? '驳回原因' : '复核备注(选填)'}
|
||||
<textarea
|
||||
name="note"
|
||||
maxLength={300}
|
||||
rows={2}
|
||||
required={review.kind === 'reject'}
|
||||
value={review.note}
|
||||
onChange={e => set(review, 'note', e.target.value)}
|
||||
disabled={blocked}
|
||||
/>
|
||||
</label>
|
||||
{review.kind === 'approve' && (
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="verified"
|
||||
checked={review.verified}
|
||||
onChange={e => set(review, 'verified', e.target.checked)}
|
||||
required
|
||||
disabled={blocked}
|
||||
/>
|
||||
{team
|
||||
? '已核对实际付款人与每项承担人,同意计入成员往来。'
|
||||
: '已核对项目和金额,同意将 ¥' + Model.yuan(row.total) + ' 计入 ' + row.date + ' 的应转合计。'}
|
||||
</label>
|
||||
)}
|
||||
{errBox('reimbursement-review-error', 'review')}
|
||||
<div className="actions">
|
||||
<button type="submit" className="primary" disabled={blocked}>
|
||||
{review.kind === 'approve' ? '同意报销' : '确认驳回'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{data ? view.renderReimbursementRows(data, month) : <p className="muted">报销资料尚未读到,草稿保留。</p>}
|
||||
</section>
|
||||
{list && (
|
||||
<PendingList
|
||||
client={client}
|
||||
view={view}
|
||||
close={() => setList(false)}
|
||||
openDate={row => {
|
||||
setList(false);
|
||||
changeDate(row.date, owner && row.canApprove ? row.id : undefined);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { JSX } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState, SessionInfo } from '../../shared';
|
||||
export function ReportPage(props: { client: LedgerClient; state: LedgerState; session: SessionInfo }): JSX.Element;
|
||||
export default ReportPage;
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { navigate } from '../../lib/router';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
import { Button, Choice } from '../Settings/controls';
|
||||
import { errorText } from '../Settings/settingsModel';
|
||||
import { reportPresentation } from './presentation';
|
||||
import { Reimbursements } from './Reimbursements';
|
||||
import './report.css';
|
||||
|
||||
const savedQueries = new WeakMap();
|
||||
export function ReportPage({ client, state, session }) {
|
||||
useClientSnapshot(client);
|
||||
const user = state.user.id;
|
||||
const [query, setQuery] = useState(
|
||||
() => savedQueries.get(client)?.get(user) || { date: state.today, month: false, member: '' },
|
||||
);
|
||||
const [version, setVersion] = useState(0),
|
||||
[reply, setReply] = useState(null),
|
||||
[notice, setNotice] = useState(null);
|
||||
const daily = useRef(null),
|
||||
actions = useRef(null);
|
||||
const reload = useCallback(() => setVersion(v => v + 1), []);
|
||||
const dispatch = useCallback(data => actions.current(data), []);
|
||||
const view = reportPresentation({
|
||||
state,
|
||||
session,
|
||||
reportMonth: query.month,
|
||||
reportMember: query.member,
|
||||
onAction: dispatch,
|
||||
});
|
||||
const viewRef = useRef(view);
|
||||
viewRef.current = view;
|
||||
const from = query.month ? query.date.slice(0, 7) + '-01' : query.date;
|
||||
const range = { ...query, from };
|
||||
const ready = reply?.query === query && reply.version === version ? reply : null;
|
||||
const notify = (text, error = false) => setNotice({ text, error });
|
||||
const change = d => {
|
||||
const n = { ...query, reviewId: undefined, ...d };
|
||||
if (!savedQueries.has(client)) savedQueries.set(client, new Map());
|
||||
savedQueries.get(client).set(user, n);
|
||||
setQuery(n);
|
||||
setNotice(null);
|
||||
};
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
async function load() {
|
||||
try {
|
||||
const model = viewRef.current;
|
||||
if (!model.validOrderDate(query.date)) throw new Error('请选择有效的对账日期。');
|
||||
if (query.date > state.today) throw new Error('请选择今天或之前的日期。');
|
||||
const data = await client.api(
|
||||
'/api/report?' +
|
||||
new URLSearchParams({
|
||||
basis: 'orderDate',
|
||||
from,
|
||||
date: query.date,
|
||||
...(state.user.role === 'owner' && query.member ? { member: query.member } : {}),
|
||||
}),
|
||||
);
|
||||
if (!active) return;
|
||||
model.validateReport(data, { from, date: query.date });
|
||||
let fundsError = '';
|
||||
try {
|
||||
model.validateDailyFunds(data.dailyFunds, { ...query, from });
|
||||
} catch (err) {
|
||||
fundsError = errorText(err);
|
||||
}
|
||||
setReply({ data, fundsError, query, version });
|
||||
} catch (err) {
|
||||
if (active)
|
||||
setReply({ error: err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err), query, version });
|
||||
}
|
||||
}
|
||||
void load();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [client, state.today, state.user.role, user, from, query, version]);
|
||||
async function action({ action, id, date }) {
|
||||
try {
|
||||
if (action === 'report-retry' || action === 'daily-funds-retry') {
|
||||
reload();
|
||||
return;
|
||||
}
|
||||
if (action === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(id) });
|
||||
if (action === 'after-sale-edit') return navigate('orders', { search: '?afterSale=' + encodeURIComponent(id) });
|
||||
if (action === 'open-price-lock') return navigate('price-locks', { search: '?lock=' + encodeURIComponent(id) });
|
||||
if (action === 'recovery-open') return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(id) });
|
||||
if (action === 'goto-material-pools')
|
||||
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(id) : '' });
|
||||
if (action === 'recovery-print') {
|
||||
window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
|
||||
notify('客户打印页已打开;若未出现,请允许此网站打开新窗口');
|
||||
return;
|
||||
}
|
||||
if (!ready?.data) throw new Error('对账数据正在读取或已失效,请读取完成后再操作。');
|
||||
if (action === 'close-day') {
|
||||
if (state.user.role !== 'owner' || query.month) return;
|
||||
await client.mutate('/api/close', { date: query.date, basis: 'orderDate' });
|
||||
notify(query.date + ' 对账与库存快照已保存');
|
||||
reload();
|
||||
return;
|
||||
}
|
||||
if (action === 'download-report') {
|
||||
const r = ready.data,
|
||||
text = view.reportDownloadText(r),
|
||||
link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(new Blob(['\ufeff' + text], { type: 'text/plain;charset=utf-8' }));
|
||||
link.download = view.shopBrandName() + '对账-' + (r.from === r.date ? r.date : r.from + '至' + r.date) + '.txt';
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
return;
|
||||
}
|
||||
daily.current?.({ action, id, date });
|
||||
} catch (err) {
|
||||
notify(errorText(err), true);
|
||||
}
|
||||
}
|
||||
actions.current = action;
|
||||
return (
|
||||
<div
|
||||
className="report-page"
|
||||
onKeyDown={e => {
|
||||
if (
|
||||
e.target instanceof HTMLInputElement &&
|
||||
e.target.type === 'number' &&
|
||||
['ArrowUp', 'ArrowDown'].includes(e.key)
|
||||
)
|
||||
e.preventDefault();
|
||||
}}
|
||||
onWheel={e => {
|
||||
if (e.target instanceof HTMLInputElement && e.target.type === 'number' && document.activeElement === e.target)
|
||||
e.target.blur();
|
||||
}}
|
||||
>
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<div className="eyebrow">DAILY CHECK</div>
|
||||
<h1>每日对账</h1>
|
||||
<p className="muted">核对本人或所选成员的所属订单收入、实际支出与收款账户。</p>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<div className="report-controls">
|
||||
{state.user.role === 'owner' && view.teamMode() && (
|
||||
<Choice
|
||||
label="订单归属"
|
||||
id="report-member-filter"
|
||||
value={query.member}
|
||||
onChange={e => change({ member: e.target.value })}
|
||||
options={[['', '全部成员'], ...view.teamMemberOptions(false, { historical: true })]}
|
||||
/>
|
||||
)}
|
||||
<label>
|
||||
对账日期
|
||||
<input
|
||||
type="date"
|
||||
id="report-date"
|
||||
value={query.date}
|
||||
max={state.today}
|
||||
aria-label="对账日期"
|
||||
onChange={e => change({ date: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="check">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="report-month"
|
||||
checked={query.month}
|
||||
onChange={e => change({ month: e.target.checked })}
|
||||
/>
|
||||
汇总当月
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="small muted report-scope">
|
||||
普通订单按开单日期、售后按记录日期筛选。锁价收付按实际发生日期,销售和完整利润在交付日计入;原锁付款不会重复计入交付日支出。
|
||||
</p>
|
||||
<div id="report-content" aria-live="polite" aria-busy={!ready}>
|
||||
{ready?.data ? (
|
||||
view.renderReportContent(ready.data, range)
|
||||
) : (
|
||||
<>
|
||||
<div className="cards report-cards">
|
||||
{['销售净额', '累计实收', '累计实退', '订单净利润'].map(name => (
|
||||
<div className="stat" key={name}>
|
||||
<small>{name}</small>
|
||||
<strong>—</strong>
|
||||
<div className="hint">{ready?.error ? '尚未取得数据' : '正在读取'}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<section className={'panel report-query-message' + (ready?.error ? ' error' : '')}>
|
||||
<p>
|
||||
{ready?.error ||
|
||||
'正在读取' + (from === query.date ? from : from + ' 至 ' + query.date) + '订单与售后的当前结果…'}
|
||||
</p>
|
||||
{ready?.error && (
|
||||
<Button action="report-retry" onClick={reload}>
|
||||
重新读取
|
||||
</Button>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div id="daily-funds-content" aria-live="polite" aria-busy={!ready}>
|
||||
{ready?.data &&
|
||||
(ready.fundsError ? (
|
||||
<div className="error">
|
||||
{ready.fundsError}{' '}
|
||||
<Button action="daily-funds-retry" onClick={reload}>
|
||||
重新读取资料
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Reimbursements
|
||||
client={client}
|
||||
state={state}
|
||||
view={view}
|
||||
data={ready.data.dailyFunds}
|
||||
query={range}
|
||||
actionRef={daily}
|
||||
reload={reload}
|
||||
notify={notify}
|
||||
changeDate={(date, reviewId) => change({ date, month: false, reviewId })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div id="report-daily-profits-content" aria-live="polite">
|
||||
{ready?.data && view.renderReportDailyProfits(ready.data)}
|
||||
</div>
|
||||
{notice && (
|
||||
<p className={'report-notice ' + (notice.error ? 'error' : '')} role={notice.error ? 'alert' : 'status'}>
|
||||
{notice.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default ReportPage;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,224 @@
|
||||
.report-page {
|
||||
min-width: 0;
|
||||
line-height: 1.55;
|
||||
color: #233f32;
|
||||
font-size: 14px;
|
||||
padding-bottom: 30px;
|
||||
}
|
||||
.report-page .panel,
|
||||
.report-page .stat {
|
||||
min-width: 0;
|
||||
background: #fff;
|
||||
border: 1px solid #d9e4df;
|
||||
border-radius: 12px;
|
||||
padding: clamp(14px, 2vw, 24px);
|
||||
margin: 12px 0;
|
||||
}
|
||||
.report-page .report-controls,
|
||||
.report-page .actions,
|
||||
.report-page .form-actions,
|
||||
.report-page .panel-title,
|
||||
.report-page .report-ownership-equation,
|
||||
.report-page .report-business-profit-equation,
|
||||
.report-page .daily-transfer-parts {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.report-page h1,
|
||||
.report-page h2,
|
||||
.report-page h3 {
|
||||
color: #193c2e;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.report-page h1 {
|
||||
font-size: 30px;
|
||||
}
|
||||
.report-page h2 {
|
||||
font-size: 20px;
|
||||
}
|
||||
.report-page h3 {
|
||||
font-size: 16px;
|
||||
}
|
||||
.report-page label {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
.report-page .check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.report-page button,
|
||||
.report-page input:not([type='checkbox']),
|
||||
.report-page select,
|
||||
.report-page textarea {
|
||||
font: inherit;
|
||||
border: 1px solid #b8cbbf;
|
||||
border-radius: 6px;
|
||||
color: inherit;
|
||||
padding: 6px 9px;
|
||||
background: white;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.report-page button {
|
||||
cursor: pointer;
|
||||
}
|
||||
.report-page button.primary {
|
||||
color: white;
|
||||
background: #23583d;
|
||||
}
|
||||
.report-page button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.report-page .muted,
|
||||
.report-page .eyebrow,
|
||||
.report-page .hint {
|
||||
color: #566d61;
|
||||
}
|
||||
.report-page .small,
|
||||
.report-page .hint {
|
||||
font-size: 13px;
|
||||
}
|
||||
.report-page .error,
|
||||
.report-page .danger-text {
|
||||
color: #96332d;
|
||||
}
|
||||
.report-page .stat > strong,
|
||||
.report-page .daily-transfer-parts strong,
|
||||
.report-page .report-recipient-total {
|
||||
display: block;
|
||||
font-size: 21px;
|
||||
}
|
||||
.report-page .cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.report-page .report-recipient-grid,
|
||||
.report-page .report-primary,
|
||||
.report-page .split {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(340px, 100%), 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.report-page details {
|
||||
margin: 8px 0;
|
||||
}
|
||||
.report-page summary {
|
||||
cursor: pointer;
|
||||
color: #234b35;
|
||||
}
|
||||
.report-page p {
|
||||
margin: 6px 0 10px;
|
||||
}
|
||||
.report-page .note,
|
||||
.report-page .badge {
|
||||
background: #edf5f0;
|
||||
border-radius: 6px;
|
||||
padding: 5px 8px;
|
||||
}
|
||||
.report-page .warn {
|
||||
background: #fbefdd;
|
||||
}
|
||||
.report-page .table-wrap {
|
||||
overflow: auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
.report-page table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.report-page th,
|
||||
.report-page td {
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #d9e4df;
|
||||
padding: 7px;
|
||||
vertical-align: top;
|
||||
}
|
||||
.report-page .number {
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.report-page .link-button {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
color: #235c3e;
|
||||
text-align: left;
|
||||
}
|
||||
.report-page .link-button > span,
|
||||
.report-page .link-button > strong {
|
||||
display: block;
|
||||
}
|
||||
.report-page .reimbursement-form,
|
||||
.report-page .reimbursement-review-form,
|
||||
.report-page .daily-outlay-form {
|
||||
padding: 12px 0;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.report-page .reimbursement-item-row,
|
||||
.report-page .reimbursement-item-labels {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr auto;
|
||||
gap: 8px;
|
||||
align-items: end;
|
||||
}
|
||||
.report-page button:focus-visible,
|
||||
.report-page input:focus-visible,
|
||||
.report-page summary:focus-visible {
|
||||
outline: 2px solid #3d7a52;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.report-page .sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.report-page dialog {
|
||||
width: min(900px, calc(100vw - 32px));
|
||||
max-height: 88dvh;
|
||||
overflow: auto;
|
||||
box-sizing: border-box;
|
||||
padding: 20px;
|
||||
border: 1px solid #cbdacf;
|
||||
border-radius: 12px;
|
||||
color: inherit;
|
||||
}
|
||||
.report-page dialog::backdrop {
|
||||
background: #132a1e66;
|
||||
}
|
||||
.report-page .dialog-close {
|
||||
float: right;
|
||||
}
|
||||
.report-page .report-notice {
|
||||
position: fixed;
|
||||
bottom: 16px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
background: #edf5ef;
|
||||
border-radius: 8px;
|
||||
padding: 10px 16px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.report-page .cards {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.report-page .reimbursement-item-row {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
.report-page .report-receipt-table,
|
||||
.report-page .report-order-table,
|
||||
.report-page .report-cost-detail-table {
|
||||
min-width: 600px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,937 @@
|
||||
import { Calc as LedgerCalc } from '../../shared';
|
||||
import { reportValidation } from './validation';
|
||||
export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
function reportDownloadText(r) {
|
||||
if (teamMode() && typeof reportTeamDownloadText === 'function') return reportTeamDownloadText(r);
|
||||
const s = r.summary,
|
||||
receipts = r.receiptsByOrderDate,
|
||||
people = teamDataKeys(r.payerCosts).map(key => r.payerCosts[key]),
|
||||
missing = people.reduce((sum, c) => sum + c.missingCount, 0),
|
||||
pending = people.reduce((sum, c) => sum + c.pendingCount, 0);
|
||||
const costs = people.flatMap(c => [
|
||||
`${c.name}支出成本:货品成本 ${reportCostAmount(c.goods, c.missingCount)};已付费用 ¥${yuan(c.paidFees)}${c.items.some(item => item.kind === 'afterSale') ? '(其中售后 ¥' + yuan(reportAfterSaleAmount(c)) + ')' : ''};支出合计 ${reportCostAmount(c.total, c.missingCount + c.pendingCount)}`,
|
||||
reportPayerHints(c),
|
||||
`${c.name}逐项明细(货品成本为 0 的分项省略,已核实为 0 的费用保留):`,
|
||||
...reportCostItems(c).map(
|
||||
item =>
|
||||
`${item.date} / ${reportCostIdentity(item)} / ${item.name} / ${item.source}${item.calculation ? ' / ' + reportCostFormula(item) : ''} / ${reportCostItemAmount(item)}${item.kind === 'pending' ? '(未计入实际成本与合计)' : ''}`,
|
||||
),
|
||||
'',
|
||||
]);
|
||||
const orders = r.orderRows.map(
|
||||
row =>
|
||||
`${row.date} / ${row.kind === 'afterSale' ? '售后 · ' + row.project + ' / 客户 ' + row.customer + ' / ' + afterSalePayerName(row) + '支付' : row.paper_number || row.number} / ${label[row.status] || row.status} / 销售净额 ${reportRowAmount(row, 'sale')} / 货品成本 ${reportRowAmount(row, 'goods')} / 已付费用 ${reportRowAmount(row, 'paidFees')} / 成本合计 ${reportRowAmount(row, 'totalCost')} / 净利润 ${reportRowAmount(row, 'profit')}${row.costHint ? ' / ' + row.costHint : ''}`,
|
||||
);
|
||||
return [
|
||||
`${shopBrandName()}新账 · ${reportPeriod(r)} 对账报告`,
|
||||
'口径:普通订单按开单日期、售后按记录日期;锁价收付款按实际发生日期,销售与完整利润按交付日期。原锁料费不会重复计入交付日实际支出。',
|
||||
`销售订单:${s.orderCount} 单;售后 ${s.afterSaleCount || 0} 笔;完成 ${s.completedCount} 单;退货 ${s.returnedCount} 单;取消 ${s.cancelledCount} 单;旧草稿 ${s.draftCount} 单(未计金额)`,
|
||||
`销售净额:${reportSummaryAmount(s, 'sale')}`,
|
||||
`累计实收:¥${yuan(receipts.receipt)}`,
|
||||
`累计实退:¥${yuan(receipts.refund)}`,
|
||||
`客户收款净额:¥${yuan(receipts.net)}`,
|
||||
`订单耗用货品成本:${reportCostAmount(r.goods, s.missingCosts)}`,
|
||||
`订单已付费用:¥${yuan(r.expense)}${s.afterSaleCount ? '(其中售后 ¥' + yuan(people.reduce((sum, c) => sum + reportAfterSaleAmount(c), 0)) + ')' : ''}`,
|
||||
`各人实际货品支出:${reportCostAmount(r.outlayGoods ?? r.goods, missing)}`,
|
||||
`各人实际费用支出:¥${yuan(r.outlayExpense ?? r.expense)}`,
|
||||
`各人实际支出合计:${reportCostAmount(r.outlayTotal ?? r.goods + r.expense, missing + pending)}`,
|
||||
`本期净利润${s.unknownProfitCount ? '(已核算部分)' : ''}:${reportSummaryAmount(s, 'profit')}${s.unknownProfitCount ? ';' + s.unknownProfitCount + ' 单利润待补齐' : ''}`,
|
||||
'',
|
||||
...reportDailyProfitsText(r),
|
||||
...reportOwnershipReceiptsText(r),
|
||||
...(typeof dailyFundsDownloadText === 'function' ? dailyFundsDownloadText(r) : []),
|
||||
...reportRecipientReceiptsText(r),
|
||||
'按收款账户核对(普通订单累计收付+同期锁价实际收付)',
|
||||
...reportActiveAccounts(r).map(
|
||||
a =>
|
||||
`${accountDisplayName(a.account)}:实收 ¥${yuan(a.receipt)},实退 ¥${yuan(a.refund)},净额 ¥${yuan(a.net)}`,
|
||||
),
|
||||
'',
|
||||
teamMode() ? '各人支出成本(未入账费用不计合计)' : '双方支出成本(未入账费用不计合计)',
|
||||
...costs,
|
||||
...priceLockActivityText(r.priceLockActivity),
|
||||
...(r.materialPoolActivity?.purchases?.length
|
||||
? [
|
||||
'本期实际购料(已计入各人实际支出,不再加总)',
|
||||
...r.materialPoolActivity.purchases.map(
|
||||
item =>
|
||||
`${item.date} / ${grams(item.mg)}g / ¥${yuan(item.amount)} / ${materialPayerName(item.payer)} / ${item.note || ''}`,
|
||||
),
|
||||
'',
|
||||
]
|
||||
: []),
|
||||
'订单与售后净额明细(订单按开单日期、售后按售后日期)',
|
||||
...orders,
|
||||
'',
|
||||
`${r.date} 账面库存(按所选日及此前流水计算,月汇总仍显示所选日)`,
|
||||
...r.inventory.map(
|
||||
i =>
|
||||
`${pocketLabel(i.pocket)}:${grams(i.mg)}g${i.countUnit === 'pair' || pocketCountsEnabled(i.pocket) ? ' / ' + stockCountText(i.count) : ''}`,
|
||||
),
|
||||
'',
|
||||
'截至现在的全局未结事项(不受日期筛选)',
|
||||
`客户待收款:¥${yuan(r.customerBalance)}`,
|
||||
`订单与剩余料款待结净额:${materialReportMoney(r.settlementDue)}`,
|
||||
...r.unsettled.map(
|
||||
o =>
|
||||
`${o.number}:货款待结 ${materialReportMoney(o.costDue)},利润待结 ${materialReportMoney(o.profitDue)},${teamMemberName('owner')}直收净额 ¥${yuan(o.ownerDirect)},总待结 ${materialReportMoney(o.total)}`,
|
||||
),
|
||||
'',
|
||||
'当前待处理(所有订单,不受日期筛选)',
|
||||
...r.warnings.map(w => `${w.number || ''} ${w.message}`),
|
||||
'',
|
||||
...(r.materialPoolSettlement?.pools?.length
|
||||
? [
|
||||
'剩余料款与' +
|
||||
teamMemberName('assistant') +
|
||||
'结算(正数' +
|
||||
teamMemberName('assistant') +
|
||||
'交' +
|
||||
teamMemberName('owner') +
|
||||
',负数' +
|
||||
teamMemberName('owner') +
|
||||
'转回助理)',
|
||||
...r.materialPoolSettlement.pools.map(
|
||||
item =>
|
||||
`${item.date}:${teamMemberName('assistant')}剩余料款 ${materialReportMoney(item.assistantInventoryCredit)},实际已交净额 ¥${yuan(item.transferred)},待结 ${materialReportMoney(item.settlementDue)}`,
|
||||
),
|
||||
'',
|
||||
]
|
||||
: []),
|
||||
'收款由经办人登记,不代表支付平台自动核验。各人实际付款与订单耗用成本分别核对;退货冲回耗用成本,锁价实际进货付款保留。净利润不含房租、工资、水电。',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function shopBrandName() {
|
||||
return state?.shopSettings?.storeName || state?.printing?.store || session?.brand?.storeName || '珠宝台账';
|
||||
}
|
||||
|
||||
function teamMemberOptions(assistantFirst = false, { historical = false, selected = '' } = {}) {
|
||||
let keys = (historical ? teamMemberKeys() : activeTeamMemberKeys()).filter(
|
||||
member => teamMode() || member !== 'assistant2',
|
||||
);
|
||||
if (assistantFirst)
|
||||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||||
const options = keys.map(member => [
|
||||
member,
|
||||
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
||||
]);
|
||||
if (selected && teamMemberKeys().includes(selected) && !keys.includes(selected))
|
||||
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
|
||||
return options;
|
||||
}
|
||||
|
||||
function currentMember() {
|
||||
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
|
||||
}
|
||||
|
||||
function teamMode() {
|
||||
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function dailyFundsMoney(value) {
|
||||
return value == null ? '待确认' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
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(' + '),
|
||||
};
|
||||
}
|
||||
|
||||
function teamDataKeys(data) {
|
||||
return [...assistantMemberKeys(), 'owner'].filter(member => data && Object.hasOwn(data, member));
|
||||
}
|
||||
|
||||
function reportSummaryAmount(summary, key) {
|
||||
const missing = summary.unknownCounts?.[key] || 0;
|
||||
return missing && summary.knownCounts?.[key] === 0 && !summary[key] && !summary.afterSaleCount
|
||||
? '待补齐'
|
||||
: (missing ? '已知 ' : '') + '¥' + yuan(summary[key]);
|
||||
}
|
||||
|
||||
const yuan = n =>
|
||||
n == null
|
||||
? '待补'
|
||||
: (n / 100).toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
function reportPeriod(range) {
|
||||
return range.from === range.date ? range.date : range.from + ' 至 ' + range.date;
|
||||
}
|
||||
|
||||
function reportActiveAccounts(r) {
|
||||
const recorded = new Set(
|
||||
teamDataKeys(r.recipientReceipts).flatMap(key => r.recipientReceipts[key].items.map(item => item.account)),
|
||||
);
|
||||
return r.accounts.filter(
|
||||
account =>
|
||||
account.receipt !== 0 ||
|
||||
account.refund !== 0 ||
|
||||
account.net !== 0 ||
|
||||
account.entryCount > 0 ||
|
||||
recorded.has(account.account),
|
||||
);
|
||||
}
|
||||
|
||||
function accountDisplayName(value) {
|
||||
const account = accountIdentity(value);
|
||||
return account ? teamMemberName(account.member) + account.channel : value;
|
||||
}
|
||||
|
||||
function reportDailyProfitAmount(value, known, profit = false) {
|
||||
return value === null ? (profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥') + yuan(known) + ')' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function reportTeamDownloadText(report) {
|
||||
const summary = report.summary,
|
||||
receipts = report.receiptsByOrderDate;
|
||||
return [
|
||||
shopBrandName() + '三人账 · ' + reportPeriod(report),
|
||||
'利润留在店里,按订单归属分别记业绩。经营款各自管理;未导入真实期初经营款。',
|
||||
...peopleCountReportLines(report.peopleCount),
|
||||
'销售净额:' + reportSummaryAmount(summary, 'sale'),
|
||||
'本期净利润:' + reportSummaryAmount(summary, 'profit'),
|
||||
'本期实收:¥' + yuan(receipts.receipt) + ';本期实退:¥' + yuan(receipts.refund),
|
||||
...reportDailyProfitsText(report),
|
||||
...reportOwnershipReceiptsText(report),
|
||||
...dailyFundsDownloadText(report),
|
||||
...reportRecipientReceiptsText(report),
|
||||
'按实际付款人核对成本',
|
||||
...teamDataKeys(report.payerCosts).flatMap(member => {
|
||||
const row = report.payerCosts[member];
|
||||
return [
|
||||
teamMemberName(member) +
|
||||
':实际货品支出 ' +
|
||||
reportCostAmount(row.goods, row.missingCount) +
|
||||
';已付费用 ¥' +
|
||||
yuan(row.paidFees),
|
||||
...reportCostItems(row).map(
|
||||
item =>
|
||||
item.date + ' / ' + reportCostIdentity(item) + ' / ' + item.name + ' / ' + reportCostItemAmount(item),
|
||||
),
|
||||
];
|
||||
}),
|
||||
'订单与售后',
|
||||
...report.orderRows.map(
|
||||
row =>
|
||||
row.date +
|
||||
' / ' +
|
||||
(row.paper_number || row.number || row.project) +
|
||||
' / ' +
|
||||
(row.customer || '未填客户') +
|
||||
' / ' +
|
||||
teamMemberName(row.member) +
|
||||
' / 销售 ' +
|
||||
reportRowAmount(row, 'sale') +
|
||||
' / 净利润 ' +
|
||||
reportRowAmount(row, 'profit'),
|
||||
),
|
||||
'历史两人结算不计入团队新债务。',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function reportCostAmount(value, partial = 0) {
|
||||
return partial && value === 0 ? '待补齐' : (partial ? '已知 ' : '') + '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function reportAfterSaleAmount(cost) {
|
||||
return cost.items.filter(item => item.kind === 'afterSale').reduce((sum, item) => sum + item.amount, 0);
|
||||
}
|
||||
|
||||
function reportPayerHints(cost) {
|
||||
return [
|
||||
cost.missingCount ? cost.missingCount + ' 项成本待补齐' : '',
|
||||
cost.pendingCount ? cost.pendingCount + ' 项费用未入账,不计合计' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(';');
|
||||
}
|
||||
|
||||
function reportCostItems(cost) {
|
||||
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
||||
}
|
||||
|
||||
function reportCostIdentity(item) {
|
||||
if (item.materialPoolId) return item.materialPoolId + ' 购料';
|
||||
return item.kind === 'afterSale'
|
||||
? '售后 · ' + (item.customer || '未填客户')
|
||||
: (item.price_lock_id ? '锁价 · ' : '') +
|
||||
(item.paper_number || item.number || '锁价记录') +
|
||||
(item.customer ? ' · ' + item.customer : '');
|
||||
}
|
||||
|
||||
function reportCostFormula(item) {
|
||||
const c = item.calculation;
|
||||
if (!c) return '';
|
||||
return (
|
||||
grams(c.quantity) +
|
||||
'g × ' +
|
||||
(c.rate == null
|
||||
? item.component === 'material'
|
||||
? '每克料价待补齐'
|
||||
: '每克工费待补齐'
|
||||
: yuan(c.rate) + '元/克') +
|
||||
(item.amount == null ? '' : ' = ' + yuan(item.amount) + '元')
|
||||
);
|
||||
}
|
||||
|
||||
function reportCostItemAmount(item) {
|
||||
if (item.kind === 'pending')
|
||||
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
|
||||
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
|
||||
}
|
||||
|
||||
function afterSalePayerName(row) {
|
||||
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
||||
}
|
||||
|
||||
const label = {
|
||||
draft: '旧草稿',
|
||||
confirmed: '旧单待补齐',
|
||||
delivered: '已完成',
|
||||
returned: '已退货',
|
||||
cancelled: '已取消',
|
||||
after_sale: '售后',
|
||||
recovery: '回收',
|
||||
};
|
||||
|
||||
function reportRowAmount(row, key) {
|
||||
if (row.status === 'draft') return '未开单';
|
||||
if (key === 'goods') {
|
||||
const c = reportRowCost(row);
|
||||
return reportCostAmount(c.goods, c.missing);
|
||||
}
|
||||
if (key === 'paidFees') return '¥' + yuan(reportRowCost(row).paidFees);
|
||||
if (row[key] != null) return '¥' + yuan(row[key]);
|
||||
return row.known?.[key] ? '已知 ¥' + yuan(row.known[key]) + '(待补齐)' : '待补齐';
|
||||
}
|
||||
|
||||
function reportDailyProfitsText(r) {
|
||||
const table = r.dailyProfits,
|
||||
rowText = row =>
|
||||
`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost, row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit, row.knownProfit, true)}`;
|
||||
return [
|
||||
'每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',
|
||||
...(table.rows.length
|
||||
? table.rows.map(row => `${row.date} / ${row.name} / ${rowText(row)}`)
|
||||
: ['所选范围暂无订单或售后记录。']),
|
||||
`所选范围合计:${rowText(table.summary)}`,
|
||||
'',
|
||||
];
|
||||
}
|
||||
|
||||
function reportOwnershipReceiptsText(r) {
|
||||
return [
|
||||
'按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)',
|
||||
...reportOwnershipKeys(r).flatMap(key => {
|
||||
const person = r.ownershipReceipts[key];
|
||||
return [
|
||||
`${person.name}所属订单净收入:¥${yuan(person.net)};实收 ¥${yuan(person.receipt)};实退 ¥${yuan(person.refund)}`,
|
||||
...person.accounts.map(
|
||||
account =>
|
||||
`${account.recipient === person.member ? '本人收款' : '他人代收'} / ${accountDisplayName(account.account)}:实收 ¥${yuan(account.receipt)},实退 ¥${yuan(account.refund)},净额 ¥${yuan(account.net)}`,
|
||||
),
|
||||
...reportOwnershipBusinessText(r.ownershipBusiness[key]),
|
||||
'',
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function dailyFundsDownloadText(report) {
|
||||
const range = {
|
||||
date: report.date,
|
||||
from: report.from,
|
||||
month: reportMonth,
|
||||
},
|
||||
data = report.dailyFunds;
|
||||
if (data?.team)
|
||||
return [
|
||||
'每日报销单(按报销日期归集,已批准报销不在当日订单往来重复相加)',
|
||||
...data.reimbursements.flatMap(row => [
|
||||
`${row.date} / ${row.requester_name} / ${reimbursementStatusNames[row.status]} / 合计 ¥${yuan(row.total)}`,
|
||||
...row.items.map(item => `${item.name}:¥${yuan(item.amount)}`),
|
||||
]),
|
||||
'',
|
||||
];
|
||||
if (!data || data.rangeUnsupported) return ['每天转账核对', '尚未取得完整转账资料,不输出应转金额。', ''];
|
||||
try {
|
||||
validateDailyFunds(data, range);
|
||||
} catch {
|
||||
return ['每天转账核对', '资料未完整返回,不输出应转金额。', ''];
|
||||
}
|
||||
const result = [
|
||||
'每天转账核对(应转合计,未扣已转)',
|
||||
`${teamMemberName('owner')}实收 ¥${yuan(data.ownerReceipts.receipt)} − 实退 ¥${yuan(data.ownerReceipts.refund)} = 净收款 ¥${yuan(data.ownerReceipts.net)}`,
|
||||
];
|
||||
if (data.ready)
|
||||
result.push(
|
||||
`${teamMemberName('owner')}净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,
|
||||
data.transferAmount > 0
|
||||
? '方向:' + teamMemberName('owner') + '转' + teamMemberName('assistant')
|
||||
: data.transferAmount < 0
|
||||
? '方向:' + teamMemberName('assistant') + '转' + teamMemberName('owner')
|
||||
: '方向:无需转款',
|
||||
);
|
||||
else
|
||||
result.push(
|
||||
'当天完整支出尚未全部确认,暂不输出完整应转合计。',
|
||||
...(data.missingDates.length ? ['待确认日期:' + data.missingDates.join('、')] : []),
|
||||
...(data.staleDates.length ? ['来源变动待重新确认:' + data.staleDates.join('、')] : []),
|
||||
);
|
||||
result.push('不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。', '已批准报销项目(按报销日期归集)');
|
||||
const approved = data.reimbursements.filter(row => row.status === 'approved');
|
||||
result.push(
|
||||
...(approved.length
|
||||
? approved.flatMap(row => [
|
||||
`${row.date} / ${row.requester_name} / 合计 ¥${yuan(row.total)} / ${row.reviewer_name || teamMemberName('owner')}复核`,
|
||||
...row.items.map(item => `${item.name}:¥${yuan(item.amount)}`),
|
||||
])
|
||||
: ['本期暂无已批准报销。']),
|
||||
'',
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
function reportRecipientReceiptsText(r) {
|
||||
return [
|
||||
'按收款人汇总(普通订单按开单日归集当前收付,锁价按实际收付日归集;负数为冲回)',
|
||||
...teamDataKeys(r.recipientReceipts).flatMap(key => {
|
||||
const person = r.recipientReceipts[key];
|
||||
return [
|
||||
`${person.name}总收款:¥${yuan(person.receipt)};退款 ¥${yuan(person.refund)};净收款 ¥${yuan(person.net)}`,
|
||||
...['receipt', 'refund'].flatMap(kind => {
|
||||
const items = person.items.filter(item => item.kind === kind),
|
||||
name = kind === 'receipt' ? '收款' : '退款';
|
||||
return [
|
||||
`${person.name}${name}明细(日期为实际${name}日):`,
|
||||
...(items.length
|
||||
? items.map(
|
||||
item =>
|
||||
`${item.date} / ${reportReceiptBasis(item)} / ${item.paper_number || item.number || (item.price_lock_id ? '锁价记录' : '订单记录')} / 客户 ${item.customer || '未填客户称呼'} / ${accountDisplayName(item.account)} / ${reportReceiptLabel(item)} ¥${yuan(item.amount)}${item.reference || item.note ? ' / ' + (item.reference || item.note) : ''}`,
|
||||
)
|
||||
: ['所选范围没有' + person.name + name + '记录。']),
|
||||
`${name}明细合计:¥${yuan(person[kind])}`,
|
||||
];
|
||||
}),
|
||||
'',
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function priceLockActivityText(activity) {
|
||||
if (!activity?.summary?.eventCount) return [];
|
||||
const s = activity.summary;
|
||||
return [
|
||||
'锁价实际收付(按实际发生日期,不重复计原锁付款;待交付不计销售和利润)',
|
||||
`客户实收 ¥${yuan(s.receipt)};客户实退 ¥${yuan(s.refund)};${teamMemberName('owner')}实际支出 ¥${yuan(s.ownerOutlay)};${teamMemberName('assistant')}实际支出 ¥${yuan(s.assistantOutlay)}`,
|
||||
...priceLockActivityRows(activity).map(
|
||||
item =>
|
||||
`${item.date} / ${item.number || '锁价记录'} / ${item.customer} / ${item.activityType} / ${item.activityName} / ${item.who} / ${item.amount == null ? '待补齐' : '¥' + yuan(item.amount)}`,
|
||||
),
|
||||
'',
|
||||
];
|
||||
}
|
||||
|
||||
const grams = n => (n / 1000).toFixed(3);
|
||||
|
||||
const materialPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
||||
|
||||
function pocketLabel(key) {
|
||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||
}
|
||||
|
||||
function pocketCountsEnabled(key) {
|
||||
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
|
||||
}
|
||||
|
||||
function stockCountText(value, { signed = false, unknown = '未记录对数' } = {}) {
|
||||
return Number.isSafeInteger(value) ? (signed && value > 0 ? '+' : '') + value + '对' : unknown;
|
||||
}
|
||||
|
||||
function materialReportMoney(value) {
|
||||
return value == null ? '料费待补' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function teamMemberName(member) {
|
||||
return (
|
||||
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||||
state?.members?.find(row => row.member === member)?.label ||
|
||||
session?.loginOptions?.find(row => row.member === member)?.label ||
|
||||
{
|
||||
owner: '麦麦',
|
||||
assistant: '娜娜',
|
||||
assistant2: '小昊',
|
||||
}[member] ||
|
||||
'待确认'
|
||||
);
|
||||
}
|
||||
|
||||
const reimbursementStatusNames = {
|
||||
pending: '待店主复核',
|
||||
approved: '已批准',
|
||||
rejected: '已驳回',
|
||||
};
|
||||
|
||||
function dailyFundsOwner() {
|
||||
return state?.user?.role === 'owner';
|
||||
}
|
||||
|
||||
function teamMemberKeys() {
|
||||
return teamMemberCatalog().map(row => row.member);
|
||||
}
|
||||
|
||||
function activeTeamMemberKeys() {
|
||||
return teamMemberKeys().filter(teamMemberEnabled);
|
||||
}
|
||||
|
||||
function teamMemberEnabled(member) {
|
||||
return (
|
||||
teamMemberCatalog().find(row => row.member === member)?.enabled !== false && teamMemberKeys().includes(member)
|
||||
);
|
||||
}
|
||||
|
||||
function assistantMemberKeys() {
|
||||
return teamMemberKeys().filter(member => member !== 'owner');
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function priceLockActivityRows(activity) {
|
||||
if (!activity) return [];
|
||||
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
||||
.map(item => ({
|
||||
...item,
|
||||
activityType: item.kind === 'receipt' ? '客户收款' : '客户退款',
|
||||
who: accountDisplayName(item.account),
|
||||
activityName: item.product || '客户收退款',
|
||||
}))
|
||||
.concat(
|
||||
(activity.materialOutlays || []).map(item => ({
|
||||
...item,
|
||||
activityType: item.source === 'extra' ? '补重料费付款' : '原锁料费付款',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: (item.product || '黄金') + ' · ' + grams(item.quantity) + 'g × ' + yuan(item.rate) + '元/克',
|
||||
})),
|
||||
(activity.deliveryGoodsOutlays || []).map(item => ({
|
||||
...item,
|
||||
activityType: '交付货品支出',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: item.name,
|
||||
})),
|
||||
(activity.directOutlays || []).map(item => ({
|
||||
...item,
|
||||
activityType: '实际费用',
|
||||
who: priceLockPayerName(item.payer),
|
||||
activityName: item.note,
|
||||
})),
|
||||
)
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
}
|
||||
|
||||
const materialPurchasePayer = purchase => purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
|
||||
|
||||
function peopleCountReportLines(count) {
|
||||
const period = count?.from !== count?.date;
|
||||
return peopleParts(true).map(
|
||||
([part, name]) =>
|
||||
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (count?.[part]?.baselineDate || '暂无') + ')' : ''}`,
|
||||
);
|
||||
}
|
||||
|
||||
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 reportOwnershipBusinessText(business) {
|
||||
return [
|
||||
`所属订单总成本:${reportBusinessAmount(business.totalCost, business.knownTotalCost)};本人付款 ${reportBusinessAmount(business.selfCost, business.knownSelfCost)};他人付款 ${reportBusinessAmount(business.otherCost, business.knownOtherCost)}`,
|
||||
...reportPoolMaterialText(business),
|
||||
...reportOwnerAdvancesText(business),
|
||||
...teamMemberKeys()
|
||||
.filter(key => key !== business.member)
|
||||
.map(key => business.costByPayer[key])
|
||||
.filter(payer => payer.knownTotalCost || payer.totalCost === null)
|
||||
.map(payer => `${payer.name}付款:${reportBusinessAmount(payer.totalCost, payer.knownTotalCost)}`),
|
||||
`本期利润:${business.equation.complete && !business.incomplete && business.profit !== null ? '¥' + yuan(business.profit) : '待核算,完整利润暂不显示'}`,
|
||||
...business.difference.reasons.map(reason => reason.text),
|
||||
...reportCurrentAccountText(business),
|
||||
];
|
||||
}
|
||||
|
||||
function reportReceiptBasis(item) {
|
||||
return item.order_after_sale
|
||||
? '订单售后 · 按实际收付日'
|
||||
: item.price_lock_id
|
||||
? '锁价 · 按实际收付日'
|
||||
: '普通订单 · 开单 ' + (item.order_date || '日期未提供');
|
||||
}
|
||||
|
||||
function reportReceiptLabel(item) {
|
||||
return (item.kind === 'receipt' ? '收款' : '退款') + (item.amount < 0 ? '冲回' : '');
|
||||
}
|
||||
|
||||
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 memberAccountPrefix(member) {
|
||||
return (
|
||||
{
|
||||
owner: '麦麦',
|
||||
assistant: '助理',
|
||||
assistant2: '助理2',
|
||||
}[member] || member
|
||||
);
|
||||
}
|
||||
|
||||
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
||||
|
||||
function peopleParts(historical = false) {
|
||||
const keys = assistantMemberKeys().filter(member => historical || teamMemberEnabled(member)),
|
||||
parts = keys.map(member => [member === 'assistant' ? 'assistant1' : member, teamMemberName(member) + '人数']);
|
||||
return state?.user?.role === 'assistant' && teamMode()
|
||||
? parts.filter(([key]) => peoplePartMember(key) === currentMember())
|
||||
: parts;
|
||||
}
|
||||
|
||||
function peopleCountDisplayName(name, period = false) {
|
||||
return name.replace('人数', period ? '结束日总人数' : '当日总人数');
|
||||
}
|
||||
|
||||
function peopleCountText(count, part = null) {
|
||||
const value = part ? count?.[part] : count;
|
||||
if (!value || !Object.hasOwn(value, 'endTotal') || !Object.hasOwn(value, 'netChange')) return '尚未取得总人数';
|
||||
const period = count.from !== count.date,
|
||||
total = value.endTotal === null ? (period ? '结束日未记录' : '当日未记录') : value.endTotal + ' 人(已记录)';
|
||||
const baseline = value.baselineDate,
|
||||
comparison = '较上次记录' + (baseline ? '(' + baseline + ')' : '');
|
||||
return (
|
||||
total +
|
||||
' · ' +
|
||||
(period
|
||||
? '本期净增 ' +
|
||||
(value.netChange === null
|
||||
? '未知(' + peopleCountUnknownReason(value.netChangeReason, true) + ')'
|
||||
: peopleCountSignedText(value.netChange)) +
|
||||
(baseline ? '(基准 ' + baseline + ')' : '')
|
||||
: value.netChange === null
|
||||
? value.endTotal !== null && value.netChangeReason === 'missing-previous'
|
||||
? '首次记录(暂无上次记录)'
|
||||
: comparison + '变化未知(' + peopleCountUnknownReason(value.netChangeReason) + ')'
|
||||
: comparison + peopleCountDeltaText(value.netChange))
|
||||
);
|
||||
}
|
||||
|
||||
function reportBusinessAmount(value, known) {
|
||||
return (value === null ? '已知 ' : '') + '¥' + yuan(value === null ? known : value);
|
||||
}
|
||||
|
||||
function reportPoolMaterialText(business) {
|
||||
const pool = business.poolMaterial;
|
||||
if (!pool?.days.length) return [];
|
||||
const owner = pool.byPayer.owner;
|
||||
return [
|
||||
`已用料合计:${grams(pool.mg)}g`,
|
||||
`料池已用料费:${reportBusinessAmount(pool.amount, pool.knownAmount)}(已计入总成本;当日往来只取${teamMemberName('owner')}垫付部分,公式中计入一次)`,
|
||||
...pool.days.map(day => `${day.date} 料池(已用 ${grams(day.mg)}g):${reportPoolMaterialFormula(day)}`),
|
||||
...(reportPoolMaterialPendingNote(pool) ? [reportPoolMaterialPendingNote(pool)] : []),
|
||||
`其中${teamMemberName('owner')}垫付:${reportBusinessAmount(owner.amount, owner.knownAmount)}`,
|
||||
`其他成本:${reportBusinessAmount(pool.otherCosts.amount, pool.otherCosts.knownAmount)}(其余商品成本、工费与费用)`,
|
||||
'料费按未四舍五入均价逐单核算,显示料价相乘可能有分币差。',
|
||||
...(pool.hasPriceLocks ? ['锁价已用料费在交付日的当日往来中列示,不重复记实际采购支出。'] : []),
|
||||
];
|
||||
}
|
||||
|
||||
function reportOwnerAdvancesText(business) {
|
||||
const advances = business.ownerAdvances,
|
||||
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
||||
return [
|
||||
label + '(按所属订单开单日/售后记录日逐日核对,不累计历史;预估未付不计实付)',
|
||||
...(advances.days.length
|
||||
? advances.days.flatMap(day => [
|
||||
`${day.date} ${business.member === 'owner' ? '付款' : '垫付'}小计:${reportOwnerAdvanceAmount(day.amount, day.knownAmount)}`,
|
||||
...(day.items.some(item => item.poolMaterial) ? [reportOwnerAdvanceFormula(business, day)] : []),
|
||||
...day.items.map(
|
||||
item =>
|
||||
`${item.date} / ${item.customer || '未填客户'} / ${item.paperNumber || item.number} / ${item.name} / ${reportOwnerAdvanceItemAmount(item)}`,
|
||||
),
|
||||
])
|
||||
: [
|
||||
advances.from === advances.date
|
||||
? advances.date + ' 当日已登记垫付 ¥0.00,无明细。'
|
||||
: '所选月份暂无已登记明细。',
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
function reportCurrentAccountText(business) {
|
||||
if (business.member === 'owner') return [];
|
||||
return [
|
||||
'当日往来账(逐日核对,不含历史余额,未扣实际转账)',
|
||||
...reportCurrentAccountDays(business).flatMap(day => [
|
||||
`${day.date} / ${reportCurrentAccountDirection(business, day)}${day.amount === null ? '' : ' ¥' + yuan(Math.abs(day.amount))}`,
|
||||
reportCurrentAccountFormula(day),
|
||||
...(day.incomplete ? ['成本或利润尚未补齐,暂不显示完整应转金额;预估未付项目不计垫付。'] : []),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
const legacyTeamMembers = [
|
||||
{
|
||||
member: 'owner',
|
||||
label: '麦麦',
|
||||
},
|
||||
{
|
||||
member: 'assistant',
|
||||
label: '娜娜',
|
||||
},
|
||||
{
|
||||
member: 'assistant2',
|
||||
label: '小昊',
|
||||
},
|
||||
];
|
||||
|
||||
function reportOwnerAdvanceAmount(value, known) {
|
||||
return value === null ? '待补(已知 ¥' + yuan(known) + ')' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function reportOwnerAdvanceFormula(business, day) {
|
||||
return `${business.member === 'owner' ? teamMemberName('owner') + '付款合计' : teamMemberName('owner') + '垫付合计'}:料池料费 ${reportOwnerAdvanceAmount(day.poolAmount, day.knownPoolAmount)} + 其他成本 ${reportOwnerAdvanceAmount(day.otherAmount, day.knownOtherAmount)} = ${reportOwnerAdvanceAmount(day.amount, day.knownAmount)}`;
|
||||
}
|
||||
|
||||
function reportOwnerAdvanceItemAmount(item) {
|
||||
if (item.status === 'pending')
|
||||
return (
|
||||
'待核对' +
|
||||
(item.estimatedAmount === null ? '(金额待补)' : '(预估 ¥' + yuan(item.estimatedAmount) + ')') +
|
||||
',未计垫付'
|
||||
);
|
||||
return item.amount === null ? '待补齐' : '¥' + yuan(item.amount);
|
||||
}
|
||||
|
||||
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
|
||||
? '应转金额待核算'
|
||||
: day.amount > 0
|
||||
? business.name + ('应转' + teamMemberName('owner'))
|
||||
: day.amount < 0
|
||||
? teamMemberName('owner') + '应转' + business.name
|
||||
: '当日无需转款';
|
||||
}
|
||||
|
||||
function reportCurrentAccountFormula(day) {
|
||||
return `${teamMemberName('owner')}垫付已用料费 ${reportOwnerAdvanceAmount(day.materialCost, day.knownMaterialCost)} + ${teamMemberName('owner')}垫付其他订单成本 ${reportOwnerAdvanceAmount(day.otherCost, day.knownOtherCost)} + 本人当日订单净利润 ${reportDailyProfitAmount(day.profit, day.knownProfit, true)} − ${teamMemberName('owner')}代收净额 ¥${yuan(day.ownerNetReceipts)} = ${day.amount === null ? '待核算' : '¥' + yuan(day.amount)}`;
|
||||
}
|
||||
|
||||
function peoplePartMember(part) {
|
||||
return part === 'assistant1' ? 'assistant' : part;
|
||||
}
|
||||
|
||||
function peopleCountUnknownReason(reason, period = false) {
|
||||
return (
|
||||
{
|
||||
'missing-current': period ? '结束日未记录' : '当日未记录',
|
||||
'missing-previous': period ? '开始日前暂无记录' : '暂无上次记录',
|
||||
'missing-both': period ? '结束日未记录,开始日前暂无记录' : '当日未记录,暂无上次记录',
|
||||
}[reason] || '缺少人数记录'
|
||||
);
|
||||
}
|
||||
|
||||
function peopleCountSignedText(value) {
|
||||
return (value > 0 ? '+' : '') + value + ' 人';
|
||||
}
|
||||
|
||||
function peopleCountDeltaText(value) {
|
||||
return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math.abs(value) + ' 人' : '无变化(0 人)';
|
||||
}
|
||||
|
||||
function reportPoolMaterialFormula(day) {
|
||||
if (day.sources)
|
||||
return (
|
||||
day.sources
|
||||
.map(
|
||||
source =>
|
||||
`${reportPoolMaterialSourceLabel(source)} ${grams(source.mg)}g × ${source.averageRate === null ? '待补料价' : '¥' + yuan(source.averageRate) + '/g'}`,
|
||||
)
|
||||
.join(' + ') +
|
||||
` = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`
|
||||
);
|
||||
return `${grams(day.mg)}g × ${day.averageRate === null ? '待补料价' : '¥' + yuan(day.averageRate) + '/g'} = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`;
|
||||
}
|
||||
|
||||
function reportPoolMaterialPendingNote(pool) {
|
||||
return pool.days.some(
|
||||
day => day.sources && day.sources.reduce((total, source) => total + source.knownAmount, 0) > day.knownAmount,
|
||||
)
|
||||
? '部分来源已可核对,料费待补的订单尚未计入已知料费。'
|
||||
: '';
|
||||
}
|
||||
|
||||
function reportPoolMaterialSourceLabel(source) {
|
||||
return (
|
||||
(source.kind === 'personal_recovery' ? teamMemberName(source.member) + '个人回收料' : '公共料') +
|
||||
(source.priceLocked ? '(含锁价原料)' : '')
|
||||
);
|
||||
}
|
||||
const { validateDailyFunds, validateReport, validateDailyReimbursements } = reportValidation({
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
teamMode,
|
||||
currentMember,
|
||||
teamMemberKeys,
|
||||
reimbursementStatusNames,
|
||||
state,
|
||||
reportMember,
|
||||
});
|
||||
return {
|
||||
validateReport,
|
||||
validateDailyFunds,
|
||||
validateDailyReimbursements,
|
||||
reportDownloadText,
|
||||
shopBrandName,
|
||||
teamMemberOptions,
|
||||
currentMember,
|
||||
teamMode,
|
||||
validOrderDate,
|
||||
dailyFundsMoney,
|
||||
reimbursementDraftTotal,
|
||||
reportSummaryAmount,
|
||||
yuan,
|
||||
reportPeriod,
|
||||
reportActiveAccounts,
|
||||
accountDisplayName,
|
||||
reportDailyProfitAmount,
|
||||
reimbursementStatusNames,
|
||||
teamMemberName,
|
||||
dailyFundsOwner,
|
||||
reportOwnershipKeys,
|
||||
teamDataKeys,
|
||||
reportPayerHints,
|
||||
reportCostAmount,
|
||||
reportAfterSaleAmount,
|
||||
priceLockActivityRows,
|
||||
grams,
|
||||
materialPayerName,
|
||||
materialPurchasePayer,
|
||||
afterSalePayerName,
|
||||
reportRowAmount,
|
||||
pocketLabel,
|
||||
materialReportMoney,
|
||||
reportReceiptBasis,
|
||||
reportReceiptLabel,
|
||||
reportCostItems,
|
||||
reportCostFormula,
|
||||
reportCostItemAmount,
|
||||
label,
|
||||
pocketCountsEnabled,
|
||||
stockCountText,
|
||||
teamMemberKeys,
|
||||
reportBusinessAmount,
|
||||
reportOwnerAdvanceAmount,
|
||||
reportOwnerAdvanceFormula,
|
||||
reportOwnerAdvanceItemAmount,
|
||||
reportCurrentAccountDays,
|
||||
reportCurrentAccountDirection,
|
||||
reportCurrentAccountFormula,
|
||||
reportPoolMaterialPendingNote,
|
||||
reportCostIdentity,
|
||||
reportPoolMaterialFormula,
|
||||
reportPoolMaterialSourceLabel,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,895 @@
|
||||
// 返回数据在进入报表时完成一次校验,核对明细加总、表间关联及团队权限。
|
||||
export function reportValidation({
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
teamMode,
|
||||
currentMember,
|
||||
teamMemberKeys,
|
||||
reimbursementStatusNames,
|
||||
state,
|
||||
reportMember,
|
||||
}) {
|
||||
function validateReport(r, range) {
|
||||
if (r.basis !== 'orderDate' || r.date !== range.date || r.from !== range.from)
|
||||
throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
|
||||
if (
|
||||
!r.summary ||
|
||||
!Array.isArray(r.orderRows) ||
|
||||
!Array.isArray(r.accounts) ||
|
||||
!r.receiptsByOrderDate ||
|
||||
!teamDataKeys(r.payerCosts).length ||
|
||||
!teamDataKeys(r.payerCosts).every(key => {
|
||||
const c = r.payerCosts?.[key];
|
||||
return (
|
||||
c &&
|
||||
Array.isArray(c.items) &&
|
||||
['goods', 'paidFees', 'total', 'missingCount', 'pendingCount'].every(name => Number.isSafeInteger(c[name]))
|
||||
);
|
||||
})
|
||||
)
|
||||
throw new Error('对账数据尚未完整返回,请重新读取。');
|
||||
const recipientKeys = teamDataKeys(r.recipientReceipts),
|
||||
recipients = recipientKeys.map(key => r.recipientReceipts?.[key]);
|
||||
if (
|
||||
!recipientKeys.length ||
|
||||
!recipients.every(
|
||||
(person, index) =>
|
||||
person &&
|
||||
person.recipient === recipientKeys[index] &&
|
||||
typeof person.name === 'string' &&
|
||||
person.name &&
|
||||
Array.isArray(person.items) &&
|
||||
['receipt', 'refund', 'net'].every(key => Number.isSafeInteger(person[key])) &&
|
||||
person.items.every(
|
||||
item =>
|
||||
item &&
|
||||
['receipt', 'refund'].includes(item.kind) &&
|
||||
Number.isSafeInteger(item.amount) &&
|
||||
typeof item.account === 'string' &&
|
||||
validOrderDate(item.date),
|
||||
) &&
|
||||
person.net === person.receipt - person.refund &&
|
||||
['receipt', 'refund'].every(
|
||||
kind =>
|
||||
person.items.filter(item => item.kind === kind).reduce((sum, item) => sum + item.amount, 0) ===
|
||||
person[kind],
|
||||
),
|
||||
) ||
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
key => recipients.reduce((sum, person) => sum + person[key], 0) === r.receiptsByOrderDate[key],
|
||||
)
|
||||
)
|
||||
throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
|
||||
validateOwnershipReceipts(r);
|
||||
validateOwnershipBusiness(r);
|
||||
validateDailyProfits(r);
|
||||
}
|
||||
|
||||
function validateDailyFunds(data, range) {
|
||||
if (data?.team) {
|
||||
if (data.date !== range.date || data.from !== range.from || !Array.isArray(data.reimbursements))
|
||||
throw new Error('团队日期或报销资料未完整返回,请重新读取。');
|
||||
validateTeamFunds(data.team);
|
||||
data.reimbursements.forEach(validateReimbursement);
|
||||
return data;
|
||||
}
|
||||
const money = value => Number.isSafeInteger(value),
|
||||
nullable = value => value === null || money(value);
|
||||
if (
|
||||
!data ||
|
||||
data.date !== range.date ||
|
||||
data.from !== range.from ||
|
||||
typeof data.readOnly !== 'boolean' ||
|
||||
typeof data.ready !== 'boolean' ||
|
||||
!['receipt', 'refund', 'net'].every(key => money(data.ownerReceipts?.[key])) ||
|
||||
data.ownerReceipts.net !== data.ownerReceipts.receipt - data.ownerReceipts.refund ||
|
||||
!money(data.approvedReimbursements) ||
|
||||
!nullable(data.actualOutlay) ||
|
||||
!nullable(data.transferAmount) ||
|
||||
data.transfersNotDeducted !== true ||
|
||||
!Array.isArray(data.reimbursements) ||
|
||||
!Array.isArray(data.days) ||
|
||||
!Array.isArray(data.missingDates) ||
|
||||
!Array.isArray(data.staleDates) ||
|
||||
!Number.isSafeInteger(data.pendingCount) ||
|
||||
data.pendingCount < 0 ||
|
||||
typeof data.sources?.revision !== 'string' ||
|
||||
!money(data.sources.total) ||
|
||||
!Array.isArray(data.sources.items) ||
|
||||
!data.sources.items.every(
|
||||
item =>
|
||||
item &&
|
||||
typeof item.id === 'string' &&
|
||||
validOrderDate(item.date) &&
|
||||
money(item.amount) &&
|
||||
item.payer === 'owner' &&
|
||||
typeof item.name === 'string',
|
||||
) ||
|
||||
data.sources.items.reduce((sum, item) => sum + item.amount, 0) !== data.sources.total
|
||||
)
|
||||
throw new Error('转账核对资料未完整返回,请重新读取。');
|
||||
data.reimbursements.forEach(validateReimbursement);
|
||||
if (
|
||||
data.confirmation &&
|
||||
(!money(data.confirmation.amount) ||
|
||||
data.confirmation.amount < 0 ||
|
||||
!Number.isSafeInteger(data.confirmation.revision) ||
|
||||
typeof data.confirmation.sourceRevision !== 'string' ||
|
||||
typeof data.confirmation.stale !== 'boolean')
|
||||
)
|
||||
throw new Error('实际支出确认资料未完整返回,请重新读取。');
|
||||
if (
|
||||
(data.ready &&
|
||||
(data.actualOutlay == null ||
|
||||
data.transferAmount !== data.ownerReceipts.net - data.actualOutlay + data.approvedReimbursements)) ||
|
||||
(!data.ready && data.transferAmount !== null)
|
||||
)
|
||||
throw new Error('转账合计与分项不一致,请重新读取。');
|
||||
if (!range.month && range.from === range.date && data.ready && (!data.confirmation || data.confirmation.stale))
|
||||
throw new Error('当天支出尚未有效确认,请重新读取。');
|
||||
return data;
|
||||
}
|
||||
|
||||
function validateDailyReimbursements(data) {
|
||||
if (
|
||||
!data ||
|
||||
!Array.isArray(data.requests) ||
|
||||
!Number.isSafeInteger(data.total) ||
|
||||
!Number.isSafeInteger(data.offset) ||
|
||||
!Number.isSafeInteger(data.limit) ||
|
||||
typeof data.hasMore !== 'boolean' ||
|
||||
!['pending', 'approved', 'rejected'].every(key => Number.isSafeInteger(data.counts?.[key]))
|
||||
)
|
||||
throw new Error('全日期报销列表未完整返回,请重新读取。');
|
||||
data.requests.forEach(validateReimbursement);
|
||||
return data;
|
||||
}
|
||||
|
||||
function validateOwnershipReceipts(r) {
|
||||
const fail = () => {
|
||||
throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');
|
||||
},
|
||||
keys = teamDataKeys(r.ownershipReceipts),
|
||||
selected = teamMode() ? (state.user.role === 'owner' ? reportMember : currentMember()) : '',
|
||||
expected = selected ? [selected] : teamMode() ? teamMemberKeys() : teamDataKeys(r.recipientReceipts);
|
||||
if (
|
||||
!r.ownershipReceipts ||
|
||||
typeof r.ownershipReceipts !== 'object' ||
|
||||
Array.isArray(r.ownershipReceipts) ||
|
||||
Object.keys(r.ownershipReceipts).length !== expected.length ||
|
||||
keys.length !== expected.length ||
|
||||
!expected.every(key => keys.includes(key))
|
||||
)
|
||||
fail();
|
||||
const receipts = [],
|
||||
owned = [],
|
||||
sum = (items, kind) => items.filter(item => item.kind === kind).reduce((total, item) => total + item.amount, 0);
|
||||
for (const key of keys) {
|
||||
const person = r.ownershipReceipts[key];
|
||||
if (
|
||||
!person ||
|
||||
person.member !== key ||
|
||||
typeof person.name !== 'string' ||
|
||||
!person.name ||
|
||||
!Array.isArray(person.accounts) ||
|
||||
!Array.isArray(person.items) ||
|
||||
!['receipt', 'refund', 'net'].every(name => Number.isSafeInteger(person[name])) ||
|
||||
person.net !== person.receipt - person.refund
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
!person.items.every(
|
||||
item =>
|
||||
item &&
|
||||
['receipt', 'refund'].includes(item.kind) &&
|
||||
Number.isSafeInteger(item.amount) &&
|
||||
typeof item.account === 'string' &&
|
||||
validOrderDate(item.date),
|
||||
) ||
|
||||
!['receipt', 'refund'].every(kind => sum(person.items, kind) === person[kind])
|
||||
)
|
||||
fail();
|
||||
const accounts = new Set();
|
||||
for (const account of person.accounts) {
|
||||
if (
|
||||
!account ||
|
||||
typeof account.account !== 'string' ||
|
||||
!account.account ||
|
||||
accounts.has(account.account) ||
|
||||
!teamMemberKeys().includes(account.recipient) ||
|
||||
!['wechat', 'alipay', 'cash', 'credit_card'].includes(account.channel) ||
|
||||
!['receipt', 'refund', 'net', 'entryCount'].every(name => Number.isSafeInteger(account[name])) ||
|
||||
account.entryCount < 1 ||
|
||||
account.net !== account.receipt - account.refund
|
||||
)
|
||||
fail();
|
||||
const items = person.items.filter(item => item.account === account.account);
|
||||
if (
|
||||
items.length !== account.entryCount ||
|
||||
!['receipt', 'refund'].every(kind => sum(items, kind) === account[kind])
|
||||
)
|
||||
fail();
|
||||
accounts.add(account.account);
|
||||
}
|
||||
if (
|
||||
person.items.some(item => !accounts.has(item.account)) ||
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
name => person.accounts.reduce((total, account) => total + account[name], 0) === person[name],
|
||||
)
|
||||
)
|
||||
fail();
|
||||
receipts.push(person);
|
||||
owned.push(...person.items);
|
||||
}
|
||||
if (
|
||||
!['receipt', 'refund', 'net'].every(
|
||||
name => receipts.reduce((total, person) => total + person[name], 0) === r.receiptsByOrderDate[name],
|
||||
)
|
||||
)
|
||||
fail();
|
||||
const identity = item =>
|
||||
JSON.stringify([item.id, item.kind, item.amount, item.account, item.date, item.order_id, item.price_lock_id]),
|
||||
actual = teamDataKeys(r.recipientReceipts)
|
||||
.flatMap(key => r.recipientReceipts[key].items)
|
||||
.map(identity)
|
||||
.sort(),
|
||||
copies = owned.map(identity).sort();
|
||||
if (actual.length !== copies.length || actual.some((value, index) => value !== copies[index])) fail();
|
||||
}
|
||||
|
||||
function validateOwnershipBusiness(r) {
|
||||
const fail = () => {
|
||||
throw new Error('所属订单成本、利润或待转资料未完整返回,请重新读取。');
|
||||
},
|
||||
money = value => Number.isSafeInteger(value),
|
||||
nullable = value => value === null || money(value),
|
||||
count = value => money(value) && value >= 0,
|
||||
keys = teamDataKeys(r.ownershipReceipts);
|
||||
if (
|
||||
!r.ownershipBusiness ||
|
||||
typeof r.ownershipBusiness !== 'object' ||
|
||||
Array.isArray(r.ownershipBusiness) ||
|
||||
Object.keys(r.ownershipBusiness).length !== keys.length ||
|
||||
!keys.every(key => Object.hasOwn(r.ownershipBusiness, key))
|
||||
)
|
||||
fail();
|
||||
for (const member of keys) {
|
||||
const b = r.ownershipBusiness[member];
|
||||
if (
|
||||
!b ||
|
||||
b.member !== member ||
|
||||
typeof b.name !== 'string' ||
|
||||
!b.name ||
|
||||
b.basis !== 'orderDate' ||
|
||||
b.from !== r.from ||
|
||||
b.date !== r.date ||
|
||||
b.netReceipts !== r.ownershipReceipts[member].net ||
|
||||
!['sales', 'netReceipts', 'knownTotalCost', 'knownSelfCost', 'knownOtherCost', 'knownProfit'].every(key =>
|
||||
money(b[key]),
|
||||
) ||
|
||||
!['totalCost', 'selfCost', 'otherCost', 'profit'].every(key => nullable(b[key])) ||
|
||||
![
|
||||
'missingCostCount',
|
||||
'pendingCostCount',
|
||||
'unknownProfitCount',
|
||||
'draftCount',
|
||||
'recordCount',
|
||||
'orderCount',
|
||||
'afterSaleCount',
|
||||
].every(key => count(b[key])) ||
|
||||
typeof b.incomplete !== 'boolean' ||
|
||||
typeof b.hasActivity !== 'boolean'
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
b.knownSelfCost + b.knownOtherCost !== b.knownTotalCost ||
|
||||
(b.totalCost !== null && b.totalCost !== b.knownTotalCost) ||
|
||||
(b.selfCost !== null && b.selfCost !== b.knownSelfCost) ||
|
||||
(b.otherCost !== null && b.otherCost !== b.knownOtherCost)
|
||||
)
|
||||
fail();
|
||||
if (!b.costByPayer || Object.keys(b.costByPayer).length !== teamMemberKeys().length) fail();
|
||||
for (const payer of teamMemberKeys()) {
|
||||
const row = b.costByPayer[payer];
|
||||
if (
|
||||
!row ||
|
||||
row.member !== payer ||
|
||||
typeof row.name !== 'string' ||
|
||||
!row.name ||
|
||||
!nullable(row.totalCost) ||
|
||||
!money(row.knownTotalCost) ||
|
||||
!count(row.missingCount) ||
|
||||
!count(row.pendingCount) ||
|
||||
(row.totalCost !== null && row.totalCost !== row.knownTotalCost)
|
||||
)
|
||||
fail();
|
||||
}
|
||||
if (
|
||||
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].knownTotalCost, 0) !== b.knownTotalCost ||
|
||||
b.costByPayer[member].knownTotalCost !== b.knownSelfCost ||
|
||||
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].missingCount, 0) !== b.missingCostCount ||
|
||||
teamMemberKeys().reduce((total, key) => total + b.costByPayer[key].pendingCount, 0) !== b.pendingCostCount
|
||||
)
|
||||
fail();
|
||||
const recoveries = reportAfterSaleRecoveryCosts(r, b, fail);
|
||||
validatePoolMaterialCosts(b, recoveries, fail);
|
||||
validateOwnerAdvances(b, recoveries, fail);
|
||||
validateCurrentAccount(b, r.ownershipReceipts[member], fail);
|
||||
const difference = b.difference,
|
||||
equation = b.equation,
|
||||
settlement = b.settlement;
|
||||
if (
|
||||
!difference ||
|
||||
difference.amount !== b.netReceipts - b.sales ||
|
||||
typeof difference.reconciled !== 'boolean' ||
|
||||
!Array.isArray(difference.reasons) ||
|
||||
!difference.reasons.every(
|
||||
reason => reason && typeof reason.code === 'string' && typeof reason.text === 'string',
|
||||
)
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
!equation ||
|
||||
!['netReceipts', 'sales'].includes(equation.basis) ||
|
||||
equation.revenue !== (equation.basis === 'netReceipts' ? b.netReceipts : b.sales) ||
|
||||
equation.totalCost !== b.totalCost ||
|
||||
equation.profit !== b.profit ||
|
||||
typeof equation.complete !== 'boolean' ||
|
||||
(equation.complete &&
|
||||
(!money(equation.totalCost) ||
|
||||
!money(equation.profit) ||
|
||||
equation.revenue - equation.totalCost !== equation.profit))
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
!settlement ||
|
||||
typeof settlement.available !== 'boolean' ||
|
||||
settlement.basis !== 'cumulative-through-date' ||
|
||||
settlement.from !== r.from ||
|
||||
settlement.date !== r.date ||
|
||||
typeof settlement.partial !== 'boolean' ||
|
||||
!count(settlement.pendingCount) ||
|
||||
!count(settlement.legacyCount) ||
|
||||
typeof settlement.notice !== 'string' ||
|
||||
!Array.isArray(settlement.counterparts)
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
settlement.available
|
||||
? !count(settlement.dueOut) || !count(settlement.dueIn)
|
||||
: settlement.dueOut !== null || settlement.dueIn !== null
|
||||
)
|
||||
fail();
|
||||
const seen = new Set();
|
||||
for (const row of settlement.counterparts) {
|
||||
if (
|
||||
!row ||
|
||||
!teamMemberKeys().includes(row.member) ||
|
||||
row.member === member ||
|
||||
seen.has(row.member) ||
|
||||
typeof row.name !== 'string' ||
|
||||
!row.name ||
|
||||
!['dueOut', 'dueIn', 'offset'].every(key => count(row[key])) ||
|
||||
!['openingDue', 'periodNew', 'periodTransferred', 'closingDue'].every(key => money(row[key])) ||
|
||||
row.openingDue + row.periodNew - row.periodTransferred !== row.closingDue ||
|
||||
row.dueOut !== Math.max(0, row.closingDue) ||
|
||||
row.dueIn !== Math.max(0, -row.closingDue) ||
|
||||
!row.period ||
|
||||
row.period.obligationNet !== row.periodNew ||
|
||||
row.period.transferred !== row.periodTransferred ||
|
||||
!money(row.period.receivedForNet) ||
|
||||
!money(row.period.advancedNet) ||
|
||||
row.period.receivedForNet + row.period.advancedNet !== row.periodNew
|
||||
)
|
||||
fail();
|
||||
seen.add(row.member);
|
||||
}
|
||||
if (
|
||||
settlement.available &&
|
||||
['dueOut', 'dueIn'].some(
|
||||
key => settlement.counterparts.reduce((total, row) => total + row[key], 0) !== settlement[key],
|
||||
)
|
||||
)
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
function validateDailyProfits(r) {
|
||||
const fail = () => {
|
||||
throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');
|
||||
},
|
||||
table = r.dailyProfits,
|
||||
money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value),
|
||||
members = teamDataKeys(r.ownershipReceipts);
|
||||
const amounts = ['sales', 'knownTotalCost', 'knownProfit'],
|
||||
counts = ['recordCount', 'orderCount', 'afterSaleCount', 'draftCount', 'unknownCostCount', 'unknownProfitCount'];
|
||||
const valid = row =>
|
||||
row &&
|
||||
amounts.every(key => money(row[key])) &&
|
||||
counts.every(key => count(row[key])) &&
|
||||
nullable(row.totalCost) &&
|
||||
nullable(row.profit) &&
|
||||
typeof row.incomplete === 'boolean' &&
|
||||
row.recordCount === row.orderCount + row.afterSaleCount &&
|
||||
row.draftCount <= row.orderCount &&
|
||||
row.unknownCostCount <= row.recordCount &&
|
||||
row.unknownProfitCount <= row.recordCount &&
|
||||
row.totalCost === (row.unknownCostCount ? null : row.knownTotalCost) &&
|
||||
row.profit === (row.unknownProfitCount ? null : row.knownProfit) &&
|
||||
(row.unknownCostCount || row.unknownProfitCount ? row.incomplete : true) &&
|
||||
(row.profit === null || (row.totalCost !== null && row.sales - row.totalCost === row.profit));
|
||||
if (
|
||||
!table ||
|
||||
table.basis !== 'orderDate' ||
|
||||
table.from !== r.from ||
|
||||
table.date !== r.date ||
|
||||
!Array.isArray(table.rows) ||
|
||||
!valid(table.summary)
|
||||
)
|
||||
fail();
|
||||
let previousDate = '',
|
||||
previousIndex = -1;
|
||||
for (const row of table.rows) {
|
||||
if (
|
||||
!valid(row) ||
|
||||
!row.recordCount ||
|
||||
!members.includes(row.member) ||
|
||||
typeof row.name !== 'string' ||
|
||||
!row.name ||
|
||||
!validOrderDate(row.date) ||
|
||||
row.date < r.from ||
|
||||
row.date > r.date
|
||||
)
|
||||
fail();
|
||||
const index = teamMemberKeys().indexOf(row.member);
|
||||
if (row.date < previousDate || (row.date === previousDate && index <= previousIndex)) fail();
|
||||
previousDate = row.date;
|
||||
previousIndex = index;
|
||||
}
|
||||
if (
|
||||
[...amounts, ...counts].some(key => table.rows.reduce((sum, row) => sum + row[key], 0) !== table.summary[key]) ||
|
||||
table.rows.some(row => row.incomplete) !== table.summary.incomplete ||
|
||||
table.summary.sales !== r.summary.sale ||
|
||||
table.summary.knownTotalCost !== r.summary.totalCost ||
|
||||
table.summary.knownProfit !== r.summary.profit ||
|
||||
table.summary.recordCount !== r.orderRows.length ||
|
||||
table.summary.unknownProfitCount !== (r.summary.unknownProfitCount || 0) + (r.summary.draftCount || 0) ||
|
||||
table.summary.unknownCostCount !== (r.summary.unknownCostCount || 0) + (r.summary.draftCount || 0)
|
||||
)
|
||||
fail();
|
||||
}
|
||||
|
||||
function validateTeamFunds(report) {
|
||||
const money = value => Number.isSafeInteger(value);
|
||||
if (
|
||||
!report ||
|
||||
!Array.isArray(report.pairs) ||
|
||||
!Array.isArray(report.balances) ||
|
||||
!Array.isArray(report.transfers) ||
|
||||
report.revision == null ||
|
||||
!validOrderDate(report.from) ||
|
||||
!validOrderDate(report.to)
|
||||
)
|
||||
throw new Error('团队账目未完整返回,请重新读取。');
|
||||
for (const pair of report.pairs) {
|
||||
if (
|
||||
!pair ||
|
||||
!Array.isArray(pair.members) ||
|
||||
pair.members.length !== 2 ||
|
||||
pair.members[0] === pair.members[1] ||
|
||||
!pair.members.every(member => teamMemberKeys().includes(member)) ||
|
||||
!['net', 'obligationNet', 'transferred', 'due'].every(key => money(pair[key])) ||
|
||||
pair.due < 0 ||
|
||||
Math.abs(pair.net) !== pair.due ||
|
||||
!Array.isArray(pair.entries)
|
||||
)
|
||||
throw new Error('两人往来金额未完整返回,请重新读取。');
|
||||
if (state.user.role !== 'owner' && !pair.members.includes(currentMember()))
|
||||
throw new Error('返回了其他成员的往来,请重新登录。');
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
function validateReimbursement(row) {
|
||||
if (
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
!row.id ||
|
||||
!validOrderDate(row.date) ||
|
||||
!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 reportAfterSaleRecoveryCosts(r, b, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
items = [],
|
||||
byPayer = Object.fromEntries(teamMemberKeys().map(key => [key, 0]));
|
||||
const identity = item =>
|
||||
JSON.stringify([item.component, item.payer, item.amount, item.source, item.materialPoolId ?? null]);
|
||||
for (const row of r.orderRows.filter(
|
||||
row => row.kind === 'orderAfterSale' && (row.member ?? (teamMode() ? null : 'assistant')) === b.member,
|
||||
)) {
|
||||
const record = row.orderAfterSale,
|
||||
summary = record?.summary,
|
||||
original = record?.originalOrder ?? record?.original,
|
||||
expected = [];
|
||||
if (
|
||||
row.status !== 'after_sale' ||
|
||||
!validOrderDate(row.date) ||
|
||||
row.date < b.from ||
|
||||
row.date > b.date ||
|
||||
record?.date !== row.date ||
|
||||
(record.order_id ?? record.orderId) !== (row.order_id ?? row.id) ||
|
||||
!summary ||
|
||||
!Array.isArray(summary.lines) ||
|
||||
!summary.lines.length ||
|
||||
!Array.isArray(row.costItems) ||
|
||||
!count(summary.materialReturnedCost) ||
|
||||
!count(summary.laborRestockedCost)
|
||||
)
|
||||
fail();
|
||||
for (const line of summary.lines) {
|
||||
if (!line || !count(line.lineIndex) || typeof line.name !== 'string') fail();
|
||||
for (const [component, key, totalKey] of [
|
||||
['material', 'materialAllocations', 'materialReturnedCost'],
|
||||
['labor', 'restockedLaborAllocations', 'laborRestockedCost'],
|
||||
]) {
|
||||
const parts = line[key];
|
||||
if (
|
||||
!Array.isArray(parts) ||
|
||||
!count(line[totalKey]) ||
|
||||
parts.some(part => !part || !teamMemberKeys().includes(part.payer) || !count(part.amount)) ||
|
||||
parts.reduce((sum, part) => sum + part.amount, 0) !== line[totalKey]
|
||||
)
|
||||
fail();
|
||||
for (const part of parts)
|
||||
if (part.amount)
|
||||
expected.push({
|
||||
component,
|
||||
payer: part.payer,
|
||||
amount: -part.amount,
|
||||
source: `商品 ${line.lineIndex + 1} · ${line.name}`,
|
||||
materialPoolId: component === 'material' ? row.date : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
['materialReturnedCost', 'laborRestockedCost'].some(
|
||||
key => summary.lines.reduce((sum, line) => sum + line[key], 0) !== summary[key],
|
||||
)
|
||||
)
|
||||
fail();
|
||||
const recovered = row.costItems.filter(item => item?.nonCash === true),
|
||||
actual = recovered.map(identity).sort(),
|
||||
wanted = expected.map(identity).sort();
|
||||
if (
|
||||
actual.length !== wanted.length ||
|
||||
actual.some((value, index) => value !== wanted[index]) ||
|
||||
row.costItems.some(
|
||||
item =>
|
||||
!item ||
|
||||
!teamMemberKeys().includes(item.payer) ||
|
||||
!money(item.amount) ||
|
||||
(item.nonCash === true
|
||||
? item.kind !== 'goods' || item.amount >= 0
|
||||
: item.kind !== 'paid' || item.component !== 'fee' || item.afterSaleExpense !== true || item.amount < 0),
|
||||
) ||
|
||||
row.costItems.reduce((sum, item) => sum + item.amount, 0) !== row.known?.totalCost ||
|
||||
row.totalCost !== row.known.totalCost ||
|
||||
!money(original?.total) ||
|
||||
!money(summary.retainedAmount) ||
|
||||
row.sale !== summary.retainedAmount - original.total ||
|
||||
!money(row.profit) ||
|
||||
row.profit !== summary.profitAdjustment ||
|
||||
row.sale - row.totalCost !== row.profit
|
||||
)
|
||||
fail();
|
||||
for (const item of recovered) {
|
||||
byPayer[item.payer] += item.amount;
|
||||
items.push({
|
||||
...item,
|
||||
id: row.id,
|
||||
date: row.date,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
byPayer,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
function validatePoolMaterialCosts(b, recoveries, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || count(value),
|
||||
pool = b.poolMaterial;
|
||||
const valid = value =>
|
||||
value &&
|
||||
['mg', 'knownAmount', 'missingCount'].every(key => count(value[key])) &&
|
||||
nullable(value.amount) &&
|
||||
value.amount === (value.missingCount ? null : value.knownAmount) &&
|
||||
value.byPayer &&
|
||||
Object.keys(value.byPayer).length === teamMemberKeys().length &&
|
||||
teamMemberKeys().every(key => {
|
||||
const payer = value.byPayer[key];
|
||||
return (
|
||||
payer &&
|
||||
count(payer.knownAmount) &&
|
||||
nullable(payer.amount) &&
|
||||
payer.amount === (value.missingCount ? null : payer.knownAmount)
|
||||
);
|
||||
}) &&
|
||||
teamMemberKeys().reduce((sum, key) => sum + value.byPayer[key].knownAmount, 0) === value.knownAmount;
|
||||
if (
|
||||
!valid(pool) ||
|
||||
typeof pool.hasPriceLocks !== 'boolean' ||
|
||||
!Array.isArray(pool.days) ||
|
||||
pool.missingCount > b.missingCostCount ||
|
||||
!pool.otherCosts ||
|
||||
!money(pool.otherCosts.knownAmount) ||
|
||||
!(pool.otherCosts.amount === null || money(pool.otherCosts.amount)) ||
|
||||
(pool.otherCosts.amount !== null && pool.otherCosts.amount !== pool.otherCosts.knownAmount)
|
||||
)
|
||||
fail();
|
||||
const seen = new Set();
|
||||
for (const day of pool.days) {
|
||||
if (
|
||||
!valid(day) ||
|
||||
day.mg <= 0 ||
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day.poolId) ||
|
||||
day.date !== day.poolId ||
|
||||
!nullable(day.averageRate)
|
||||
)
|
||||
fail();
|
||||
if (day.sources !== undefined) {
|
||||
if (
|
||||
!Array.isArray(day.sources) ||
|
||||
!day.sources.length ||
|
||||
day.sources.some(
|
||||
source =>
|
||||
!source ||
|
||||
!['public', 'personal_recovery'].includes(source.kind) ||
|
||||
(source.kind === 'personal_recovery'
|
||||
? !teamMemberKeys().includes(source.member)
|
||||
: source.member !== null) ||
|
||||
typeof source.priceLocked !== 'boolean' ||
|
||||
!count(source.mg) ||
|
||||
source.mg <= 0 ||
|
||||
!nullable(source.averageRate) ||
|
||||
!count(source.knownAmount) ||
|
||||
!count(source.missingCount) ||
|
||||
!nullable(source.amount) ||
|
||||
source.amount !== (source.missingCount ? null : source.knownAmount),
|
||||
) ||
|
||||
day.sources.reduce((sum, source) => sum + source.mg, 0) !== day.mg ||
|
||||
day.sources.reduce((sum, source) => sum + source.knownAmount, 0) < day.knownAmount ||
|
||||
(!day.missingCount &&
|
||||
(day.sources.some(source => source.missingCount) ||
|
||||
day.sources.reduce((sum, source) => sum + source.knownAmount, 0) !== day.knownAmount)) ||
|
||||
day.averageRate !== (day.sources.length === 1 ? day.sources[0].averageRate : null)
|
||||
)
|
||||
fail();
|
||||
}
|
||||
const key = day.poolId + ':' + (day.sources ? 'sources' : day.averageRate);
|
||||
if (seen.has(key)) fail();
|
||||
seen.add(key);
|
||||
}
|
||||
if (
|
||||
['mg', 'knownAmount', 'missingCount'].some(
|
||||
key => pool.days.reduce((sum, day) => sum + day[key], 0) !== pool[key],
|
||||
) ||
|
||||
teamMemberKeys().some(
|
||||
key =>
|
||||
pool.days.reduce((sum, day) => sum + day.byPayer[key].knownAmount, 0) !== pool.byPayer[key].knownAmount ||
|
||||
pool.byPayer[key].knownAmount > b.costByPayer[key].knownTotalCost - recoveries.byPayer[key],
|
||||
) ||
|
||||
pool.otherCosts.knownAmount - teamMemberKeys().reduce((sum, key) => sum + recoveries.byPayer[key], 0) < 0 ||
|
||||
pool.knownAmount + pool.otherCosts.knownAmount !== b.knownTotalCost ||
|
||||
(b.totalCost !== null &&
|
||||
(pool.amount === null ||
|
||||
pool.otherCosts.amount === null ||
|
||||
pool.amount + pool.otherCosts.amount !== b.totalCost))
|
||||
)
|
||||
fail();
|
||||
}
|
||||
|
||||
function validateOwnerAdvances(b, recoveries, fail) {
|
||||
const money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value),
|
||||
advances = b.ownerAdvances;
|
||||
const identity = item =>
|
||||
JSON.stringify([
|
||||
item.id,
|
||||
item.date,
|
||||
item.component,
|
||||
item.source,
|
||||
item.poolId ?? item.materialPoolId ?? null,
|
||||
item.amount,
|
||||
]),
|
||||
remaining = recoveries.items.filter(item => item.payer === 'owner').map(identity);
|
||||
if (
|
||||
!advances ||
|
||||
advances.basis !== 'orderDate' ||
|
||||
advances.from !== b.from ||
|
||||
advances.date !== b.date ||
|
||||
!Array.isArray(advances.days)
|
||||
)
|
||||
fail();
|
||||
let previous = '',
|
||||
knownTotal = 0;
|
||||
for (const day of advances.days) {
|
||||
if (
|
||||
!day ||
|
||||
typeof day.date !== 'string' ||
|
||||
day.date < b.from ||
|
||||
day.date > b.date ||
|
||||
day.date <= previous ||
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(day.date) ||
|
||||
!Array.isArray(day.items) ||
|
||||
!day.items.length ||
|
||||
!['knownAmount', 'knownPoolAmount', 'knownOtherAmount'].every(key => money(day[key])) ||
|
||||
!['missingCount', 'pendingCount'].every(key => count(day[key])) ||
|
||||
!['amount', 'poolAmount', 'otherAmount'].every(key => nullable(day[key]))
|
||||
)
|
||||
fail();
|
||||
for (const item of day.items) {
|
||||
if (
|
||||
!item ||
|
||||
item.date !== day.date ||
|
||||
!['order', 'afterSale'].includes(item.kind) ||
|
||||
!['id', 'number', 'paperNumber', 'customer', 'name', 'source', 'component'].every(
|
||||
key => typeof item[key] === 'string',
|
||||
) ||
|
||||
!item.id ||
|
||||
!item.name ||
|
||||
typeof item.poolMaterial !== 'boolean' ||
|
||||
typeof item.allocationPending !== 'boolean' ||
|
||||
item.poolMaterial !== (item.poolId !== null) ||
|
||||
(item.poolId !== null && !/^\d{4}-\d{2}-\d{2}$/.test(item.poolId)) ||
|
||||
!['recorded', 'missing', 'pending'].includes(item.status) ||
|
||||
!nullable(item.amount) ||
|
||||
!nullable(item.estimatedAmount)
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
(item.nonCash !== undefined && typeof item.nonCash !== 'boolean') ||
|
||||
(item.estimatedAmount !== null && item.estimatedAmount < 0) ||
|
||||
(item.status === 'recorded'
|
||||
? item.amount === null || item.amount === 0 || item.estimatedAmount !== null || item.allocationPending
|
||||
: item.amount !== null ||
|
||||
(item.status === 'missing' && item.estimatedAmount !== null) ||
|
||||
(item.allocationPending && (!item.poolMaterial || item.status !== 'missing')))
|
||||
)
|
||||
fail();
|
||||
if (item.amount < 0 || item.nonCash === true) {
|
||||
const index = remaining.indexOf(identity(item));
|
||||
if (
|
||||
item.kind !== 'order' ||
|
||||
item.status !== 'recorded' ||
|
||||
item.nonCash !== true ||
|
||||
item.amount >= 0 ||
|
||||
index < 0
|
||||
)
|
||||
fail();
|
||||
remaining.splice(index, 1);
|
||||
}
|
||||
}
|
||||
const recorded = day.items.filter(item => item.status === 'recorded'),
|
||||
missing = day.items.filter(item => item.status === 'missing'),
|
||||
total = rows => rows.reduce((sum, item) => sum + item.amount, 0),
|
||||
poolMissing = missing.some(item => item.poolMaterial),
|
||||
otherMissing = missing.some(item => !item.poolMaterial);
|
||||
if (
|
||||
day.knownAmount !== total(recorded) ||
|
||||
day.knownPoolAmount !== total(recorded.filter(item => item.poolMaterial)) ||
|
||||
day.knownOtherAmount !== day.knownAmount - day.knownPoolAmount ||
|
||||
day.missingCount !== missing.length ||
|
||||
day.pendingCount !== day.items.filter(item => item.status === 'pending').length ||
|
||||
day.amount !== (missing.length ? null : day.knownAmount) ||
|
||||
day.poolAmount !== (poolMissing ? null : day.knownPoolAmount) ||
|
||||
day.otherAmount !== (otherMissing ? null : day.knownOtherAmount)
|
||||
)
|
||||
fail();
|
||||
previous = day.date;
|
||||
knownTotal += day.knownAmount;
|
||||
}
|
||||
if (remaining.length || knownTotal > b.costByPayer.owner.knownTotalCost) fail();
|
||||
}
|
||||
|
||||
function validateCurrentAccount(b, income, fail) {
|
||||
const account = b.currentAccount,
|
||||
money = Number.isSafeInteger,
|
||||
count = value => money(value) && value >= 0,
|
||||
nullable = value => value === null || money(value);
|
||||
if (
|
||||
!account ||
|
||||
account.basis !== 'orderDate' ||
|
||||
account.from !== b.from ||
|
||||
account.date !== b.date ||
|
||||
!Array.isArray(account.days)
|
||||
)
|
||||
fail();
|
||||
const ownerAccounts = new Set(income.accounts.filter(row => row.recipient === 'owner').map(row => row.account)),
|
||||
received = new Map();
|
||||
for (const item of income.items) {
|
||||
const date = item.price_lock_id || item.order_after_sale ? item.date : item.order_date;
|
||||
if (!date || date < b.from || date > b.date) continue;
|
||||
if (ownerAccounts.has(item.account))
|
||||
received.set(date, (received.get(date) || 0) + (item.kind === 'receipt' ? item.amount : -item.amount));
|
||||
}
|
||||
const seen = new Set();
|
||||
let previous = '';
|
||||
for (const day of account.days) {
|
||||
if (
|
||||
!day ||
|
||||
!validOrderDate(day.date) ||
|
||||
day.date < b.from ||
|
||||
day.date > b.date ||
|
||||
day.date <= previous ||
|
||||
!['recordCount', 'missingCostCount', 'pendingCostCount', 'unknownProfitCount'].every(key => count(day[key])) ||
|
||||
!['knownMaterialCost', 'knownOtherCost', 'knownProfit', 'ownerNetReceipts', 'knownAmount'].every(key =>
|
||||
money(day[key]),
|
||||
) ||
|
||||
!['materialCost', 'otherCost', 'profit', 'amount'].every(key => nullable(day[key])) ||
|
||||
typeof day.incomplete !== 'boolean'
|
||||
)
|
||||
fail();
|
||||
if (
|
||||
(day.materialCost !== null && day.materialCost !== day.knownMaterialCost) ||
|
||||
(day.otherCost !== null && day.otherCost !== day.knownOtherCost) ||
|
||||
day.profit !== (day.unknownProfitCount ? null : day.knownProfit) ||
|
||||
day.knownAmount !== day.knownMaterialCost + day.knownOtherCost + day.knownProfit - day.ownerNetReceipts ||
|
||||
day.amount !== (day.incomplete ? null : day.knownAmount) ||
|
||||
((day.missingCostCount || day.pendingCostCount || day.unknownProfitCount) && !day.incomplete) ||
|
||||
day.ownerNetReceipts !== (received.get(day.date) || 0)
|
||||
)
|
||||
fail();
|
||||
const advance = b.ownerAdvances.days.find(row => row.date === day.date),
|
||||
items = advance?.items || [],
|
||||
recorded = items.filter(item => item.status === 'recorded');
|
||||
const material = rows => rows.filter(item => item.component === 'material'),
|
||||
other = rows => rows.filter(item => item.component !== 'material'),
|
||||
sum = rows => rows.reduce((total, item) => total + item.amount, 0),
|
||||
missing = items.filter(item => item.status === 'missing');
|
||||
if (
|
||||
day.knownMaterialCost !== sum(material(recorded)) ||
|
||||
day.knownOtherCost !== sum(other(recorded)) ||
|
||||
day.materialCost !== (material(missing).length ? null : day.knownMaterialCost) ||
|
||||
day.otherCost !== (other(missing).length ? null : day.knownOtherCost) ||
|
||||
day.missingCostCount !== (advance?.missingCount || 0) ||
|
||||
day.pendingCostCount !== (advance?.pendingCount || 0)
|
||||
)
|
||||
fail();
|
||||
seen.add(day.date);
|
||||
previous = day.date;
|
||||
}
|
||||
if (
|
||||
[...received.keys(), ...b.ownerAdvances.days.map(day => day.date)].some(date => !seen.has(date)) ||
|
||||
account.days.reduce((sum, day) => sum + day.knownProfit, 0) !== b.knownProfit ||
|
||||
account.days.reduce((sum, day) => sum + day.unknownProfitCount, 0) !== b.unknownProfitCount ||
|
||||
account.days.reduce((sum, day) => sum + day.recordCount, 0) !== b.recordCount ||
|
||||
account.days.some(day => day.incomplete) !== b.incomplete
|
||||
)
|
||||
fail();
|
||||
}
|
||||
return { validateDailyFunds, validateReport, validateDailyReimbursements };
|
||||
}
|
||||
Reference in new issue
Block a user