保存工作区合并前的本地开发现场 ledger-migration-typed-54c0587
This commit is contained in:
1 parent
54c05879d5
commit
d18273ac37
82 files changed
+8878
-4757
No files matched your search
+122
-31
@@ -1,28 +1,96 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { FormEvent, RefObject } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { LedgerState } from '../../shared';
|
||||
import type {
|
||||
DailyFunds,
|
||||
ReportQuery,
|
||||
Range,
|
||||
ReportAction,
|
||||
ReimbursementList,
|
||||
Reimbursement,
|
||||
ReimbursementItem,
|
||||
Confirmation,
|
||||
} from './contracts';
|
||||
import type { reportPresentation } from './presentation';
|
||||
import { useEffect, useEffectEvent, useLayoutEffect, 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) {
|
||||
type View = ReturnType<typeof reportPresentation>;
|
||||
type DraftItem = Omit<ReimbursementItem, 'amount'> & { amount: string };
|
||||
interface Draft {
|
||||
id: string;
|
||||
revision?: number;
|
||||
date: string;
|
||||
items: DraftItem[];
|
||||
payer?: string;
|
||||
note: string;
|
||||
}
|
||||
interface Review {
|
||||
id: string;
|
||||
revision: number;
|
||||
kind: 'approve' | 'reject';
|
||||
note: string;
|
||||
verified: boolean;
|
||||
}
|
||||
interface Outlay {
|
||||
amount: string;
|
||||
note: string;
|
||||
verified: boolean;
|
||||
editing: boolean;
|
||||
revision: number;
|
||||
sourceRevision: string;
|
||||
}
|
||||
interface Drafts {
|
||||
user: string;
|
||||
forms: Map<string, Draft>;
|
||||
editors: Map<string, string>;
|
||||
reviews: Map<string, Review>;
|
||||
outlays: Map<string, Outlay>;
|
||||
}
|
||||
interface Props {
|
||||
client: LedgerClient;
|
||||
state: LedgerState;
|
||||
view: View;
|
||||
data: DailyFunds;
|
||||
query: ReportQuery & Range;
|
||||
changeDate: (date: string, reviewId?: string) => void;
|
||||
reload: () => void;
|
||||
notify: (text: string, error?: boolean) => void;
|
||||
actionRef: RefObject<((data: ReportAction) => void) | null>;
|
||||
}
|
||||
interface PageReply {
|
||||
query: { offset: number };
|
||||
list?: ReimbursementList;
|
||||
error?: string;
|
||||
}
|
||||
type FormKind = 'outlay' | 'draft' | 'review';
|
||||
type FormError = { kind: FormKind; text: string; conflict?: boolean };
|
||||
const draftsByClient = new WeakMap<LedgerClient, Drafts>();
|
||||
function draftsFor(client: LedgerClient, user: string) {
|
||||
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() };
|
||||
const drafts: Drafts = { user, forms: new Map(), editors: new Map(), reviews: new Map(), outlays: new Map() };
|
||||
draftsByClient.set(client, drafts);
|
||||
return drafts;
|
||||
}
|
||||
function newItem(team) {
|
||||
function newItem(team: boolean): DraftItem {
|
||||
return {
|
||||
name: '',
|
||||
amount: '',
|
||||
...(team ? { member: 'owner', sourceType: 'independent', sourceKey: crypto.randomUUID() } : {}),
|
||||
};
|
||||
}
|
||||
function PendingList({ client, view, close, openDate }) {
|
||||
function PendingList({
|
||||
client,
|
||||
view,
|
||||
close,
|
||||
openDate,
|
||||
}: Pick<Props, 'client' | 'view'> & { close: () => void; openDate: (row: Reimbursement) => void }) {
|
||||
const [query, setQuery] = useState({ offset: 0 }),
|
||||
[result, setResult] = useState(null);
|
||||
const validate = useRef(view.validateDailyReimbursements);
|
||||
validate.current = view.validateDailyReimbursements;
|
||||
[result, setResult] = useState<PageReply | null>(null);
|
||||
const validate = useEffectEvent((data: unknown) => view.validateDailyReimbursements(data));
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
client
|
||||
@@ -30,7 +98,7 @@ function PendingList({ client, view, close, openDate }) {
|
||||
'/api/reimbursements?' + new URLSearchParams({ status: 'pending', limit: '50', offset: String(query.offset) }),
|
||||
)
|
||||
.then(data => {
|
||||
const list = validate.current(data);
|
||||
const list = validate(data);
|
||||
if (current) setResult({ query, list });
|
||||
})
|
||||
.catch(error => {
|
||||
@@ -134,27 +202,29 @@ function PendingList({ client, view, close, openDate }) {
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }) {
|
||||
export function Reimbursements({ client, state, view, data, query, changeDate, reload, notify, actionRef }: Props) {
|
||||
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);
|
||||
[error, setError] = useState<FormError | null>(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),
|
||||
draft = formKey ? cache.forms.get(formKey) : undefined,
|
||||
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;
|
||||
memberName = (id?: string) => (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;
|
||||
useLayoutEffect(() => {
|
||||
currentView.current = key;
|
||||
}, [key]);
|
||||
const out = cache.outlays.get(key);
|
||||
useEffect(() => {
|
||||
if (!data) return;
|
||||
@@ -187,9 +257,9 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
}
|
||||
redraw();
|
||||
}, [data, key, cache, owner, query.month, query.reviewId]);
|
||||
function action({ action, id, date }) {
|
||||
function action({ action, id, date }: ReportAction) {
|
||||
if (action === 'daily-funds-open-date') {
|
||||
changeDate(date);
|
||||
if (date) changeDate(date);
|
||||
return;
|
||||
}
|
||||
if (action === 'reimbursement-open-list') {
|
||||
@@ -223,7 +293,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
if (action === 'reimbursement-approve' || action === 'reimbursement-reject') {
|
||||
if (!owner || !record?.canApprove || record.status !== 'pending') return;
|
||||
cache.reviews.set(key, {
|
||||
id,
|
||||
id: record.id,
|
||||
revision: record.revision,
|
||||
kind: action === 'reimbursement-approve' ? 'approve' : 'reject',
|
||||
note: '',
|
||||
@@ -243,14 +313,24 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
actionRef.current = null;
|
||||
};
|
||||
});
|
||||
function set(obj, field, value) {
|
||||
function set<O, K extends keyof O>(obj: O, field: K, value: O[K]) {
|
||||
obj[field] = value;
|
||||
redraw();
|
||||
}
|
||||
async function submit(event, kind) {
|
||||
async function submit(event: FormEvent, kind: FormKind) {
|
||||
event.preventDefault();
|
||||
if (blocked || month) return;
|
||||
let url, input, notice;
|
||||
let url: string, notice: string;
|
||||
let input: {
|
||||
date?: string;
|
||||
revision?: number;
|
||||
note: string;
|
||||
verified?: boolean;
|
||||
amount?: string;
|
||||
sourceRevision?: string;
|
||||
payer?: string;
|
||||
items?: DraftItem[];
|
||||
};
|
||||
try {
|
||||
if (kind === 'outlay') {
|
||||
if (!owner || !out) throw new Error('完整支出由店主确认。');
|
||||
@@ -305,7 +385,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
};
|
||||
notice = '报销单已提交,等待店主复核';
|
||||
} else {
|
||||
if (!owner || !row?.canApprove || row.status !== 'pending' || row.revision !== review.revision)
|
||||
if (!review || !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))
|
||||
@@ -321,13 +401,23 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
: '报销已批准,已计入报销日期的应转合计';
|
||||
}
|
||||
setError(null);
|
||||
const result = await client.mutate(url, input);
|
||||
if (kind === 'draft') {
|
||||
const result = await client.mutate<{
|
||||
confirmation?: Pick<Confirmation, 'revision' | 'sourceRevision'>;
|
||||
reimbursement?: { date: string };
|
||||
date?: string;
|
||||
}>(url, input);
|
||||
if (kind === 'draft' && formKey) {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
if (kind === 'review') cache.reviews.delete(key);
|
||||
if (kind === 'outlay') {
|
||||
if (kind === 'outlay' && out) {
|
||||
if (
|
||||
!result.confirmation ||
|
||||
!Number.isSafeInteger(result.confirmation.revision) ||
|
||||
typeof result.confirmation.sourceRevision !== 'string'
|
||||
)
|
||||
throw new Error('实际支出已提交,确认回执未完整返回,请重新读取后核对。');
|
||||
out.editing = false;
|
||||
out.verified = false;
|
||||
out.revision = result.confirmation.revision;
|
||||
@@ -338,15 +428,16 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
notify(notice + (date && date !== query.date ? '(' + date + ')' : ''));
|
||||
} catch (err) {
|
||||
if (currentView.current !== key) return;
|
||||
setError({ kind, text: errorText(err), conflict: err.status === 409 });
|
||||
const conflict = err instanceof Error && 'status' in err && err.status === 409;
|
||||
setError({ kind, text: errorText(err), conflict });
|
||||
notify(errorText(err), true);
|
||||
if (err.status === 409) {
|
||||
if (conflict) {
|
||||
if (review) review.verified = false;
|
||||
reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
const errBox = (id, kind) => (
|
||||
const errBox = (id: string, kind: FormKind) => (
|
||||
<div id={id} aria-live="polite">
|
||||
{error?.kind === kind && (
|
||||
<div className="error">
|
||||
@@ -357,7 +448,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
onClick={async () => {
|
||||
try {
|
||||
await client.retryPending();
|
||||
if (kind === 'draft') {
|
||||
if (kind === 'draft' && formKey) {
|
||||
cache.forms.delete(formKey);
|
||||
cache.editors.delete(key);
|
||||
}
|
||||
@@ -382,7 +473,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
const btn = (text, name, primary = false) => (
|
||||
const btn = (text: string, name: string, primary = false) => (
|
||||
<Button
|
||||
className={primary ? 'primary' : 'quiet'}
|
||||
action={name}
|
||||
@@ -392,7 +483,7 @@ export function Reimbursements({ client, state, view, data, query, changeDate, r
|
||||
{text}
|
||||
</Button>
|
||||
);
|
||||
const total = draft ? view.reimbursementDraftTotal(draft.items) : null;
|
||||
const total = view.reimbursementDraftTotal(draft?.items ?? []);
|
||||
return (
|
||||
<>
|
||||
{!team && (
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
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;
|
||||
+42
-26
@@ -1,4 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { LedgerClient } from '../../lib/api';
|
||||
import type { ReportContext, ReportQuery, ReportAction, Report, Range } from './contracts';
|
||||
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { navigate } from '../../lib/router';
|
||||
import { useClientSnapshot } from '../../lib/useClient';
|
||||
import { Button, Choice } from '../Settings/controls';
|
||||
@@ -7,20 +9,24 @@ import { reportPresentation } from './presentation';
|
||||
import { Reimbursements } from './Reimbursements';
|
||||
import './report.css';
|
||||
|
||||
const savedQueries = new WeakMap();
|
||||
export function ReportPage({ client, state, session }) {
|
||||
type ReportProps = Pick<ReportContext, 'state' | 'session'> & { client: LedgerClient };
|
||||
type Reply = { query: ReportQuery; version: number } & (
|
||||
{ error: string; data?: never; fundsError?: never } | { data: Report; fundsError: string; error?: never }
|
||||
);
|
||||
const savedQueries = new WeakMap<LedgerClient, Map<string, ReportQuery>>();
|
||||
export function ReportPage({ client, state, session }: ReportProps) {
|
||||
useClientSnapshot(client);
|
||||
const user = state.user.id;
|
||||
const [query, setQuery] = useState(
|
||||
const [query, setQuery] = useState<ReportQuery>(
|
||||
() => 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);
|
||||
[reply, setReply] = useState<Reply | null>(null),
|
||||
[notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
|
||||
const daily = useRef<((value: ReportAction) => void) | null>(null),
|
||||
actions = useRef<((value: ReportAction) => void) | null>(null);
|
||||
const reload = useCallback(() => setVersion(v => v + 1), []);
|
||||
const dispatch = useCallback(data => actions.current(data), []);
|
||||
const dispatch = useCallback((data: ReportAction) => actions.current?.(data), []);
|
||||
const view = reportPresentation({
|
||||
state,
|
||||
session,
|
||||
@@ -28,16 +34,16 @@ export function ReportPage({ client, state, session }) {
|
||||
reportMember: query.member,
|
||||
onAction: dispatch,
|
||||
});
|
||||
const viewRef = useRef(view);
|
||||
viewRef.current = view;
|
||||
const currentModel = useEffectEvent(() => 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 notify = (text: string, error = false) => setNotice({ text, error });
|
||||
const change = (d: Partial<ReportQuery>) => {
|
||||
const n = { ...query, reviewId: undefined, ...d };
|
||||
if (!savedQueries.has(client)) savedQueries.set(client, new Map());
|
||||
savedQueries.get(client).set(user, n);
|
||||
const queries = savedQueries.get(client) ?? new Map<string, ReportQuery>();
|
||||
queries.set(user, n);
|
||||
savedQueries.set(client, queries);
|
||||
setQuery(n);
|
||||
setNotice(null);
|
||||
};
|
||||
@@ -45,7 +51,7 @@ export function ReportPage({ client, state, session }) {
|
||||
let active = true;
|
||||
async function load() {
|
||||
try {
|
||||
const model = viewRef.current;
|
||||
const model: ReturnType<typeof reportPresentation> = currentModel();
|
||||
if (!model.validOrderDate(query.date)) throw new Error('请选择有效的对账日期。');
|
||||
if (query.date > state.today) throw new Error('请选择今天或之前的日期。');
|
||||
const data = await client.api(
|
||||
@@ -58,7 +64,8 @@ export function ReportPage({ client, state, session }) {
|
||||
}),
|
||||
);
|
||||
if (!active) return;
|
||||
model.validateReport(data, { from, date: query.date });
|
||||
const validate: (input: unknown, range: Range) => asserts input is Report = model.validateReport;
|
||||
validate(data, { from, date: query.date });
|
||||
let fundsError = '';
|
||||
try {
|
||||
model.validateDailyFunds(data.dailyFunds, { ...query, from });
|
||||
@@ -68,7 +75,11 @@ export function ReportPage({ client, state, session }) {
|
||||
setReply({ data, fundsError, query, version });
|
||||
} catch (err) {
|
||||
if (active)
|
||||
setReply({ error: err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err), query, version });
|
||||
setReply({
|
||||
error: err instanceof Error && err.name === 'AbortError' ? '读取超时,请重新读取。' : errorText(err),
|
||||
query,
|
||||
version,
|
||||
});
|
||||
}
|
||||
}
|
||||
void load();
|
||||
@@ -76,20 +87,23 @@ export function ReportPage({ client, state, session }) {
|
||||
active = false;
|
||||
};
|
||||
}, [client, state.today, state.user.role, user, from, query, version]);
|
||||
async function action({ action, id, date }) {
|
||||
async function action({ action, id, date }: ReportAction) {
|
||||
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 === 'open-order') return navigate('orders', { search: '?order=' + encodeURIComponent(String(id)) });
|
||||
if (action === 'after-sale-edit')
|
||||
return navigate('orders', { search: '?afterSale=' + encodeURIComponent(String(id)) });
|
||||
if (action === 'open-price-lock')
|
||||
return navigate('price-locks', { search: '?lock=' + encodeURIComponent(String(id)) });
|
||||
if (action === 'recovery-open')
|
||||
return navigate('recoveries', { search: '?recovery=' + encodeURIComponent(String(id)) });
|
||||
if (action === 'goto-material-pools')
|
||||
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(id) : '' });
|
||||
return navigate('material-pools', { search: id ? '?pool=' + encodeURIComponent(String(id)) : '' });
|
||||
if (action === 'recovery-print') {
|
||||
window.open('/print/recoveries/' + encodeURIComponent(id), '_blank', 'noopener');
|
||||
window.open('/print/recoveries/' + encodeURIComponent(String(id)), '_blank', 'noopener');
|
||||
notify('客户打印页已打开;若未出现,请允许此网站打开新窗口');
|
||||
return;
|
||||
}
|
||||
@@ -116,7 +130,9 @@ export function ReportPage({ client, state, session }) {
|
||||
notify(errorText(err), true);
|
||||
}
|
||||
}
|
||||
actions.current = action;
|
||||
useLayoutEffect(() => {
|
||||
actions.current = action;
|
||||
});
|
||||
return (
|
||||
<div
|
||||
className="report-page"
|
||||
@@ -0,0 +1,604 @@
|
||||
import type { LedgerState, SessionInfo } from '../../shared';
|
||||
|
||||
export interface Range {
|
||||
date: string;
|
||||
from: string;
|
||||
month?: boolean;
|
||||
}
|
||||
export interface ReportQuery {
|
||||
date: string;
|
||||
month: boolean;
|
||||
member: string;
|
||||
reviewId?: string;
|
||||
}
|
||||
export interface ReportContext {
|
||||
state: LedgerState;
|
||||
session: SessionInfo;
|
||||
reportMonth: boolean;
|
||||
reportMember: string;
|
||||
}
|
||||
export interface RuleContext {
|
||||
state: Pick<LedgerState, 'user'>;
|
||||
reportMember: string;
|
||||
teamDataKeys: (data: object) => string[];
|
||||
teamMode: () => boolean;
|
||||
currentMember: () => string;
|
||||
teamMemberKeys: () => string[];
|
||||
isReimbursementStatus: (status: string) => boolean;
|
||||
validOrderDate: (value: unknown) => boolean;
|
||||
}
|
||||
export interface ReportAction {
|
||||
action?: string;
|
||||
id?: string;
|
||||
date?: string;
|
||||
}
|
||||
export type Amount = number | null;
|
||||
export interface Receipts {
|
||||
receipt: number;
|
||||
refund: number;
|
||||
net: number;
|
||||
}
|
||||
export interface Account extends Receipts {
|
||||
account: string;
|
||||
recipient: string;
|
||||
channel: string;
|
||||
entryCount: number;
|
||||
}
|
||||
export interface ReceiptItem {
|
||||
id: string;
|
||||
kind: string;
|
||||
amount: number;
|
||||
account: string;
|
||||
date: string;
|
||||
order_id: string | null;
|
||||
order_date: string | null;
|
||||
price_lock_id: string | null;
|
||||
order_after_sale?: boolean;
|
||||
note?: string;
|
||||
paper_number?: string | null;
|
||||
number: string;
|
||||
reference?: string;
|
||||
customer: string;
|
||||
product?: string;
|
||||
}
|
||||
export interface MemberReceipts extends Receipts {
|
||||
name: string;
|
||||
items: ReceiptItem[];
|
||||
}
|
||||
export interface RecipientReceipts extends MemberReceipts {
|
||||
recipient: string;
|
||||
}
|
||||
export interface OwnershipReceipts extends MemberReceipts {
|
||||
member: string;
|
||||
accounts: Account[];
|
||||
}
|
||||
export interface CostItem {
|
||||
id: string;
|
||||
kind: string;
|
||||
name: string;
|
||||
source: string;
|
||||
amount: Amount;
|
||||
payer: string;
|
||||
date: string;
|
||||
number: string;
|
||||
paper_number?: string;
|
||||
customer: string;
|
||||
order_id?: string;
|
||||
price_lock_id?: string;
|
||||
component: string;
|
||||
materialPoolId?: string | null;
|
||||
nonCash?: boolean;
|
||||
afterSaleExpense?: boolean;
|
||||
paidDate?: string;
|
||||
after_sale_id?: string;
|
||||
pool_id?: string;
|
||||
product?: string;
|
||||
quantity?: number;
|
||||
calculation?: { rate: number; quantity: number; weighted?: boolean } | null;
|
||||
}
|
||||
export interface PayerCosts {
|
||||
name: string;
|
||||
goods: number;
|
||||
paidFees: number;
|
||||
total: number;
|
||||
missingCount: number;
|
||||
pendingCount: number;
|
||||
items: CostItem[];
|
||||
}
|
||||
export interface Allocation {
|
||||
payer: string;
|
||||
amount: number;
|
||||
}
|
||||
export interface ReturnedLine {
|
||||
lineIndex: number;
|
||||
name: string;
|
||||
materialAllocations: Allocation[];
|
||||
restockedLaborAllocations: Allocation[];
|
||||
materialReturnedCost: number;
|
||||
laborRestockedCost: number;
|
||||
}
|
||||
export interface OrderAfterSale {
|
||||
date: string;
|
||||
order_id?: string;
|
||||
orderId?: string;
|
||||
original: { total: number };
|
||||
originalOrder?: { total: number };
|
||||
summary: {
|
||||
lines: ReturnedLine[];
|
||||
materialReturnedCost: number;
|
||||
laborRestockedCost: number;
|
||||
retainedAmount: number;
|
||||
profitAdjustment: number;
|
||||
};
|
||||
}
|
||||
export interface Row {
|
||||
id: string;
|
||||
kind: string;
|
||||
member: string;
|
||||
date: string;
|
||||
status: string;
|
||||
order_date?: string;
|
||||
orderAfterSale: OrderAfterSale;
|
||||
sale: Amount;
|
||||
totalCost: Amount;
|
||||
profit: Amount;
|
||||
known: Record<string, number>;
|
||||
costItems: CostItem[];
|
||||
material: Amount;
|
||||
laborAndFees: Amount;
|
||||
number: string;
|
||||
paper_number?: string;
|
||||
customer: string;
|
||||
costHint?: string;
|
||||
note?: string;
|
||||
project?: string;
|
||||
order_id?: string;
|
||||
recovery_id?: string;
|
||||
recovery_mode?: string;
|
||||
cashPayment: number;
|
||||
payer?: string;
|
||||
after_sale_id?: string;
|
||||
price_lock_id?: string;
|
||||
}
|
||||
export interface Summary {
|
||||
orderCount: number;
|
||||
completedCount: number;
|
||||
returnedCount: number;
|
||||
cancelledCount: number;
|
||||
draftCount: number;
|
||||
afterSaleCount: number;
|
||||
sale: number;
|
||||
totalCost: number;
|
||||
profit: number;
|
||||
missingCosts: number;
|
||||
pendingCosts: number;
|
||||
unknownProfitCount: number;
|
||||
unknownCostCount: number;
|
||||
knownCounts: Record<string, number>;
|
||||
unknownCounts: Record<string, number>;
|
||||
}
|
||||
export interface Profit {
|
||||
recordCount: number;
|
||||
orderCount: number;
|
||||
afterSaleCount: number;
|
||||
draftCount: number;
|
||||
unknownCostCount: number;
|
||||
unknownProfitCount: number;
|
||||
sales: number;
|
||||
knownTotalCost: number;
|
||||
knownProfit: number;
|
||||
incomplete: boolean;
|
||||
totalCost: Amount;
|
||||
profit: Amount;
|
||||
}
|
||||
export interface ProfitRow extends Profit {
|
||||
name: string;
|
||||
member: string;
|
||||
date: string;
|
||||
}
|
||||
export interface ProfitTable extends Range {
|
||||
basis: string;
|
||||
rows: ProfitRow[];
|
||||
summary: Profit;
|
||||
}
|
||||
export interface BusinessCost {
|
||||
member: string;
|
||||
name: string;
|
||||
totalCost: Amount;
|
||||
knownTotalCost: number;
|
||||
missingCount: number;
|
||||
pendingCount: number;
|
||||
}
|
||||
export interface MaterialValue {
|
||||
amount: Amount;
|
||||
knownAmount: number;
|
||||
}
|
||||
export interface MaterialSource extends MaterialValue {
|
||||
kind: string;
|
||||
member: string;
|
||||
priceLocked: boolean;
|
||||
mg: number;
|
||||
averageRate: Amount;
|
||||
missingCount: number;
|
||||
}
|
||||
export interface PoolDay extends MaterialValue {
|
||||
date: string;
|
||||
poolId: string;
|
||||
mg: number;
|
||||
averageRate: Amount;
|
||||
missingCount: number;
|
||||
byPayer: Record<string, MaterialValue>;
|
||||
sources?: MaterialSource[];
|
||||
}
|
||||
export interface PoolMaterial extends MaterialValue {
|
||||
mg: number;
|
||||
missingCount: number;
|
||||
byPayer: Record<string, MaterialValue>;
|
||||
hasPriceLocks: boolean;
|
||||
days: PoolDay[];
|
||||
otherCosts: MaterialValue;
|
||||
}
|
||||
export interface AdvanceItem {
|
||||
id: string;
|
||||
date: string;
|
||||
kind: string;
|
||||
number: string;
|
||||
paperNumber: string;
|
||||
customer: string;
|
||||
name: string;
|
||||
source: string;
|
||||
component: string;
|
||||
poolMaterial: boolean;
|
||||
poolId: string | null;
|
||||
allocationPending: boolean;
|
||||
nonCash?: boolean;
|
||||
status: 'recorded' | 'missing' | 'pending';
|
||||
amount: Amount;
|
||||
estimatedAmount: Amount;
|
||||
}
|
||||
export interface AdvanceDay {
|
||||
date: string;
|
||||
items: AdvanceItem[];
|
||||
amount: Amount;
|
||||
knownAmount: number;
|
||||
missingCount: number;
|
||||
pendingCount: number;
|
||||
poolAmount: Amount;
|
||||
knownPoolAmount: number;
|
||||
otherAmount: Amount;
|
||||
knownOtherAmount: number;
|
||||
}
|
||||
export interface CurrentDay {
|
||||
date: string;
|
||||
recordCount: number;
|
||||
knownMaterialCost: number;
|
||||
knownOtherCost: number;
|
||||
knownProfit: number;
|
||||
ownerNetReceipts: number;
|
||||
missingCostCount: number;
|
||||
pendingCostCount: number;
|
||||
unknownProfitCount: number;
|
||||
incomplete: boolean;
|
||||
materialCost: Amount;
|
||||
otherCost: Amount;
|
||||
profit: Amount;
|
||||
knownAmount: number;
|
||||
amount: Amount;
|
||||
}
|
||||
export interface Counterpart {
|
||||
member: string;
|
||||
name: string;
|
||||
dueOut: number;
|
||||
dueIn: number;
|
||||
offset: number;
|
||||
openingDue: number;
|
||||
periodNew: number;
|
||||
periodTransferred: number;
|
||||
closingDue: number;
|
||||
period: { obligationNet: number; transferred: number; receivedForNet: number; advancedNet: number };
|
||||
}
|
||||
export interface Business extends Range {
|
||||
member: string;
|
||||
name: string;
|
||||
basis: string;
|
||||
recordCount: number;
|
||||
orderCount: number;
|
||||
afterSaleCount: number;
|
||||
draftCount: number;
|
||||
sales: number;
|
||||
netReceipts: number;
|
||||
totalCost: Amount;
|
||||
knownTotalCost: number;
|
||||
selfCost: Amount;
|
||||
knownSelfCost: number;
|
||||
otherCost: Amount;
|
||||
knownOtherCost: number;
|
||||
profit: Amount;
|
||||
knownProfit: number;
|
||||
missingCostCount: number;
|
||||
pendingCostCount: number;
|
||||
unknownProfitCount: number;
|
||||
incomplete: boolean;
|
||||
hasActivity: boolean;
|
||||
costByPayer: Record<string, BusinessCost>;
|
||||
poolMaterial: PoolMaterial;
|
||||
ownerAdvances: Range & { basis: string; days: AdvanceDay[] };
|
||||
currentAccount: Range & { basis: string; days: CurrentDay[] };
|
||||
difference: { amount: number; reconciled: boolean; reasons: { code: string; text: string }[] };
|
||||
equation: { basis: string; revenue: number; totalCost: Amount; profit: Amount; complete: boolean };
|
||||
settlement: Range & {
|
||||
available: boolean;
|
||||
basis: string;
|
||||
partial: boolean;
|
||||
pendingCount: number;
|
||||
legacyCount: number;
|
||||
notice: string;
|
||||
counterparts: Counterpart[];
|
||||
dueIn: Amount;
|
||||
dueOut: Amount;
|
||||
};
|
||||
}
|
||||
export interface DailySource {
|
||||
id: string;
|
||||
date: string;
|
||||
sourceType: string;
|
||||
sourceId: string;
|
||||
payer: string;
|
||||
name: string;
|
||||
note: string;
|
||||
amount: number;
|
||||
}
|
||||
export interface Sources {
|
||||
revision: string;
|
||||
total: number;
|
||||
items: DailySource[];
|
||||
}
|
||||
export interface Confirmation {
|
||||
date: string;
|
||||
amount: number;
|
||||
revision: number;
|
||||
sourceRevision: string;
|
||||
note: string;
|
||||
actor: string;
|
||||
stale: boolean;
|
||||
}
|
||||
export interface FundsDay {
|
||||
date: string;
|
||||
ownerReceipts: Receipts;
|
||||
approvedReimbursements: number;
|
||||
actualOutlay: Amount;
|
||||
confirmation: Confirmation | null;
|
||||
sources: Sources;
|
||||
ready: boolean;
|
||||
transferAmount: Amount;
|
||||
direction: string | null;
|
||||
hasActivity: boolean;
|
||||
}
|
||||
export interface ReimbursementItem {
|
||||
id?: string;
|
||||
availableAmount?: number;
|
||||
name: string;
|
||||
amount: number;
|
||||
member?: string;
|
||||
sourceType?: string;
|
||||
sourceKey?: string;
|
||||
usedAmount?: number;
|
||||
remainingAmount?: number;
|
||||
}
|
||||
export type ReimbursementStatus = 'pending' | 'approved' | 'rejected';
|
||||
export interface Reimbursement {
|
||||
id: string;
|
||||
date: string;
|
||||
status: ReimbursementStatus;
|
||||
revision: number;
|
||||
canEdit: boolean;
|
||||
canApprove: boolean;
|
||||
items: ReimbursementItem[];
|
||||
total: number;
|
||||
note: string;
|
||||
requester_name: string;
|
||||
reviewer_name: string;
|
||||
review_note: string;
|
||||
payer?: string;
|
||||
member?: string;
|
||||
}
|
||||
export interface ReimbursementList {
|
||||
requests: Reimbursement[];
|
||||
total: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
hasMore: boolean;
|
||||
counts: Record<ReimbursementStatus, number>;
|
||||
}
|
||||
export interface TeamPair {
|
||||
members: string[];
|
||||
net: number;
|
||||
obligationNet: number;
|
||||
transferred: number;
|
||||
due: number;
|
||||
entries: unknown[];
|
||||
}
|
||||
export interface Team {
|
||||
from: string;
|
||||
to: string;
|
||||
revision: string | number;
|
||||
pairs: TeamPair[];
|
||||
balances: unknown[];
|
||||
transfers: unknown[];
|
||||
}
|
||||
export interface DailyFunds extends Range, FundsDay {
|
||||
team?: Team;
|
||||
readOnly: boolean;
|
||||
hasRecords: boolean;
|
||||
pendingCount: number;
|
||||
reimbursements: Reimbursement[];
|
||||
missingDates: string[];
|
||||
staleDates: string[];
|
||||
days: FundsDay[];
|
||||
transfersNotDeducted: boolean;
|
||||
rangeUnsupported?: boolean;
|
||||
}
|
||||
export interface PriceActivityItem {
|
||||
id: string;
|
||||
date: string;
|
||||
kind: string;
|
||||
amount: number;
|
||||
account: string;
|
||||
payer: string;
|
||||
quantity: number;
|
||||
rate: number;
|
||||
product: string;
|
||||
customer: string;
|
||||
note: string;
|
||||
name: string;
|
||||
source: string;
|
||||
price_lock_id: string;
|
||||
order_id: string;
|
||||
number: string;
|
||||
paper_number: string;
|
||||
component: string;
|
||||
actor: string;
|
||||
line_index: number;
|
||||
}
|
||||
export interface PriceActivity extends Range {
|
||||
customerCash: PriceActivityItem[];
|
||||
orderPayments: PriceActivityItem[];
|
||||
materialOutlays: PriceActivityItem[];
|
||||
deliveryGoodsOutlays: PriceActivityItem[];
|
||||
directOutlays: PriceActivityItem[];
|
||||
summary: {
|
||||
eventCount: number;
|
||||
receipt: number;
|
||||
refund: number;
|
||||
net: number;
|
||||
materialOutlay: number;
|
||||
goodsOutlay: number;
|
||||
feeOutlay: number;
|
||||
totalOutlay: number;
|
||||
ownerOutlay: number;
|
||||
assistantOutlay: number;
|
||||
};
|
||||
}
|
||||
export interface MaterialPurchase {
|
||||
id: string;
|
||||
pool_id: string;
|
||||
date: string;
|
||||
mg: number;
|
||||
amount: number;
|
||||
payer?: string;
|
||||
actualpayer?: string;
|
||||
actualPayer?: string;
|
||||
note: string;
|
||||
}
|
||||
export interface PoolActivity extends Range {
|
||||
purchases: MaterialPurchase[];
|
||||
summary: {
|
||||
eventCount: number;
|
||||
purchaseCount: number;
|
||||
poolCount: number;
|
||||
mg: number;
|
||||
materialOutlay: number;
|
||||
purchaseValue: number;
|
||||
ownerOutlay: number;
|
||||
assistantOutlay: number;
|
||||
};
|
||||
}
|
||||
export interface PoolSettlement {
|
||||
legacyReadOnly?: boolean;
|
||||
assistantInventoryCredit: Amount;
|
||||
knownAssistantInventoryCredit: number;
|
||||
transferred: number;
|
||||
settlementDue: Amount;
|
||||
knownSettlementDue: number;
|
||||
pendingCount: number;
|
||||
pools: {
|
||||
id: string;
|
||||
date: string;
|
||||
assistantInventoryCredit: Amount;
|
||||
transferred: number;
|
||||
settlementDue: Amount;
|
||||
pending: boolean;
|
||||
}[];
|
||||
}
|
||||
export interface InventoryBalance {
|
||||
pocket: string;
|
||||
mg: number;
|
||||
reserved: number;
|
||||
available: number;
|
||||
countUnit?: string;
|
||||
count?: number | null;
|
||||
}
|
||||
export interface PeoplePart {
|
||||
total: Amount;
|
||||
endTotal: Amount;
|
||||
baselineTotal: Amount;
|
||||
baselineDate: string;
|
||||
netChange: Amount;
|
||||
netChangeReason: string;
|
||||
recordedDays: number;
|
||||
}
|
||||
export type PeopleCount = Range &
|
||||
PeoplePart & { [key: string]: string | number | boolean | null | PeoplePart | undefined };
|
||||
export interface Report extends Range {
|
||||
basis: string;
|
||||
summary: Summary;
|
||||
orderRows: Row[];
|
||||
accounts: Account[];
|
||||
payerCosts: Record<string, PayerCosts>;
|
||||
recipientReceipts: Record<string, RecipientReceipts>;
|
||||
ownershipReceipts: Record<string, OwnershipReceipts>;
|
||||
ownershipBusiness: Record<string, Business>;
|
||||
receiptsByOrderDate: Receipts & {
|
||||
channels: (Receipts & { name: string; channel: string })[];
|
||||
accounts: Account[];
|
||||
paymentCount: number;
|
||||
orderCount: number;
|
||||
};
|
||||
dailyProfits: ProfitTable;
|
||||
dailyFunds: DailyFunds;
|
||||
peopleCount: PeopleCount;
|
||||
priceLockActivity: PriceActivity | null;
|
||||
materialPoolActivity: PoolActivity | null;
|
||||
materialPoolSettlement: PoolSettlement | null;
|
||||
goods: number;
|
||||
expense: number;
|
||||
outlayGoods: number;
|
||||
outlayExpense: number;
|
||||
outlayTotal: number;
|
||||
customerBalance: number;
|
||||
settlementDue: Amount;
|
||||
knownSettlementDue: number;
|
||||
pendingMaterialCount: number;
|
||||
inventory: InventoryBalance[];
|
||||
warnings: { id: string; number: string; message: string }[];
|
||||
unsettled: {
|
||||
id: string;
|
||||
number: string;
|
||||
customer: string;
|
||||
costDue: Amount;
|
||||
profitDue: Amount;
|
||||
ownerGoods: Amount;
|
||||
ownerDirect: number;
|
||||
total: Amount;
|
||||
}[];
|
||||
close: { date: string; actor: string; created: string; stale: boolean; staleReason: string } | null;
|
||||
}
|
||||
export type Metric = 'sale' | 'totalCost' | 'profit';
|
||||
export type RowMetric = Metric | 'goods' | 'paidFees' | 'material' | 'laborAndFees';
|
||||
export type CurrentDisplayDay = Pick<
|
||||
CurrentDay,
|
||||
| 'date'
|
||||
| 'materialCost'
|
||||
| 'knownMaterialCost'
|
||||
| 'otherCost'
|
||||
| 'knownOtherCost'
|
||||
| 'profit'
|
||||
| 'knownProfit'
|
||||
| 'ownerNetReceipts'
|
||||
| 'amount'
|
||||
| 'incomplete'
|
||||
>;
|
||||
export interface RecoveryCosts {
|
||||
byPayer: Record<string, number>;
|
||||
items: CostItem[];
|
||||
}
|
||||
+69
-60
@@ -1,9 +1,18 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type * as T from './contracts';
|
||||
import { Children } from 'react';
|
||||
import { reportData } from './reportData';
|
||||
const withKeys = Children.toArray;
|
||||
const fallback = (rows, empty) => (rows.length ? rows : empty);
|
||||
const e = value => (value == null ? '' : String(value));
|
||||
export function reportPresentation({ state, session, reportMonth, reportMember, onAction, dailyFundsLoading = false }) {
|
||||
const fallback = (rows: ReactNode[], empty: ReactNode) => (rows.length ? rows : empty);
|
||||
const e = (value: unknown) => (value == null ? '' : String(value));
|
||||
export function reportPresentation({
|
||||
state,
|
||||
session,
|
||||
reportMonth,
|
||||
reportMember,
|
||||
onAction,
|
||||
dailyFundsLoading = false,
|
||||
}: T.ReportContext & { onAction: (data: T.ReportAction) => void; dailyFundsLoading?: boolean }) {
|
||||
const model = reportData({ state, session, reportMonth, reportMember });
|
||||
const {
|
||||
reportSummaryAmount,
|
||||
@@ -51,7 +60,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
reportPoolMaterialFormula,
|
||||
reportPoolMaterialSourceLabel,
|
||||
} = model;
|
||||
function renderReportContent(r, range) {
|
||||
function renderReportContent(r: T.Report, range: T.Range) {
|
||||
const s = r.summary,
|
||||
receipts = r.receiptsByOrderDate,
|
||||
profitMissing = s.unknownProfitCount || 0;
|
||||
@@ -116,7 +125,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="4" className="muted">
|
||||
<td colSpan={4} className="muted">
|
||||
所选范围没有收退款活动账户。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -228,9 +237,9 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportDailyProfits(r) {
|
||||
function renderReportDailyProfits(r: T.Report) {
|
||||
const table = r.dailyProfits,
|
||||
amounts = row => (
|
||||
amounts = (row: T.Profit) => (
|
||||
<>
|
||||
<td className="number">¥{yuan(row.sales)}</td>
|
||||
<td className="number">{reportDailyProfitAmount(row.totalCost, row.knownTotalCost)}</td>
|
||||
@@ -280,7 +289,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="5" className="muted">
|
||||
<td colSpan={5} className="muted">
|
||||
所选范围暂无订单或售后记录。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -288,7 +297,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan="2">所选范围合计</td>
|
||||
<td colSpan={2}>所选范围合计</td>
|
||||
{amounts(table.summary)}
|
||||
</tr>
|
||||
</tfoot>
|
||||
@@ -302,7 +311,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReimbursementRows(data, readOnly) {
|
||||
function renderReimbursementRows(data: T.DailyFunds, readOnly: boolean) {
|
||||
return (
|
||||
<div className="reimbursement-records">
|
||||
{fallback(
|
||||
@@ -389,7 +398,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderDailyFundsMonth(data) {
|
||||
function renderDailyFundsMonth(data: T.DailyFunds) {
|
||||
return (
|
||||
<>
|
||||
<p className="small muted">月汇总只读。按每张报销单的报销日期归集,跨日批准仍回到原日期。</p>
|
||||
@@ -440,7 +449,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="6" className="muted">
|
||||
<td colSpan={6} className="muted">
|
||||
所选范围暂无需核对的记录。可切换单日确认。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -452,7 +461,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderDailyFundsSources(data) {
|
||||
function renderDailyFundsSources(data: T.DailyFunds) {
|
||||
return (
|
||||
<details className="daily-funds-sources">
|
||||
<summary>
|
||||
@@ -487,7 +496,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="3" className="muted">
|
||||
<td colSpan={3} className="muted">
|
||||
暂无已记录付款;这不代表当天完整支出一定为 0。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -499,12 +508,12 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderDailyTransferResult(data, month = false) {
|
||||
function renderDailyTransferResult(data: T.DailyFunds, month = false) {
|
||||
const ready = data.ready && !dailyFundsLoading;
|
||||
const direction =
|
||||
data.transferAmount > 0
|
||||
(data.transferAmount ?? 0) > 0
|
||||
? teamMemberName('owner') + '转' + teamMemberName('assistant')
|
||||
: data.transferAmount < 0
|
||||
: (data.transferAmount ?? 0) < 0
|
||||
? teamMemberName('assistant') + '转' + teamMemberName('owner')
|
||||
: '无需转款';
|
||||
return (
|
||||
@@ -535,7 +544,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
<span>
|
||||
{month ? '本期' : '本日'}应转合计 · {direction}
|
||||
</span>
|
||||
<strong>¥{yuan(Math.abs(data.transferAmount))}</strong>
|
||||
<strong>¥{yuan(Math.abs(data.transferAmount ?? 0))}</strong>
|
||||
<p>
|
||||
{teamMemberName('owner')}净收款 ¥{yuan(data.ownerReceipts.net)} − 确认对外支出 ¥{yuan(data.actualOutlay)}{' '}
|
||||
+ 已批准报销 ¥{yuan(data.approvedReimbursements)} = <b>¥{yuan(data.transferAmount)}</b>
|
||||
@@ -555,7 +564,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReimbursementItems(row) {
|
||||
function renderReimbursementItems(row: T.Reimbursement) {
|
||||
return (
|
||||
<ul className="reimbursement-items-read">
|
||||
{withKeys(
|
||||
@@ -581,7 +590,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipReceipts(r, range) {
|
||||
function renderReportOwnershipReceipts(r: T.Report, range: T.Range) {
|
||||
const keys = reportOwnershipKeys(r);
|
||||
return (
|
||||
<section className="report-receipts report-ownership-receipts" aria-label="按订单归属汇总净收入">
|
||||
@@ -638,7 +647,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
const card = (title, value, hint = '', emphasis = false) => (
|
||||
const card = (title: ReactNode, value: ReactNode, hint: ReactNode = '', emphasis = false) => (
|
||||
<div className={'stat ' + (emphasis ? 'emphasis' : '')}>
|
||||
<small>{title}</small>
|
||||
<strong>{value}</strong>
|
||||
@@ -646,7 +655,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</div>
|
||||
);
|
||||
|
||||
function renderReportPayerCosts(r) {
|
||||
function renderReportPayerCosts(r: T.Report) {
|
||||
const 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);
|
||||
@@ -713,7 +722,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderPriceLockActivity(activity) {
|
||||
function renderPriceLockActivity(activity: T.PriceActivity | null) {
|
||||
if (!activity?.summary?.eventCount) return '';
|
||||
const s = activity.summary,
|
||||
rows = priceLockActivityRows(activity);
|
||||
@@ -783,7 +792,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderMaterialPoolActivity(activity) {
|
||||
function renderMaterialPoolActivity(activity: T.PoolActivity | null) {
|
||||
if (!activity?.purchases?.length) return '';
|
||||
return (
|
||||
<section className="panel material-report-activity">
|
||||
@@ -830,7 +839,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOrderNet(r, range) {
|
||||
function renderReportOrderNet(r: T.Report, range: T.Range) {
|
||||
const s = r.summary;
|
||||
return (
|
||||
<section className="panel report-order-net">
|
||||
@@ -870,7 +879,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</td>
|
||||
<td>{badge(row)}</td>
|
||||
{withKeys(
|
||||
['sale', 'goods', 'paidFees', 'totalCost', 'profit'].map(key => (
|
||||
(['sale', 'goods', 'paidFees', 'totalCost', 'profit'] as const).map(key => (
|
||||
<td className="number">{reportRowAmount(row, key)}</td>
|
||||
)),
|
||||
)}
|
||||
@@ -878,7 +887,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="7" className="muted">
|
||||
<td colSpan={7} className="muted">
|
||||
所选日期没有订单或售后记录。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -886,7 +895,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan="2">
|
||||
<td colSpan={2}>
|
||||
销售 {s.orderCount} 单 · 售后 {s.afterSaleCount || 0} 笔
|
||||
</td>
|
||||
<td className="number">{reportSummaryAmount(s, 'sale')}</td>
|
||||
@@ -902,7 +911,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportGlobal(r) {
|
||||
function renderReportGlobal(r: T.Report) {
|
||||
if (teamMode())
|
||||
return (
|
||||
<section className="panel">
|
||||
@@ -960,7 +969,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportUnsettled(r) {
|
||||
function renderReportUnsettled(r: T.Report) {
|
||||
return (
|
||||
<section className="panel report-unsettled">
|
||||
<h2>逐单交款与返款(截至现在)</h2>
|
||||
@@ -1002,7 +1011,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="5">目前没有待结款项。</td>
|
||||
<td colSpan={5}>目前没有待结款项。</td>
|
||||
</tr>,
|
||||
)}
|
||||
</tbody>
|
||||
@@ -1012,7 +1021,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderMaterialPoolGlobalSettlement(value) {
|
||||
function renderMaterialPoolGlobalSettlement(value: T.PoolSettlement | null) {
|
||||
if (!value?.pools?.length) return '';
|
||||
return (
|
||||
<section className="panel material-report-settlement">
|
||||
@@ -1048,7 +1057,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
<td className="number">¥{yuan(item.transferred)}</td>
|
||||
<td className="number">
|
||||
{materialReportMoney(item.settlementDue)}
|
||||
{item.settlementDue < 0 ? (
|
||||
{(item.settlementDue ?? 0) < 0 ? (
|
||||
<>
|
||||
<>
|
||||
<>
|
||||
@@ -1062,7 +1071,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</>
|
||||
{'</div>'}
|
||||
</>
|
||||
) : item.settlementDue > 0 ? (
|
||||
) : (item.settlementDue ?? 0) > 0 ? (
|
||||
<>
|
||||
<>
|
||||
<>
|
||||
@@ -1099,11 +1108,11 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipAccounts(person) {
|
||||
function renderReportOwnershipAccounts(person: T.OwnershipReceipts) {
|
||||
const ownAccounts = person.accounts.filter(account => account.recipient === person.member),
|
||||
otherAccounts = person.accounts.filter(account => account.recipient !== person.member),
|
||||
net = accounts => accounts.reduce((total, account) => total + account.net, 0);
|
||||
const group = (title, rows) => (
|
||||
net = (accounts: T.Account[]) => accounts.reduce((total, account) => total + account.net, 0);
|
||||
const group = (title: string, rows: T.Account[]) => (
|
||||
<section className="report-ownership-account-group">
|
||||
<h3>{title}</h3>
|
||||
{rows.length ? (
|
||||
@@ -1149,7 +1158,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipBusiness(business, range) {
|
||||
function renderReportOwnershipBusiness(business: T.Business, range: T.Range) {
|
||||
return (
|
||||
<>
|
||||
<>
|
||||
@@ -1164,7 +1173,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportRecipientDetails(person, kind = 'receipt') {
|
||||
function renderReportRecipientDetails(person: T.MemberReceipts, kind: 'receipt' | 'refund' = 'receipt') {
|
||||
const items = person.items.filter(item => item.kind === kind),
|
||||
name = kind === 'receipt' ? '收款' : '退款';
|
||||
return (
|
||||
@@ -1175,7 +1184,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
{items.length} 笔{items.some(item => item.amount < 0) ? ',含冲回' : ''}
|
||||
</span>
|
||||
</summary>
|
||||
<div className="table-wrap" tabIndex="0" role="region" aria-label={person.name + name + '明细表'}>
|
||||
<div className="table-wrap" tabIndex={0} role="region" aria-label={person.name + name + '明细表'}>
|
||||
<table className="report-receipt-table" aria-label={person.name + name + '逐笔明细'}>
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -1211,7 +1220,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="4" className="muted">
|
||||
<td colSpan={4} className="muted">
|
||||
所选范围没有{person.name}
|
||||
{name}记录。
|
||||
</td>
|
||||
@@ -1220,7 +1229,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan="3">{name}明细合计</td>
|
||||
<td colSpan={3}>{name}明细合计</td>
|
||||
<td className="number">¥{yuan(person[kind])}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
@@ -1230,7 +1239,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function reportAfterSaleHint(cost) {
|
||||
function reportAfterSaleHint(cost: T.PayerCosts) {
|
||||
return cost.items.some(item => item.kind === 'afterSale') ? (
|
||||
<div className="small muted">其中售后 ¥{yuan(reportAfterSaleAmount(cost))}</div>
|
||||
) : (
|
||||
@@ -1238,7 +1247,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function reportCostDetails(cost) {
|
||||
function reportCostDetails(cost: T.PayerCosts) {
|
||||
const items = reportCostItems(cost);
|
||||
return (
|
||||
<details className="report-cost-detail">
|
||||
@@ -1297,7 +1306,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
)),
|
||||
),
|
||||
<tr>
|
||||
<td colSpan="3" className="muted">
|
||||
<td colSpan={3} className="muted">
|
||||
没有需逐项核对的成本。货品成本为 0 的分项已省略。
|
||||
</td>
|
||||
</tr>,
|
||||
@@ -1309,7 +1318,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function orderBookIdentity(row, version) {
|
||||
function orderBookIdentity(row: T.Row, version?: string) {
|
||||
if (row.kind === 'orderAfterSale')
|
||||
return (
|
||||
<button
|
||||
@@ -1405,13 +1414,13 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
const badge = o => (
|
||||
const badge = (o: T.Row) => (
|
||||
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
|
||||
{label[o.status] || o.status}
|
||||
</span>
|
||||
);
|
||||
|
||||
function renderInventoryBalanceCount(item) {
|
||||
function renderInventoryBalanceCount(item: T.InventoryBalance) {
|
||||
return item?.countUnit === 'pair' || pocketCountsEnabled(item?.pocket) ? (
|
||||
<div className="stock-count-number">{stockCountText(item?.count)}</div>
|
||||
) : (
|
||||
@@ -1419,7 +1428,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipCost(business) {
|
||||
function renderReportOwnershipCost(business: T.Business) {
|
||||
const showPayers = business.knownTotalCost !== 0 || business.totalCost === null,
|
||||
others = teamMemberKeys()
|
||||
.filter(key => key !== business.member)
|
||||
@@ -1461,7 +1470,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnerAdvances(business) {
|
||||
function renderReportOwnerAdvances(business: T.Business) {
|
||||
const advances = business.ownerAdvances,
|
||||
single = advances.from === advances.date,
|
||||
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
||||
@@ -1561,7 +1570,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipProfit(business, range) {
|
||||
function renderReportOwnershipProfit(business: T.Business, range: T.Range) {
|
||||
const equation = business.equation,
|
||||
title = reportMonth || range.from !== range.date ? '本期利润' : '当日利润',
|
||||
complete = equation.complete && !business.incomplete && business.totalCost !== null && business.profit !== null,
|
||||
@@ -1580,7 +1589,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
订单总成本 <b>¥{yuan(equation.totalCost)}</b>
|
||||
</span>
|
||||
<span aria-hidden="true">=</span>
|
||||
<strong className={business.profit < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
|
||||
<strong className={(business.profit ?? 0) < 0 ? 'danger-text' : ''}>¥{yuan(business.profit)}</strong>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
@@ -1607,7 +1616,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportOwnershipCurrentAccount(business) {
|
||||
function renderReportOwnershipCurrentAccount(business: T.Business) {
|
||||
if (business.member === 'owner') return '';
|
||||
const account = business.currentAccount,
|
||||
days = reportCurrentAccountDays(business);
|
||||
@@ -1649,7 +1658,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportReceiptIdentity(item) {
|
||||
function renderReportReceiptIdentity(item: T.ReceiptItem) {
|
||||
const number = item.paper_number || item.number || (item.price_lock_id ? '锁价记录' : '订单记录');
|
||||
const identity = item.order_id ? (
|
||||
<button
|
||||
@@ -1699,7 +1708,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function materialReportCostLink(item) {
|
||||
function materialReportCostLink(item: T.CostItem) {
|
||||
return item.materialPoolId ? (
|
||||
<button
|
||||
className="link-button"
|
||||
@@ -1714,7 +1723,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function afterSaleEditButton(row) {
|
||||
function afterSaleEditButton(row: T.Row) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -1729,7 +1738,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportPoolMaterial(business) {
|
||||
function renderReportPoolMaterial(business: T.Business) {
|
||||
const pool = business.poolMaterial;
|
||||
if (!pool?.days.length) return '';
|
||||
const owner = pool.byPayer.owner;
|
||||
@@ -1764,7 +1773,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function reportOwnerAdvanceIdentity(item) {
|
||||
function reportOwnerAdvanceIdentity(item: T.AdvanceItem) {
|
||||
return item.kind === 'order' ? (
|
||||
<>
|
||||
<button
|
||||
@@ -1785,7 +1794,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function priceLockCostLink(item) {
|
||||
function priceLockCostLink(item: T.CostItem) {
|
||||
if (item.kind === 'afterSale') return reportCostIdentity(item);
|
||||
if (item.price_lock_id)
|
||||
return (
|
||||
@@ -1813,7 +1822,7 @@ export function reportPresentation({ state, session, reportMonth, reportMember,
|
||||
);
|
||||
}
|
||||
|
||||
function renderReportPoolMaterialDay(day) {
|
||||
function renderReportPoolMaterialDay(day: T.PoolDay) {
|
||||
if (!day.sources)
|
||||
return (
|
||||
<li>
|
||||
+95
-236
@@ -1,7 +1,9 @@
|
||||
import { Calc as LedgerCalc } from '../../shared';
|
||||
import { reportValidation } from './validation';
|
||||
export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
function reportDownloadText(r) {
|
||||
import type * as T from './contracts';
|
||||
import { Calc as LedgerCalc, Values } from '../../shared';
|
||||
import ReportRules from '@public/report-rules.js';
|
||||
const { reportAfterSaleAmount, reportCostItems, reportRowCost, reportCurrentAccountDays } = ReportRules;
|
||||
export function reportData({ state, session, reportMonth, reportMember }: T.ReportContext) {
|
||||
function reportDownloadText(r: T.Report) {
|
||||
if (teamMode() && typeof reportTeamDownloadText === 'function') return reportTeamDownloadText(r);
|
||||
const s = r.summary,
|
||||
receipts = r.receiptsByOrderDate,
|
||||
@@ -112,7 +114,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
);
|
||||
if (assistantFirst)
|
||||
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
|
||||
const options = keys.map(member => [
|
||||
const options = keys.map((member): [string, string] => [
|
||||
member,
|
||||
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
|
||||
]);
|
||||
@@ -129,84 +131,44 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
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;
|
||||
}
|
||||
const validOrderDate = Values.validDate;
|
||||
|
||||
function dailyFundsMoney(value) {
|
||||
function dailyFundsMoney(value: T.Amount | undefined) {
|
||||
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 reimbursementDraftTotal(items: { amount: string }[]) {
|
||||
const { total, complete, amounts } = ReportRules.reimbursementAmounts(items, LedgerCalc.cents);
|
||||
return { total, complete, formula: amounts.map(amount => '¥' + yuan(amount)).join(' + ') };
|
||||
}
|
||||
|
||||
function teamDataKeys(data) {
|
||||
function teamDataKeys(data: object) {
|
||||
return [...assistantMemberKeys(), 'owner'].filter(member => data && Object.hasOwn(data, member));
|
||||
}
|
||||
|
||||
function reportSummaryAmount(summary, key) {
|
||||
function reportSummaryAmount(summary: T.Summary, key: T.Metric) {
|
||||
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,
|
||||
});
|
||||
const yuan = (n: T.Amount | undefined) => (n == null ? '待补' : Values.yuan(n));
|
||||
|
||||
function reportPeriod(range) {
|
||||
function reportPeriod(range: T.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) {
|
||||
function accountDisplayName(value: string) {
|
||||
const account = accountIdentity(value);
|
||||
return account ? teamMemberName(account.member) + account.channel : value;
|
||||
}
|
||||
|
||||
function reportDailyProfitAmount(value, known, profit = false) {
|
||||
function reportDailyProfitAmount(value: T.Amount, known: number, profit = false) {
|
||||
return value === null ? (profit ? '待核算(已核算 ¥' : '待补齐(已知 ¥') + yuan(known) + ')' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function reportTeamDownloadText(report) {
|
||||
function reportTeamDownloadText(report: T.Report) {
|
||||
const summary = report.summary,
|
||||
receipts = report.receiptsByOrderDate;
|
||||
return [
|
||||
@@ -254,15 +216,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function reportCostAmount(value, partial = 0) {
|
||||
function reportCostAmount(value: T.Amount | undefined, 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) {
|
||||
function reportPayerHints(cost: T.PayerCosts) {
|
||||
return [
|
||||
cost.missingCount ? cost.missingCount + ' 项成本待补齐' : '',
|
||||
cost.pendingCount ? cost.pendingCount + ' 项费用未入账,不计合计' : '',
|
||||
@@ -271,11 +229,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
.join(';');
|
||||
}
|
||||
|
||||
function reportCostItems(cost) {
|
||||
return cost.items.filter(item => item.kind !== 'goods' || item.amount !== 0);
|
||||
}
|
||||
|
||||
function reportCostIdentity(item) {
|
||||
function reportCostIdentity(item: T.CostItem) {
|
||||
if (item.materialPoolId) return item.materialPoolId + ' 购料';
|
||||
return item.kind === 'afterSale'
|
||||
? '售后 · ' + (item.customer || '未填客户')
|
||||
@@ -284,7 +238,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
(item.customer ? ' · ' + item.customer : '');
|
||||
}
|
||||
|
||||
function reportCostFormula(item) {
|
||||
function reportCostFormula(item: T.CostItem) {
|
||||
const c = item.calculation;
|
||||
if (!c) return '';
|
||||
return (
|
||||
@@ -299,17 +253,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
);
|
||||
}
|
||||
|
||||
function reportCostItemAmount(item) {
|
||||
function reportCostItemAmount(item: T.CostItem) {
|
||||
if (item.kind === 'pending')
|
||||
return '未入账' + (item.amount == null ? '(金额待补)' : '(登记 ¥' + yuan(item.amount) + ')');
|
||||
return item.amount == null ? '待补齐' : '¥' + yuan(item.amount);
|
||||
}
|
||||
|
||||
function afterSalePayerName(row) {
|
||||
function afterSalePayerName(row: T.Row) {
|
||||
return row.costItems?.[0]?.payer ? teamMemberName(row.costItems[0].payer) : '付款人待补';
|
||||
}
|
||||
|
||||
const label = {
|
||||
const label: Record<string, string> = {
|
||||
draft: '旧草稿',
|
||||
confirmed: '旧单待补齐',
|
||||
delivered: '已完成',
|
||||
@@ -319,7 +273,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
recovery: '回收',
|
||||
};
|
||||
|
||||
function reportRowAmount(row, key) {
|
||||
function reportRowAmount(row: T.Row, key: T.RowMetric) {
|
||||
if (row.status === 'draft') return '未开单';
|
||||
if (key === 'goods') {
|
||||
const c = reportRowCost(row);
|
||||
@@ -330,9 +284,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
return row.known?.[key] ? '已知 ¥' + yuan(row.known[key]) + '(待补齐)' : '待补齐';
|
||||
}
|
||||
|
||||
function reportDailyProfitsText(r) {
|
||||
function reportDailyProfitsText(r: T.Report) {
|
||||
const table = r.dailyProfits,
|
||||
rowText = row =>
|
||||
rowText = (row: T.Profit) =>
|
||||
`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost, row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit, row.knownProfit, true)}`;
|
||||
return [
|
||||
'每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',
|
||||
@@ -344,7 +298,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function reportOwnershipReceiptsText(r) {
|
||||
function reportOwnershipReceiptsText(r: T.Report) {
|
||||
return [
|
||||
'按订单归属核对净收入(收款减退款,已含他人代收,尚未扣成本与费用)',
|
||||
...reportOwnershipKeys(r).flatMap(key => {
|
||||
@@ -362,7 +316,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function dailyFundsDownloadText(report) {
|
||||
function dailyFundsDownloadText(report: T.Report) {
|
||||
const range = {
|
||||
date: report.date,
|
||||
from: report.from,
|
||||
@@ -391,9 +345,9 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
if (data.ready)
|
||||
result.push(
|
||||
`${teamMemberName('owner')}净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,
|
||||
data.transferAmount > 0
|
||||
(data.transferAmount ?? 0) > 0
|
||||
? '方向:' + teamMemberName('owner') + '转' + teamMemberName('assistant')
|
||||
: data.transferAmount < 0
|
||||
: (data.transferAmount ?? 0) < 0
|
||||
? '方向:' + teamMemberName('assistant') + '转' + teamMemberName('owner')
|
||||
: '方向:无需转款',
|
||||
);
|
||||
@@ -417,14 +371,14 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
return result;
|
||||
}
|
||||
|
||||
function reportRecipientReceiptsText(r) {
|
||||
function reportRecipientReceiptsText(r: T.Report) {
|
||||
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 => {
|
||||
...(['receipt', 'refund'] as const).flatMap(kind => {
|
||||
const items = person.items.filter(item => item.kind === kind),
|
||||
name = kind === 'receipt' ? '收款' : '退款';
|
||||
return [
|
||||
@@ -444,7 +398,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function priceLockActivityText(activity) {
|
||||
function priceLockActivityText(activity: T.PriceActivity | null) {
|
||||
if (!activity?.summary?.eventCount) return [];
|
||||
const s = activity.summary;
|
||||
return [
|
||||
@@ -458,27 +412,29 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
const grams = n => (n / 1000).toFixed(3);
|
||||
const grams = Values.grams;
|
||||
|
||||
const materialPayerName = payer => (payer ? teamMemberName(payer) : '待补');
|
||||
const materialPayerName = (payer?: string) => (payer ? teamMemberName(payer) : '待补');
|
||||
|
||||
function pocketLabel(key) {
|
||||
function pocketLabel(key: string) {
|
||||
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
|
||||
}
|
||||
|
||||
function pocketCountsEnabled(key) {
|
||||
function pocketCountsEnabled(key: string) {
|
||||
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 stockCountText(value: number | null | undefined, { signed = false, unknown = '未记录对数' } = {}) {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value)
|
||||
? (signed && value > 0 ? '+' : '') + value + '对'
|
||||
: unknown;
|
||||
}
|
||||
|
||||
function materialReportMoney(value) {
|
||||
function materialReportMoney(value: T.Amount | undefined) {
|
||||
return value == null ? '料费待补' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function teamMemberName(member) {
|
||||
function teamMemberName(member: string) {
|
||||
return (
|
||||
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
|
||||
state?.members?.find(row => row.member === member)?.label ||
|
||||
@@ -503,62 +459,24 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
}
|
||||
|
||||
function teamMemberKeys() {
|
||||
return teamMemberCatalog().map(row => row.member);
|
||||
return Values.memberKeys(state);
|
||||
}
|
||||
|
||||
function activeTeamMemberKeys() {
|
||||
return teamMemberKeys().filter(teamMemberEnabled);
|
||||
}
|
||||
|
||||
function teamMemberEnabled(member) {
|
||||
return (
|
||||
teamMemberCatalog().find(row => row.member === member)?.enabled !== false && teamMemberKeys().includes(member)
|
||||
);
|
||||
function teamMemberEnabled(member: string) {
|
||||
return Values.memberEnabled(state, 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;
|
||||
}
|
||||
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
|
||||
|
||||
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) {
|
||||
function priceLockActivityRows(activity: T.PriceActivity | null) {
|
||||
if (!activity) return [];
|
||||
return [...(activity.customerCash || []), ...(activity.orderPayments || [])]
|
||||
.map(item => ({
|
||||
@@ -590,28 +508,18 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
.sort((a, b) => a.date.localeCompare(b.date));
|
||||
}
|
||||
|
||||
const materialPurchasePayer = purchase => purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
|
||||
const materialPurchasePayer = (purchase: T.MaterialPurchase) =>
|
||||
purchase.payer ?? purchase.actualpayer ?? purchase.actualPayer;
|
||||
|
||||
function peopleCountReportLines(count) {
|
||||
function peopleCountReportLines(count: T.PeopleCount) {
|
||||
const period = count?.from !== count?.date;
|
||||
return peopleParts(true).map(
|
||||
([part, name]) =>
|
||||
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (count?.[part]?.baselineDate || '暂无') + ')' : ''}`,
|
||||
`${peopleCountDisplayName(name, period)}:${peopleCountText(count, part)}${period ? '(期末 ' + (count?.date || '未知') + ';开始日前最近记录 ' + (countForPart(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) {
|
||||
function reportOwnershipBusinessText(business: T.Business) {
|
||||
return [
|
||||
`所属订单总成本:${reportBusinessAmount(business.totalCost, business.knownTotalCost)};本人付款 ${reportBusinessAmount(business.selfCost, business.knownSelfCost)};他人付款 ${reportBusinessAmount(business.otherCost, business.knownOtherCost)}`,
|
||||
...reportPoolMaterialText(business),
|
||||
@@ -627,7 +535,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function reportReceiptBasis(item) {
|
||||
function reportReceiptBasis(item: T.ReceiptItem) {
|
||||
return item.order_after_sale
|
||||
? '订单售后 · 按实际收付日'
|
||||
: item.price_lock_id
|
||||
@@ -635,30 +543,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
: '普通订单 · 开单 ' + (item.order_date || '日期未提供');
|
||||
}
|
||||
|
||||
function reportReceiptLabel(item) {
|
||||
function reportReceiptLabel(item: T.ReceiptItem) {
|
||||
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) : '待补');
|
||||
const priceLockPayerName = (payer: string) => (payer ? teamMemberName(payer) : '待补');
|
||||
|
||||
function peopleParts(historical = false) {
|
||||
const keys = assistantMemberKeys().filter(member => historical || teamMemberEnabled(member)),
|
||||
@@ -668,12 +557,16 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
: parts;
|
||||
}
|
||||
|
||||
function peopleCountDisplayName(name, period = false) {
|
||||
function peopleCountDisplayName(name: string, period = false) {
|
||||
return name.replace('人数', period ? '结束日总人数' : '当日总人数');
|
||||
}
|
||||
|
||||
function peopleCountText(count, part = null) {
|
||||
const value = part ? count?.[part] : count;
|
||||
function countForPart(count: T.PeopleCount, part: string) {
|
||||
const value = count?.[part];
|
||||
return value && typeof value === 'object' ? value : undefined;
|
||||
}
|
||||
function peopleCountText(count: T.PeopleCount, part: string | null = null) {
|
||||
const value = part ? countForPart(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 + ' 人(已记录)';
|
||||
@@ -696,11 +589,11 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
);
|
||||
}
|
||||
|
||||
function reportBusinessAmount(value, known) {
|
||||
function reportBusinessAmount(value: T.Amount, known: number) {
|
||||
return (value === null ? '已知 ' : '') + '¥' + yuan(value === null ? known : value);
|
||||
}
|
||||
|
||||
function reportPoolMaterialText(business) {
|
||||
function reportPoolMaterialText(business: T.Business) {
|
||||
const pool = business.poolMaterial;
|
||||
if (!pool?.days.length) return [];
|
||||
const owner = pool.byPayer.owner;
|
||||
@@ -716,7 +609,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function reportOwnerAdvancesText(business) {
|
||||
function reportOwnerAdvancesText(business: T.Business) {
|
||||
const advances = business.ownerAdvances,
|
||||
label = business.member === 'owner' ? teamMemberName('owner') + '付款明细' : teamMemberName('owner') + '垫付明细';
|
||||
return [
|
||||
@@ -738,7 +631,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
function reportCurrentAccountText(business) {
|
||||
function reportCurrentAccountText(business: T.Business) {
|
||||
if (business.member === 'owner') return [];
|
||||
return [
|
||||
'当日往来账(逐日核对,不含历史余额,未扣实际转账)',
|
||||
@@ -750,30 +643,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
];
|
||||
}
|
||||
|
||||
const legacyTeamMembers = [
|
||||
{
|
||||
member: 'owner',
|
||||
label: '麦麦',
|
||||
},
|
||||
{
|
||||
member: 'assistant',
|
||||
label: '娜娜',
|
||||
},
|
||||
{
|
||||
member: 'assistant2',
|
||||
label: '小昊',
|
||||
},
|
||||
];
|
||||
|
||||
function reportOwnerAdvanceAmount(value, known) {
|
||||
function reportOwnerAdvanceAmount(value: T.Amount | undefined, known?: number) {
|
||||
return value === null ? '待补(已知 ¥' + yuan(known) + ')' : '¥' + yuan(value);
|
||||
}
|
||||
|
||||
function reportOwnerAdvanceFormula(business, day) {
|
||||
function reportOwnerAdvanceFormula(business: T.Business, day: Partial<T.AdvanceDay>) {
|
||||
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) {
|
||||
function reportOwnerAdvanceItemAmount(item: T.AdvanceItem) {
|
||||
if (item.status === 'pending')
|
||||
return (
|
||||
'待核对' +
|
||||
@@ -783,29 +661,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
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) {
|
||||
function reportCurrentAccountDirection(business: T.Business, day: T.CurrentDisplayDay) {
|
||||
return day.amount === null
|
||||
? '应转金额待核算'
|
||||
: day.amount > 0
|
||||
@@ -815,15 +671,15 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
: '当日无需转款';
|
||||
}
|
||||
|
||||
function reportCurrentAccountFormula(day) {
|
||||
function reportCurrentAccountFormula(day: T.CurrentDisplayDay) {
|
||||
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) {
|
||||
function peoplePartMember(part: string) {
|
||||
return part === 'assistant1' ? 'assistant' : part;
|
||||
}
|
||||
|
||||
function peopleCountUnknownReason(reason, period = false) {
|
||||
function peopleCountUnknownReason(reason: string, period = false) {
|
||||
return (
|
||||
{
|
||||
'missing-current': period ? '结束日未记录' : '当日未记录',
|
||||
@@ -833,15 +689,17 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
);
|
||||
}
|
||||
|
||||
function peopleCountSignedText(value) {
|
||||
function peopleCountSignedText(value: number) {
|
||||
return (value > 0 ? '+' : '') + value + ' 人';
|
||||
}
|
||||
|
||||
function peopleCountDeltaText(value) {
|
||||
function peopleCountDeltaText(value: number) {
|
||||
return value > 0 ? '新增 ' + value + ' 人' : value < 0 ? '减少 ' + Math.abs(value) + ' 人' : '无变化(0 人)';
|
||||
}
|
||||
|
||||
function reportPoolMaterialFormula(day) {
|
||||
function reportPoolMaterialFormula(
|
||||
day: Pick<T.PoolDay, 'mg' | 'averageRate' | 'amount' | 'knownAmount' | 'sources'>,
|
||||
) {
|
||||
if (day.sources)
|
||||
return (
|
||||
day.sources
|
||||
@@ -855,7 +713,7 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
return `${grams(day.mg)}g × ${day.averageRate === null ? '待补料价' : '¥' + yuan(day.averageRate) + '/g'} = ${day.amount === null ? '料费待补(已知 ¥' + yuan(day.knownAmount) + ')' : '¥' + yuan(day.amount)}`;
|
||||
}
|
||||
|
||||
function reportPoolMaterialPendingNote(pool) {
|
||||
function reportPoolMaterialPendingNote(pool: T.PoolMaterial) {
|
||||
return pool.days.some(
|
||||
day => day.sources && day.sources.reduce((total, source) => total + source.knownAmount, 0) > day.knownAmount,
|
||||
)
|
||||
@@ -863,22 +721,23 @@ export function reportData({ state, session, reportMonth, reportMember }) {
|
||||
: '';
|
||||
}
|
||||
|
||||
function reportPoolMaterialSourceLabel(source) {
|
||||
function reportPoolMaterialSourceLabel(source: T.MaterialSource) {
|
||||
return (
|
||||
(source.kind === 'personal_recovery' ? teamMemberName(source.member) + '个人回收料' : '公共料') +
|
||||
(source.priceLocked ? '(含锁价原料)' : '')
|
||||
);
|
||||
}
|
||||
const { validateDailyFunds, validateReport, validateDailyReimbursements } = reportValidation({
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
teamMode,
|
||||
currentMember,
|
||||
teamMemberKeys,
|
||||
reimbursementStatusNames,
|
||||
state,
|
||||
reportMember,
|
||||
});
|
||||
const { validateDailyFunds, validateReport, validateDailyReimbursements, reportActiveAccounts, reportOwnershipKeys } =
|
||||
ReportRules.forContext({
|
||||
teamDataKeys,
|
||||
validOrderDate,
|
||||
teamMode,
|
||||
currentMember,
|
||||
teamMemberKeys,
|
||||
isReimbursementStatus: value => Object.hasOwn(reimbursementStatusNames, value),
|
||||
state,
|
||||
reportMember,
|
||||
});
|
||||
return {
|
||||
validateReport,
|
||||
validateDailyFunds,
|
||||
@@ -1,895 +0,0 @@
|
||||
// 返回数据在进入报表时完成一次校验,核对明细加总、表间关联及团队权限。
|
||||
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