Files
weiguang-jewelry-ledger/新账系统/web/src/pages/Orders/views/sharedViews.tsx
T

1308 lines
50 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes } from 'react';
import type { OrderContext, Options } from '../viewTypes';
import type {
OrderRecord,
OrderLine,
OwnershipRequest,
ChangeRequest,
CancelSummary,
Member,
RelatedLock,
LockImpact,
InventoryRow,
InventoryChange,
LockCosts,
OrderAfterSale,
BookRow,
PrintStatus,
} from '../orderData';
import { Children, Fragment } from 'react';
import { Calc as LedgerCalc, Cards as CreditCardFees, Values } from '../../../shared';
import {
LedgerButton,
LedgerDataTable,
LedgerInput,
LedgerSelect,
LedgerTable,
} from '../../../components/BusinessControls';
export function sharedViews({
state,
session,
currentOrder,
orderChangeDetail,
orderOwnershipDetail,
orderCancellationDetail,
ui = {},
}: OrderContext) {
function stockCountValue(
value: unknown,
{ zero = false, optional = false, signed = false, title = '库存数量(对)' } = {},
) {
const text = String(value ?? '').trim();
if (!text && optional) return null;
if (signed) {
if (
!/^-?\d+$/.test(text) ||
!Number.isSafeInteger(Number(text)) ||
Math.abs(Number(text)) > 1000000000 ||
Number(text) === 0
)
throw new Error(title + '请填写非0整数,增加填正数,减少填负数。');
return Number(text);
}
if (
!/^\d+$/.test(text) ||
!Number.isSafeInteger(Number(text)) ||
Number(text) > 1000000000 ||
Number(text) < (zero ? 0 : 1)
)
throw new Error(title + '请填写' + (zero ? '非负' : '大于0的') + '整数,一对填1。');
return Number(text);
}
function activePaymentAccounts(selected = '') {
const values = [...new Set((state?.accounts || []).map(normalizePaymentAccount))].filter(value => {
const member = accountIdentity(value)?.member;
return !member || teamMemberEnabled(member) || value === selected;
});
if (selected && !values.includes(selected)) values.push(selected);
return values;
}
const defaultPocketKeys = ['现货', '金料', '找金', '回收旧料', '君宝汇'];
function activePocketKeys() {
return Array.isArray(state?.pockets) ? state.pockets : defaultPocketKeys;
}
function stockCountField(
pocket: string,
value: string | number | null | undefined = '',
{
name = 'stockCount',
title = '出库数量(对)',
optional = false,
readOnly = false,
visible = pocketCountsEnabled(pocket),
help,
}: { name?: string; title?: string; optional?: boolean; readOnly?: boolean; visible?: boolean; help?: string } = {},
) {
const hint = help ?? (optional ? '历史未记录对数,可保留空白;与计工费件数分别填写。' : '与计工费件数分别填写。');
return (
<label className="stock-count-field" data-stock-count-field="" hidden={!visible}>
{title}
<LedgerInput
name={name}
readOnly={readOnly}
defaultValue={value ?? ''}
type="number"
min="1"
max="1000000000"
step="1"
inputMode="numeric"
disabled={!visible}
required={visible && !optional}
placeholder="一对填1"
/>
{hint ? <small className="muted">{hint}</small> : ''}
</label>
);
}
function currentMember() {
return state?.user?.member || session?.user?.member || (state?.user?.role === 'owner' ? 'owner' : 'assistant');
}
function normalizePaymentAccount(account: string) {
return typeof CreditCardFees === 'object' && typeof CreditCardFees.normalizeAccount === 'function'
? CreditCardFees.normalizeAccount(account)
: ['助理信用卡', '助理1信用卡', '助理2信用卡', '麦麦信用卡'].includes(account)
? '麦麦信用卡'
: account;
}
function activeTeamMemberKeys() {
return teamMemberKeys().filter(teamMemberEnabled);
}
function teamMemberOptions(assistantFirst = false, { historical = false, selected = '' } = {}) {
let keys = (historical ? teamMemberKeys() : activeTeamMemberKeys()).filter(
member => teamMode() || member !== 'assistant2',
);
if (assistantFirst)
keys = [...keys.filter(member => member !== 'owner'), ...keys.filter(member => member === 'owner')];
const options = keys.map((member): [string, string] => [
member,
teamMemberName(member) + (historical && !teamMemberEnabled(member) ? '(已停用)' : ''),
]);
if (selected && teamMemberKeys().includes(selected) && !keys.includes(selected))
options.push([selected, teamMemberName(selected) + '(已停用 · 原记录)']);
return options;
}
const choice = (title: string, name: string, values: Options, selected?: string) => {
if (
selected &&
teamMemberKeys().includes(selected) &&
!teamMemberEnabled(selected) &&
values.some(value => teamMemberKeys().includes(Array.isArray(value) ? value[0] : value)) &&
!values.some(value => (Array.isArray(value) ? value[0] : value) === selected)
)
values = [...values, [selected, teamMemberName(selected) + '(已停用 · 原记录)']];
return (
<label>
{title}
<LedgerSelect name={name} defaultValue={selected}>
{opts(values)}
</LedgerSelect>
</label>
);
};
const moneyField = (title: string, name: string, value: string | number = '') =>
field(title, name, value, 'number', {
min: '0',
step: '0.01',
required: true,
});
const field = (
title: string,
name: string,
value: string | number = '',
type = 'text',
props: InputHTMLAttributes<HTMLInputElement> = {},
) => (
<label>
{title}
<LedgerInput type={type} name={name} defaultValue={value} {...props} />
</label>
);
const opts = (values: Options) =>
values.map(v => {
const [value, name, disabled] = Array.isArray(v) ? v : [v, v];
return (
<option key={value} value={value} disabled={!!disabled}>
{value === name ? accountDisplayName(value) : name}
</option>
);
});
const actionName: Record<string, string> = {
confirm: '确认订单',
receipt: '登记收款',
refund: '登记退款',
expense: '直接费用',
fees: '补记旧单费用',
cost: '补齐货品成本',
deliver: '完成销售记账',
complete: '补齐旧单账务',
cancel: '取消订单',
return: '整单退货',
settlement: '实际交款',
review: '店主复核',
correct: '更正流水',
ownership: '修改订单归属',
};
function orderOwnershipEffectHTML(before: string) {
return (
<>
<p className="small muted">
修改后,订单的经营款与业绩按新归属统计。原单号、实际收退款账户、成本付款人及库存记录保留。
</p>
{before !== 'owner' ? (
<p className="small order-ownership-access-note">
生效后,本单将从原归属助理的列表移出,原助理不能再查看或修改本单。
</p>
) : (
''
)}
</>
);
}
function orderOwnershipTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
function validOrderOwnershipMember(value: Member) {
return value && teamMemberKeys().includes(value.member) && typeof value.label === 'string' && !!value.label;
}
const orderOwnershipStatus = {
pending: '待店主复核',
approved: '已修改归属',
rejected: '已驳回',
};
function validateOrderOwnershipRequest(request: OwnershipRequest, orderId: string | undefined = undefined) {
if (
!request ||
typeof request.id !== 'string' ||
!request.id ||
typeof request.order_id !== 'string' ||
!request.order_id ||
(orderId && request.order_id !== orderId) ||
!Object.hasOwn(orderOwnershipStatus, request.status) ||
!Number.isSafeInteger(request.order_revision) ||
typeof request.reason !== 'string' ||
typeof request.requester_name !== 'string' ||
typeof request.created !== 'string' ||
typeof request.stale !== 'boolean' ||
typeof request.canApprove !== 'boolean' ||
!validOrderOwnershipMember(request.before) ||
!validOrderOwnershipMember(request.after) ||
request.before.member === request.after.member
)
throw new Error('归属修改资料未完整返回,请重新读取订单后复核。');
return request;
}
function orderOwnershipPairHTML(request: OwnershipRequest) {
validateOrderOwnershipRequest(request);
return (
<div className="order-ownership-pair" aria-label="订单归属原值与新值">
<div>
<small>原归属</small>
<strong>{request.before.label}</strong>
</div>
<span aria-hidden="true">→</span>
<div>
<small>{request.status === 'pending' ? '申请归属' : '本次新归属'}</small>
<strong>{request.after.label}</strong>
</div>
</div>
);
}
function relatedPriceLocksHTML(items: RelatedLock[] | undefined) {
const locks = validateRelatedPriceLocks(items);
if (!locks.length) return '';
const money = (value?: number | null) => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = (value: LockImpact) =>
value.allocations.length
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
: value.materialAmount === null
? '待补齐后分摊'
: '无分摊金额';
const pair = (name: string, before: ReactNode, after: ReactNode) => (
<tr>
<th scope="row">{name}</th>
<td>{before}</td>
<td>{after}</td>
</tr>
);
return (
<section className="price-lock-related-impact">
<h3>同时受影响的锁价单({locks.length} 张)</h3>
<p className="small muted">以下只调整料池成本和付款归属,客户锁定售价与实际收付款保持原记录。</p>
{Children.toArray(
locks.map(lock => (
<>
<h3>
{lock.date} · {lock.number || lock.id}
{lock.customer ? ' · ' + lock.customer : ''}
</h3>
<div className="table-wrap">
<LedgerTable
className="material-detail-table material-change-comparison"
aria-label="关联锁价单成本影响"
>
<thead>
<tr>
<th>核对项目</th>
<th>变更前</th>
<th>批准后</th>
</tr>
</thead>
<tbody>
{pair('原锁预留料费', money(lock.before.materialAmount), money(lock.after.materialAmount))}
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'usedMaterialAmount'))
? pair(
'交付耗用原锁料费',
Object.hasOwn(lock.before, 'usedMaterialAmount')
? money(lock.before.usedMaterialAmount)
: '未交付',
Object.hasOwn(lock.after, 'usedMaterialAmount')
? money(lock.after.usedMaterialAmount)
: '未交付',
)
: ''}
{(['before', 'after'] as const).some(side => Object.hasOwn(lock[side], 'leftoverCost'))
? pair(
'少重回池成本',
Object.hasOwn(lock.before, 'leftoverCost') ? money(lock.before.leftoverCost) : '未交付',
Object.hasOwn(lock.after, 'leftoverCost') ? money(lock.after.leftoverCost) : '未交付',
)
: ''}
{pair('自动付款归属', sources(lock.before), sources(lock.after))}
</tbody>
</LedgerTable>
</div>
</>
)),
)}
</section>
);
}
function inventoryCountHTML(item: InventoryRow, { signed = false } = {}) {
return Number.isSafeInteger(item?.stockCount) ? (
<div className="small stock-count-number">
{stockCountText(item.stockCount, {
signed,
})}
</div>
) : pocketCountsEnabled(item?.pocket) ? (
<div className="small muted">未记录对数</div>
) : (
''
);
}
function orderChangeInventoryHTML(inventory: InventoryChange | undefined) {
if (!inventory) return '';
const table = (title: string, rows: InventoryRow[], changes = false) => (
<>
<h3>{title}</h3>
{rows.length ? (
<div className="table-wrap">
<LedgerTable className="order-change-inventory">
<thead>
<tr>
<th>日期</th>
<th>货盘</th>
{changes ? '' : <th>库存业务</th>}
<th className="number">{changes ? '本次增减' : '已记克重'}</th>
</tr>
</thead>
<tbody>
{Children.toArray(
rows.map(row => (
<tr>
<td>{row.date}</td>
<td>{pocketLabel(row.pocket)}</td>
{changes ? '' : <td>{row.kind || '未提供'}</td>}
<td className="number">
{row.mg > 0 ? '+' : ''}
{grams(row.mg)}g
{inventoryCountHTML(row, {
signed: true,
})}
</td>
</tr>
)),
)}
</tbody>
</LedgerTable>
</div>
) : (
<p className="small muted">{changes ? '本次没有黄金货盘净变动。' : '没有本单库存流水。'}</p>
)}
</>
);
return (
<section className="order-change-inventory-summary">
<h3>库存原值与批准后变化</h3>
<p className="small muted">
以下为本单各日期、货盘的库存流水;正数为增加,负数为减少。按件商品或退回供应商不计黄金货盘。
</p>
{inventory.legacyCountNotice ? <p className="note">{inventory.legacyCountNotice}</p> : ''}
{table('原库存记录', inventory.before)}
{table('同意后的库存记录', inventory.after)}
{table('本次库存净变化', inventory.changes, true)}
</section>
);
}
function orderChangeEffectiveExpenses(order: OrderRecord) {
const corrected = new Set((order.corrections || []).filter(row => row.type === 'expense').map(row => row.target));
return order.expenses.filter(row => row.amount > 0 && !corrected.has(row.id));
}
function orderChangeExpensesValue(order: OrderRecord) {
return (
orderChangeEffectiveExpenses(order)
.map(
row =>
`${row.date} · ${row.note || '实际费用'}\n${orderChangeMoney(row.amount)} · ${orderChangePayer(row.payer)}支付`,
)
.join('\n\n') || '无已记费用'
);
}
function orderChangePaymentsValue(order: OrderRecord) {
const corrected = new Set((order.corrections || []).filter(row => row.type === 'payment').map(row => row.target));
return (
order.payments
.filter(row => row.amount > 0 && !corrected.has(row.id))
.map(
row =>
`${row.date} · ${row.kind === 'receipt' ? '客户收款' : '客户退款'}\n${orderChangeMoney(row.amount)} · ${row.account ? accountDisplayName(row.account) : '账户未提供'}`,
)
.join('\n\n') || '无有效收退款'
);
}
function orderChangePriceLockCostsHTML(
before: { priceLockCosts?: LockCosts },
after: { priceLockCosts?: LockCosts },
title = '锁价购料成本',
): ReactNode {
if (!before.priceLockCosts && !after.priceLockCosts) return '';
if (before.priceLockCosts?.lines || after.priceLockCosts?.lines) {
const a = before.priceLockCosts || {},
b = after.priceLockCosts || {},
rows = a.lines || b.lines!;
return Children.toArray(
rows.map((row, index) => {
const left = a.lines?.find(item => item.lineId === row.lineId) || {},
right = b.lines?.find(item => item.lineId === row.lineId) || {};
return orderChangePriceLockCostsHTML(
{
priceLockCosts: {
...left,
date: a.date,
},
},
{
priceLockCosts: {
...right,
date: b.date,
},
},
'商品 ' + (index + 1) + ' · 锁价购料成本',
);
}),
);
}
const a = before.priceLockCosts || {},
b = after.priceLockCosts || {},
source = (value?: string) => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
return (
<>
<tr className="change-section-row">
<th colSpan={3} scope="colgroup">
{title}
</th>
</tr>
{orderChangePair('原锁日期', a.date, b.date)}
{orderChangePair('原锁料费来源', source(a.materialSource), source(b.materialSource))}
{orderChangePair('原锁进货料价(每克)', orderChangeMoney(a.buyRate), orderChangeMoney(b.buyRate))}
{orderChangePair(
'原锁料费付款人',
a.materialSource === 'pool' ? '按原锁料池分摊' : orderChangePayer(a.buyPayer),
b.materialSource === 'pool' ? '按原锁料池分摊' : orderChangePayer(b.buyPayer),
)}
{orderChangePair('原锁整批料费', orderChangeMoney(a.materialAmount), orderChangeMoney(b.materialAmount))}
{orderChangePair('补重进货料价(每克)', orderChangeMoney(a.extraRate), orderChangeMoney(b.extraRate))}
{orderChangePair(
'补重料费付款人',
a.extraPayer ? orderChangePayer(a.extraPayer) : '无补重',
b.extraPayer ? orderChangePayer(b.extraPayer) : '无补重',
)}
</>
);
}
function orderChangeLineValue(line: OrderLine | undefined, kind: string) {
if (!line) return '无此商品';
const money = orderChangeMoney;
if (kind === 'name') return `${line.name || '未填写'}${line.priceNote ? '\n' + line.priceNote : ''}`;
if (kind === 'code') return line.code || '未填写';
if (kind === 'quantity') return line.unit === 'g' ? grams(line.quantity) + 'g' : String(line.quantity) + '件';
if (kind === 'sale') return money(line.sale);
if (kind === 'pricing')
return line.goldPrice != null
? `销售金价 ${money(line.goldPrice)}/克\n${line.laborMode === 'gram' ? '销售克工费' : '销售件工费'} ${money(line.laborRate)}${line.laborMode === 'gram' ? '/克' : '/件'}\n件数 ${line.pieces ?? '未填写'}`
: `手填基础金额 ${money(line.baseSale ?? line.sale)}`;
if (kind === 'stockCount')
return Number.isSafeInteger(line.stockCount) || pocketCountsEnabled(line.pocket)
? stockCountText(line.stockCount)
: '不记录对数';
if (kind === 'pocket') return pocketLabel(line.pocket) || '外配/不扣黄金';
if (kind === 'charges')
return line.charges?.length
? line.charges.map(item => `${item.name}:${money(item.amount)}`).join('\n')
: '无附加收费';
if (kind === 'cost') return money(line.cost);
if (kind === 'material') {
const material = line.costMaterial;
if (material?.mode === 'pool')
return `每日购料:${material.poolId}\n本行料费:${money(line.costParts?.material)}${line.materialPool?.allocations?.length ? '\n' + line.materialPool.allocations.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') : line.costParts?.material == null ? '\n待补采购后分摊' : ''}`;
return `${material?.mode === 'gram' ? '每克料价 ' + money(material.rate) + '/克' : '料费总额'}\n${money(line.costParts?.material)}`;
}
if (kind === 'labor')
return `${line.costLabor?.mode === 'gram' ? '进货克工费 ' + money(line.costLabor.rate) + '/克' : '进货总工费'}\n${money(line.costParts?.labor)}`;
if (kind === 'extra')
return line.costParts
? `配件 ${money(line.costParts.accessories)}\n其他 ${money(line.costParts.other)}`
: '原货品成本未分项';
if (kind === 'payers')
return `料费:${line.costMaterial?.mode === 'pool' ? line.materialPool?.allocations?.map(item => orderChangePayer(item.payer) + ' ' + money(item.amount)).join(';') || '按真实采购分摊' : orderChangePayer(line.costPayers?.material ?? line.payer)}\n进货工费:${orderChangePayer(line.costPayers?.labor ?? line.payer)}\n配件及其他:${orderChangePayer(line.payer)}`;
return '';
}
function orderChangePair(title: string, before: ReactNode, after: ReactNode) {
const changed = String(before ?? '') !== String(after ?? '');
return (
<tr
{...(changed
? {
className: 'order-change-modified',
}
: {})}
>
<th scope="row">
{title}
{changed ? <span className="change-mark">已修改</span> : ''}
</th>
<td>{orderChangeCell(before)}</td>
<td>{orderChangeCell(after)}</td>
</tr>
);
}
function validateRelatedPriceLocks(items: RelatedLock[] | undefined) {
if (items === undefined) return [];
const amount = (value?: number | null) => value === null || (Number.isSafeInteger(value) && value! >= 0);
const snapshot = (value: LockImpact) =>
value &&
amount(value.materialAmount) &&
(['usedMaterialAmount', 'leftoverCost'] as const).every(
key => !Object.hasOwn(value, key) || amount(value[key]),
) &&
Array.isArray(value.allocations) &&
value.allocations.every(
part => teamMemberKeys().includes(part.payer) && Number.isSafeInteger(part.amount) && part.amount >= 0,
) &&
(value.materialAmount === null ||
value.allocations.reduce((sum, part) => sum + part.amount, 0) === value.materialAmount);
if (
!Array.isArray(items) ||
!items.every(
item =>
item &&
typeof item.id === 'string' &&
item.id &&
validOrderDate(item.date) &&
snapshot(item.before) &&
snapshot(item.after),
)
)
throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
return items;
}
function validateOrderChangeRequest(request: ChangeRequest, orderId: string | undefined = undefined) {
const validSnapshot = (order: OrderRecord) =>
order &&
order.id === request.order_id &&
Number.isSafeInteger(order.total) &&
Array.isArray(order.lines) &&
Array.isArray(order.expenses) &&
Array.isArray(order.payments);
const nullable = (value?: number | null) => value === null || Number.isSafeInteger(value);
if (
!request ||
typeof request.id !== 'string' ||
!request.id ||
typeof request.order_id !== 'string' ||
(orderId && request.order_id !== orderId) ||
!Object.hasOwn(orderChangeStatus, request.status) ||
!Number.isSafeInteger(request.order_revision) ||
typeof request.reason !== 'string' ||
typeof request.requester_name !== 'string' ||
typeof request.created !== 'string' ||
typeof request.stale !== 'boolean' ||
typeof request.canApprove !== 'boolean' ||
!validSnapshot(request.before) ||
!validSnapshot(request.after) ||
!(['before', 'after'] as const).every(
side =>
request.summary?.[side] &&
(['total', 'netReceived', 'directCost'] as const).every(key =>
Number.isSafeInteger(request.summary[side][key]),
) &&
(['goodsCost', 'profit', 'settlementDue'] as const).every(key => nullable(request.summary[side][key])),
)
)
throw new Error('修改申请资料未完整返回,请重新读取订单后复核。');
if (request.relatedOrders !== undefined) {
if (!Array.isArray(request.relatedOrders)) throw new Error('关联订单的修改影响未完整返回,请重新读取后复核。');
request.relatedOrders.forEach(related =>
validateOrderChangeRequest({
...request,
order_id: related.id,
before: related.before,
after: related.after,
summary: related.summary,
relatedOrders: [],
}),
);
}
validateRelatedPriceLocks(request.relatedPriceLocks);
if (request.action !== undefined && !Object.hasOwn(orderChangeActionLabels, request.action))
throw new Error('变更申请类型未完整返回,请重新读取后复核。');
const inventory = request.summary.inventory;
if (
inventory !== undefined &&
(!inventory ||
!(['before', 'after', 'changes'] as const).every(
key =>
Array.isArray(inventory[key]) &&
inventory[key].every(
row => typeof row.date === 'string' && typeof row.pocket === 'string' && Number.isSafeInteger(row.mg),
),
))
)
throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
return request;
}
function orderChangeComparisonHTML(raw: ChangeRequest) {
const request = validateOrderChangeRequest(raw),
before = request.before,
after = request.after;
const basic = (
<>
{
<>
{
<>
{Children.toArray(
(
[
['业务日期', 'date'],
['客户称呼/代号', 'customer'],
['开单人', 'salesperson'],
['收款方式与收款人', 'payment_account'],
['客户单备注', 'note'],
['内部备注(客户不可见)', 'internal_note'],
] as const
).map(([title, key]) =>
orderChangePair(
title,
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
key === 'payment_account' ? accountDisplayName(after[key]) : after[key],
),
),
)}
{orderChangePair(
'成交取整方式',
before.rounding_mode === 'yuan' ? '四舍五入到整数元' : '保留到分',
after.rounding_mode === 'yuan' ? '四舍五入到整数元' : '保留到分',
)}
</>
}
{orderChangePair('新增费用默认支付日期', before.fees_date || before.date, after.fees_date || after.date)}
</>
}
{orderChangePair('交付日期', before.delivered_date, after.delivered_date)}
</>
);
const summary = Children.toArray(
(
[
['成交金额', 'total'],
['收款净额', 'netReceived'],
['货品成本', 'goodsCost'],
['实际费用合计', 'directCost'],
['利润', 'profit'],
['双方待结净额', 'settlementDue'],
] as const
).map(([title, key]) =>
orderChangePair(
title,
orderChangeMoney(request.summary.before[key]),
orderChangeMoney(request.summary.after[key]),
),
),
);
const lines = Children.toArray(
Array.from(
{
length: Math.max(before.lines.length, after.lines.length),
},
(_, index) => (
<>
<tr className="change-section-row">
<th colSpan={3} scope="colgroup">
商品 {index + 1}
</th>
</tr>
{Children.toArray(
[
['商品与销售计价说明', 'name'],
['商品编号', 'code'],
['克重/数量', 'quantity'],
['销售金价、工费与件数', 'pricing'],
['成交金额(含附加收费)', 'sale'],
['客户附加收费', 'charges'],
['货盘', 'pocket'],
['出库数量(对)', 'stockCount'],
['货品成本合计', 'cost'],
['进货料价与料费', 'material'],
['进货工费', 'labor'],
['其他货品成本', 'extra'],
['成本付款人', 'payers'],
].map(([title, key]) =>
orderChangePair(
title,
orderChangeLineValue(before.lines[index], key),
orderChangeLineValue(after.lines[index], key),
),
),
)}
</>
),
),
);
const related = Children.toArray(
(request.relatedOrders || []).map(item => (
<section className="order-change-related">
<h3>同时受影响的关联订单:{item.number || item.id}</h3>
<p className="small muted">
本次修改会重新分配同批购料的成本及付款人。以下关联订单的利润与待结金额也会随批准一起更新。
</p>
{orderChangeComparisonHTML({
...request,
order_id: item.id,
before: item.before,
after: item.after,
summary: item.summary,
relatedOrders: [],
relatedPriceLocks: [],
})}
</section>
)),
);
return (
<div className="order-change-comparison">
<p className="small muted">
原值为申请时快照,申请值由服务器按本次变更试算。批准前请核对客户实付、商品、成本、费用及付款人。
</p>
<div className="table-wrap">
<LedgerTable className="order-change-table" aria-label="变更申请原值与申请值对照">
<thead>
<tr>
<th>核对项目</th>
<th>原值(申请时)</th>
<th>申请值(同意后)</th>
</tr>
</thead>
<tbody>
{basic}
{orderChangePriceLockCostsHTML(before, after)}
{orderChangePair('订单状态', label[before.status] || before.status, label[after.status] || after.status)}
{orderChangePair('退货日期', before.returned_date, after.returned_date)}
{orderChangePair('整单优惠', orderChangeMoney(before.discount), orderChangeMoney(after.discount))}
{summary}
{lines}
<tr className="change-section-row">
<th colSpan={3} scope="colgroup">
逐笔收退款与实际费用
</th>
</tr>
{orderChangePair(
'有效客户收退款/账户',
orderChangePaymentsValue(before),
orderChangePaymentsValue(after),
)}
{orderChangePair(
'已记实际费用/日期/付款人',
orderChangeExpensesValue(before),
orderChangeExpensesValue(after),
)}
</tbody>
</LedgerTable>
</div>
{orderChangeInventoryHTML(request.summary.inventory)}
{related}
{relatedPriceLocksHTML(request.relatedPriceLocks)}
<p className="small muted">
双方已发生的实际交款保留;试算不会发起真实收款、退款或转账。批准时仍会校验订单和关联资料版本。
</p>
</div>
);
}
function orderChangeCell(value: ReactNode) {
return String(value == null || value === '' ? '未填写' : value)
.split('\n')
.map((line, index) => (
<Fragment key={index}>
{index > 0 && <br />}
{line}
</Fragment>
));
}
function orderChangePayer(value: string | undefined) {
return value ? teamMemberName(value) : '待补齐';
}
function orderChangeMoney(value: number | null | undefined) {
return value == null ? '待补齐' : '¥' + yuan(value);
}
function orderChangeInputMoney(value: unknown) {
try {
return orderChangeMoney(LedgerCalc.cents(value));
} catch {
return '金额未提供';
}
}
function stockCountText(value: unknown, { signed = false, unknown = '未记录对数' } = {}) {
return Number.isSafeInteger(value) ? (signed && Number(value) > 0 ? '+' : '') + value + '对' : unknown;
}
function pocketCountsEnabled(key: string) {
return !!key && state?.pocketCatalog?.some(row => row.key === key && row.countUnit === 'pair') === true;
}
function pocketLabel(key: string) {
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
}
function validateOrderAfterSaleRecord(record: OrderAfterSale | null) {
if (
!record ||
!Array.isArray(record.lines) ||
!record.lines.length ||
!record.lines.every(line =>
(['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'] as const).every(key =>
Number.isSafeInteger(line[key]),
),
) ||
!record.summary ||
!(
[
'refundAmount',
'retainedAmount',
'materialReturnedCost',
'laborRestockedCost',
'costLoss',
'directCost',
'profit',
'profitAdjustment',
] as const
).every(key => Number.isSafeInteger(record.summary[key]))
)
throw new Error('售后核算资料未完整返回,请重新读取订单。');
return record;
}
function orderAfterSaleSummaryHTML(raw: OrderAfterSale | null, { preview = false } = {}) {
const record = validateOrderAfterSaleRecord(raw),
summary = record.summary,
money = (value: number) => '¥' + yuan(value),
facts: [string, number][] = [
['实际退款', summary.refundAmount],
['扣留客户款', summary.retainedAmount],
['回料池原料成本', summary.materialReturnedCost],
['现货保留工费', summary.laborRestockedCost],
['本单货品成本损失', summary.costLoss],
['售后最终利润', summary.profit],
['本次售后利润调整', summary.profitAdjustment],
];
return (
<section
className={'order-after-sale-summary' + (preview ? ' is-preview' : '')}
aria-label={preview ? '售后核对预览' : '已保存售后详情'}
>
<div className="panel-title">
<h3>{preview ? '售后核对预览' : '售后处理结果'}</h3>
<span className="badge">{preview ? '尚未保存' : '已记账'}</span>
</div>
<dl className="order-after-sale-totals">
{Children.toArray(
facts.map(([name, amount]) => (
<div>
<dt>{name}</dt>
<dd
{...(amount < 0
? {
className: 'danger-text',
}
: {})}
>
{money(amount)}
</dd>
</div>
)),
)}
</dl>
<div className="table-wrap">
<LedgerDataTable
aria-label="逐件售后回库与成本"
columns={[
{ title: '商品与实际去向' },
{ title: '实际退回' },
{ title: '回料成本' },
{ title: '保留工费' },
{ title: '成本损失' },
]}
rows={record.lines.map((line, rowIndex) => ({
key: rowIndex,
cells: [
<>
{line.name || '商品 ' + (line.lineIndex + 1)}
<div className="small muted">
{pocketLabel(line.pocket)} · {line.disposition === 'stock' ? '完好现货' : '旧料/损坏'}
</div>
</>,
<>
{grams(line.quantity)}g
{line.disposition === 'stock' && pocketCountsEnabled(line.pocket) ? (
<div className="small">{stockCountText(line.stockCount)}</div>
) : (
''
)}
</>,
money(line.materialReturnedCost),
money(line.laborRestockedCost),
money(line.costLoss),
],
}))}
/>
</div>
<p className="small muted">
实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。
</p>
</section>
);
}
function orderChangeActionSummaryHTML(request: ChangeRequest) {
const action = request.action || 'edit',
input = request.action_input || request.action_details || {};
if (action === 'edit') return '';
if (input.afterSale) {
const record = orderAfterSaleRecord(request.after);
return (
<section className="order-change-action-summary">
<h3>本次售后申请</h3>
<p>
售后日期:{input.date} · 申请原因:{request.reason}
</p>
{orderAfterSaleSummaryHTML(record, {
preview: true,
})}
</section>
);
}
const facts = [
['申请动作', orderChangeActionLabel(request)],
['业务日期', input.date || request.after.returned_date || request.after.date],
];
if (input.amount !== undefined) facts.push(['本次金额', orderChangeInputMoney(input.amount)]);
if (input.account) facts.push(['退款账户', accountDisplayName(input.account)]);
if (input.payer) facts.push(['实际付款人', orderChangePayer(input.payer)]);
if (input.note) facts.push(['费用项目/说明', input.note]);
if (input.reference) facts.push(['退款凭据备注', input.reference]);
if (Array.isArray(input.returnCounts))
facts.push([
'实际退回数量(对)',
input.returnCounts
.map((count, index) => '商品 ' + (index + 1) + ':' + stockCountText(count == null ? null : Number(count)))
.join('\n'),
]);
if (Array.isArray(input.returnPockets))
facts.push([
'退货实物去向',
input.returnPockets
.map(
(pocket, index) =>
`${request.before.lines[index]?.name || '商品 ' + (index + 1)}:${pocketLabel(pocket) || '退供应商/不留黄金货盘'}`,
)
.join('\n'),
]);
if (Array.isArray(input.fee_items))
facts.push([
'本次旧费用',
input.fee_items
.map(
item =>
`${item.note || '费用'}:${orderChangeInputMoney(item.amount)} · ${orderChangePayer(item.payer)}支付`,
)
.join('\n'),
]);
return (
<section className="order-change-action-summary">
<h3>本次申请动作</h3>
<dl className="order-change-action-facts">
{Children.toArray(
facts.map(([title, value]) => (
<div>
<dt>{title}</dt>
<dd>{orderChangeCell(value)}</dd>
</div>
)),
)}
</dl>
<p className="small muted">下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。</p>
</section>
);
}
function orderChangeTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
const orderChangeStatus = {
pending: '待店主复核',
approved: '已同意变更',
rejected: '已驳回',
};
const orderChangeActionLabels: Record<string, string> = {
edit: '修改订单',
expense: '费用补记',
fees: '旧费用核实',
refund: '退款',
return: '退货',
cost: '成本补录',
};
function orderChangeActionLabel(request: ChangeRequest) {
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
}
const orderCancellationStatus = {
pending: '待店主复核',
approved: '已同意取消',
rejected: '已驳回',
};
function orderCancellationTime(value: string | null) {
const date = new Date(value!);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
const accountIdentity = (value: string) => Values.accountIdentity(teamMemberKeys(), value);
function accountDisplayName(value: string) {
const account = accountIdentity(value);
return account ? teamMemberName(account.member) + account.channel : value;
}
function validateOrderCancellationSummary(summary: CancelSummary | undefined) {
if (
!summary ||
!(['total', 'netReceived', 'directCost'] as const).every(key => Number.isSafeInteger(summary[key])) ||
!(['goodsCost', 'profit', 'settlementDue'] as const).every(
key => summary[key] === null || Number.isSafeInteger(summary[key]),
) ||
!Array.isArray(summary.inventory) ||
!summary.inventory.every(
item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg),
)
)
throw new Error('取消撤销摘要未完整返回,请重新读取订单。');
return summary;
}
function orderCancellationCanDirect(order = currentOrder) {
const data = currentOrderCancellation(order)?.data;
if (
!data?.eligible ||
data.pending ||
data.directToday !== true ||
!/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') ||
order?.date !== data.directActionDate ||
order?.price_lock_id ||
!['draft', 'confirmed', 'delivered'].includes(order?.status || '')
)
return false;
try {
validateOrderCancellationSummary(data.summary);
return true;
} catch {
return false;
}
}
function orderActionCanDirect(kind: string, date = state.today, order = currentOrder) {
const data = currentOrderChange(order)?.data;
return (
['expense', 'fees', 'refund', 'return'].includes(kind) &&
!!data &&
!data.pending &&
/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') &&
data.actions?.[kind]?.directToday === true &&
order?.date === data.directActionDate &&
date === data.directActionDate &&
!(ui.action === kind && ui.forceApproval)
);
}
function orderActionUsesChangeForm(kind: string) {
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
}
function orderActionRequiresApproval(kind: string, date = state.today) {
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
}
function orderAfterSaleRecord(order: OrderRecord | undefined) {
return order?.orderAfterSale || null;
}
function orderOwnershipUser() {
return session?.user?.id || '';
}
function currentOrderOwnership(order = currentOrder) {
return order &&
orderOwnershipDetail?.id === order.id &&
orderOwnershipDetail.user === orderOwnershipUser() &&
orderOwnershipDetail.revision === order.revision
? orderOwnershipDetail
: null;
}
function orderOwnershipPending(order = currentOrder) {
return currentOrderOwnership(order)?.data?.pending || order?.ownershipPending || null;
}
function orderChangeUser() {
return session?.user?.id || '';
}
function currentOrderChange(order = currentOrder) {
return order &&
orderChangeDetail?.id === order.id &&
orderChangeDetail.user === orderChangeUser() &&
orderChangeDetail.revision === order.revision
? orderChangeDetail
: null;
}
function orderChangePending(order: OrderRecord) {
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
}
function orderCancellationUser() {
return session?.user?.id || '';
}
function currentOrderCancellation(order = currentOrder) {
return order &&
orderCancellationDetail?.id === order.id &&
orderCancellationDetail.user === orderCancellationUser() &&
orderCancellationDetail.revision === order.revision
? orderCancellationDetail
: null;
}
function orderCancellationPending(order: OrderRecord) {
return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null;
}
function printStatusBadge(value: { id: string; kind?: string; printStatus?: PrintStatus }) {
if (['afterSale', 'orderAfterSale'].includes(value.kind ?? '')) return '';
const printed = value.printStatus?.printed;
return (
<span
data-print-kind={value.printStatus?.kind || (value.kind === 'recovery' ? 'recovery' : 'order')}
data-print-id={value.printStatus?.id || value.id}
className={'document-print-badge ' + (printed ? 'is-printed' : 'is-unprinted')}
title={printed ? '已记录打印操作' : '尚未记录打印操作'}
>
{printed ? '✓ 已打印' : '未打印'}
</span>
);
}
const grams = Values.grams;
const e = (value: unknown) => String(value ?? '');
const showOrderCopyEntry = false;
const orderEntryTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
});
const validOrderDate = Values.validDate;
function orderEntryTime(value: unknown) {
if (
typeof value !== 'string' ||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,3})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
value,
) ||
!validOrderDate(value.slice(0, 10))
)
return '未记录';
const date = new Date(value!);
if (Number.isNaN(date.getTime())) return '未记录';
const parts = Object.fromEntries(orderEntryTimeFormatter.formatToParts(date).map(part => [part.type, part.value]));
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}`;
}
function orderEntryTimeHTML(order: { created: string }) {
return <div className="small muted order-entry-time">录入时间(北京时间):{orderEntryTime(order.created)}</div>;
}
function orderIsReviewed(row: Pick<BookRow, 'kind' | 'revision' | 'reviewed_revision'>) {
return (
!['afterSale', 'orderAfterSale', 'recovery'].includes(row.kind ?? '') &&
Number.isSafeInteger(row.revision) &&
row.revision! > 0 &&
row.reviewed_revision === row.revision
);
}
const label: Record<string, string> = {
draft: '旧草稿',
confirmed: '旧单待补齐',
delivered: '已完成',
returned: '已退货',
cancelled: '已取消',
after_sale: '售后',
recovery: '回收',
};
const badge = (o: { status: string }) => (
<span className={'order-status ' + (['draft', 'confirmed'].includes(o.status) ? 'danger-text' : 'muted')}>
{label[o.status] || o.status}
</span>
);
const button = (
text: ReactNode,
action: string,
cls = '',
props: ButtonHTMLAttributes<HTMLButtonElement> & {
[key: `data-${string}`]: string | number | boolean | undefined;
} = {},
) => (
<LedgerButton type="button" data-action={action} className={cls} {...props}>
{text}
</LedgerButton>
);
function teamMemberName(member: string | undefined) {
return (
state?.shopSettings?.members?.find(row => row.member === member)?.label ||
state?.members?.find(row => row.member === member)?.label ||
session?.loginOptions?.find(row => row.member === member)?.label ||
(
{
owner: '麦麦',
assistant: '娜娜',
assistant2: '小昊',
} as Record<string, string>
)[member ?? ''] ||
'待确认'
);
}
const teamMemberKeys = () => Values.memberKeys(state);
const teamMemberEnabled = (member: string) => Values.memberEnabled(state, member);
function teamMode() {
return !!(state?.user?.member || state?.members?.some(member => member.member === 'assistant2'));
}
const yuan = (n?: number | null) => (n == null ? '待补' : Values.yuan(n));
return {
yuan,
teamMode,
teamMemberKeys,
teamMemberName,
badge,
orderEntryTimeHTML,
showOrderCopyEntry,
button,
e,
printStatusBadge,
orderIsReviewed,
grams,
validOrderDate,
activePocketKeys,
pocketLabel,
accountDisplayName,
orderCancellationPending,
orderChangePending,
orderOwnershipPending,
orderAfterSaleRecord,
orderActionRequiresApproval,
actionName,
currentOrderCancellation,
orderCancellationCanDirect,
currentOrderOwnership,
orderCancellationTime,
orderCancellationStatus,
currentOrderChange,
orderChangeActionLabel,
orderChangeStatus,
orderChangeTime,
orderChangeActionSummaryHTML,
orderChangeComparisonHTML,
orderOwnershipPairHTML,
orderOwnershipTime,
orderOwnershipEffectHTML,
orderOwnershipStatus,
orderAfterSaleSummaryHTML,
stockCountText,
pocketCountsEnabled,
orderActionUsesChangeForm,
moneyField,
choice,
teamMemberOptions,
field,
stockCountField,
activePaymentAccounts,
orderChangeActionLabels,
normalizePaymentAccount,
accountIdentity,
memberAccountPrefix: Values.memberAccountPrefix,
teamMemberEnabled,
opts,
currentMember,
stockCountValue,
validateOrderCancellationSummary,
inventoryCountHTML,
orderChangeMoney,
validateOrderChangeRequest,
validateOrderOwnershipRequest,
orderActionCanDirect,
orderChangeUser,
};
}