Files
weiguang-jewelry-ledger/新账系统/web/src/pages/PriceLocks/lockViews.jsx
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1208 lines
44 KiB
React
Raw Normal View History

import { Children, Fragment } from 'react';
import { describeMaterialSources, validateMaterialQuote as checkMaterialQuote } from '../../lib/materialQuote';
import { Model, Calc as LedgerCalc, Values } from '../../shared';
export function lockViews(state, session) {
const validateMaterialQuote = (result, input) => checkMaterialQuote(result, input, Model.memberKeys(state));
function priceLockSplitMaterialSources(pool, mg) {
let left = mg;
const taken = [],
rest = [];
if (
!Array.isArray(pool.materialSources) ||
pool.materialSources.reduce((sum, source) => sum + source.quantity, 0) !== pool.quantity ||
pool.materialSources.reduce((sum, source) => sum + source.amount, 0) !== pool.amount
)
throw new Error('原锁分来源克重或成本未完整读到,请重新读取。');
for (const source of pool.materialSources) {
if (
!['quantity', 'amount', 'basisAmount', 'basisMg', 'prefixMg', 'prefixAmount'].every(
key => Number.isSafeInteger(source[key]) && source[key] >= 0,
) ||
!source.basisMg ||
!Array.isArray(source.allocations) ||
source.allocations.reduce((sum, part) => sum + part.amount, 0) !== source.amount
)
throw new Error('原锁分来源成本未完整读到,请重新读取。');
const n = Math.min(left, source.quantity);
left -= n;
if (!n) {
rest.push({
...source,
});
continue;
}
if (n === source.quantity) {
taken.push({
...source,
});
continue;
}
const amount =
LedgerCalc.poolMaterialAmount(source.basisAmount, source.basisMg, source.prefixMg + n) - source.prefixAmount,
paid = [],
unpaid = [];
let money = amount;
for (const part of source.allocations) {
const value = Math.min(money, part.amount);
if (value)
paid.push({
...part,
amount: value,
});
if (part.amount > value)
unpaid.push({
...part,
amount: part.amount - value,
});
money -= value;
}
if (money || amount < 0 || amount > source.amount) throw new Error('原锁分来源分币未完整读到,请重新读取。');
if (!amount && !paid.length)
paid.push({
payer: source.allocations[0]?.payer || 'owner',
amount: 0,
});
const batches = [],
remainingBatches = [];
let weight = n;
for (const batch of source.batches || []) {
const value = Math.min(weight, batch.mg);
if (value)
batches.push({
...batch,
mg: value,
});
if (batch.mg > value)
remainingBatches.push({
...batch,
mg: batch.mg - value,
});
weight -= value;
}
taken.push({
...source,
quantity: n,
amount,
allocations: paid,
batches,
});
rest.push({
...source,
quantity: source.quantity - n,
amount: source.amount - amount,
allocations: unpaid,
batches: remainingBatches,
prefixMg: source.prefixMg + n,
prefixAmount: source.prefixAmount + amount,
});
}
if (left) throw new Error('实际耗料超过原锁来源克重。');
return {
taken,
rest,
};
}
function lockQuantityMg(value) {
const text = String(value ?? '').trim();
if (!/^\d+(?:\.\d{1,3})?$/.test(text)) throw new Error('克重请填写正数,最多3位小数。');
const [whole, part = ''] = text.split('.'),
mg = Number(whole) * 1000 + Number(part.padEnd(3, '0'));
if (!Number.isSafeInteger(mg) || mg <= 0) throw new Error('克重请填写大于0的有效数字。');
return mg;
}
function priceLockDeliveryCost(lock, quantity, extraBuyRate) {
if (!priceLockUsesPool(lock))
return LedgerCalc.priceLockCost({
lockedQuantity: grams(lock.locked_mg),
quantity,
buyRate: (lock.buy_rate / 100).toFixed(2),
extraBuyRate,
});
const pool = lock.materialPool,
finalMg = lockQuantityMg(quantity),
originalUsedMg = Math.min(finalMg, lock.locked_mg),
extraMg = Math.max(0, finalMg - lock.locked_mg),
leftoverMg = lock.locked_mg - originalUsedMg;
if (
!pool ||
!['basisAmount', 'basisMg', 'prefixMg', 'prefixAmount', 'amount'].every(
key => Number.isSafeInteger(pool[key]) && pool[key] >= 0,
) ||
!pool.basisMg
)
throw new Error('原锁料池成本来源未完整读到,请重新读取锁价单。');
const split = pool.materialSources ? priceLockSplitMaterialSources(pool, originalUsedMg) : null,
originalUsedCost = split
? split.taken.reduce((sum, source) => sum + source.amount, 0)
: LedgerCalc.poolMaterialAmount(pool.basisAmount, pool.basisMg, pool.prefixMg + originalUsedMg) -
pool.prefixAmount;
const extraRate = extraMg ? LedgerCalc.cents(extraBuyRate, '补重进货料价') : 0;
if (extraMg && !extraRate) throw new Error('补重进货料价必须大于0。');
const extraCost = extraMg ? Number((BigInt(extraMg) * BigInt(extraRate) + 500n) / 1000n) : 0;
let left = originalUsedCost;
const allocations = [];
for (const part of split ? split.taken.flatMap(source => source.allocations) : priceLockMaterialAllocations(lock)) {
const amount = Math.min(left, part.amount);
if (amount || (!originalUsedCost && !allocations.length))
allocations.push({
payer: part.payer,
amount,
});
left -= amount;
}
if (left || originalUsedCost < 0 || originalUsedCost > pool.amount)
throw new Error('原锁料池成本分摊不完整,请重新读取锁价单。');
return {
lockedMg: lock.locked_mg,
finalMg,
originalUsedMg,
extraMg,
leftoverMg,
originalPurchase: pool.amount,
originalUsedCost,
extraCost,
materialCost: originalUsedCost + extraCost,
leftoverCost: pool.amount - originalUsedCost,
allocations,
...(split
? {
materialSources: split.taken,
leftoverMaterialSources: split.rest,
}
: {}),
};
}
function priceLockLineInputs(lock) {
const line = lock.line,
payer = priceLockMaterialAllocations(lock)[0]?.payer || lock.buy_payer || 'owner';
return {
...line,
quantity: grams(lock.locked_mg),
goldPrice: (lock.sell_rate / 100).toFixed(2),
laborRate: (line.laborRate / 100).toFixed(2),
sale: (line.sale / 100).toFixed(2),
baseSale: ((line.baseSale ?? line.sale) / 100).toFixed(2),
charges: (line.charges || []).map(c => ({
...c,
amount: (c.amount / 100).toFixed(2),
})),
payer,
costParts: {
material: (lock.material_amount / 100).toFixed(2),
labor: '',
accessories: '0',
other: '0',
},
costMaterial: {
mode: 'total',
},
costLabor: {
mode: 'total',
},
costPayers: {
material: payer,
labor: 'owner',
},
};
}
function detailView(lock) {
return (
<>
<div className={'order-header'}>
<div className={'eyebrow'}>GOLD PRICE LOCK</div>
<h2>
{lock.customer} · {priceLockLines(lock).length}件黄金锁价
</h2>
</div>
{priceLockFacts(lock)}
{priceLockLines(lock).length === 1 ? renderPriceLockItems(lock) : ''}
<p className={'small muted'}>
预计报价 ¥{yuan(lock.estimated_total)};交付时按最终克重、工费和附加项目重新结算,销售金价保持原锁价格。
</p>
{lock.note ? (
<>
<p>{lock.note}</p>
</>
) : (
''
)}
{lock.status === 'cancelled' ? (
<>
<p className={'note'}>
已作废 · {lock.cancelled_reason || '原单记录保留'}
<br />
{lock.cancelled_at || ''}
</p>
</>
) : (
''
)}
<div className={'actions'}>
{lock.status === 'pending' ? (
<>
{button('办理交付', 'deliver-price-lock', 'primary', {
'data-id': lock.id,
})}
{renderPriceLockPendingButtons(lock)}
</>
) : lock.final_order_id ? (
button('查看销售单', 'open-lock-order', 'primary', {
'data-id': lock.final_order_id,
})
) : (
''
)}
</div>
</>
);
}
function priceLockCardFeeTotal(lock) {
return Number.isSafeInteger(lock.credit_card_fee_total)
? lock.credit_card_fee_total
: (lock.credit_card_fees || []).reduce((sum, item) => sum + item.amount, 0);
}
function renderPriceLockCardFees(lock) {
const fees = lock.credit_card_fees || [];
if (!fees.length && !priceLockCardFeeTotal(lock)) return '';
return (
<>
<div className={'price-lock-card-fees internal'}>
<strong>已记录的信用卡手续费 · ¥{yuan(priceLockCardFeeTotal(lock))}</strong>
<ul>
{Children.toArray(
fees.map(item => (
<>
<li>
<span>
{item.date} · {priceLockPayerName(item.payer)}支付{item.note ? ' · ' + item.note : ''}
</span>
<b>¥{yuan(item.amount)}</b>
</li>
</>
)),
)}
</ul>
<p className={'small muted'}>
已按各笔付款时保存的金额与费率计入内部成本;交付时沿用,不重复收取。退款不冲回已发生的手续费。
</p>
</div>
</>
);
}
function priceLockFacts(lock) {
const voided =
lock.status === 'cancelled' ? (
<>
<div className={'note price-lock-voided-note'}>
<strong>这张锁价单已作废</strong>
<p>
客户收款、手填购料和信用卡手续费有效记账已撤销,料池预留已释放。下方原录入克重、售价和成本保留用于追溯,不计当前有效收付。
</p>
{Children.toArray(
(lock.cancellationReturns || []).map(row => (
<>
<p>
商品 {row.line_index + 1} · {row.date} 按原成本回池:
<strong>
{grams(row.mg)}g / ¥{yuan(row.amount)}
</strong>
,参与回池当天加权;原料池日期 {row.origin_pool_id}。
</p>
</>
)),
)}
</div>
</>
) : (
''
);
const rows = priceLockLines(lock);
if (rows.length > 1) {
const mg = rows.reduce((sum, row) => sum + row.locked_mg, 0),
pending = rows.some(priceLockMaterialPending),
amount = rows.reduce((sum, row) => sum + (row.material_amount ?? 0), 0);
return (
<>
{voided}
<div className={'grid three price-lock-facts'}>
<div>
锁价日期<strong>{lock.date}</strong>
</div>
<div>
原锁总克重 · {rows.length}件<strong>{grams(mg)}g</strong>
</div>
<div>
{lock.status === 'delivered' ? '锁价及交付阶段净收款' : '客户实际已付净额'}
<strong>¥{yuan(lock.netReceived)}</strong>
</div>
<div>
原锁料费合计<strong>{pending ? '料费待补' : '¥' + yuan(amount)}</strong>
</div>
<div>
状态
<strong>
{lock.status === 'pending' ? '待交付,不计利润' : lock.status === 'cancelled' ? '已作废' : '已交付'}
</strong>
</div>
</div>
{renderPriceLockItems(lock)}
{renderPriceLockCardFees(lock)}
</>
);
}
lock = rows[0] || lock;
const pool = priceLockUsesPool(lock),
material = lock.materialPool,
pendingMaterial = priceLockMaterialPending(lock);
const source = pendingMaterial ? (
<>
<small>关联用料不足,补足购料后自动核算料费与付款来源。</small>
</>
) : (
<>
<small>
{pool
? material?.materialSources?.length
? materialSourceSegmentsText(material.materialSources)
: `${material?.date || lock.material_pool_id || lock.date}料池,加权均价约 ¥${yuan(material?.averageRate ?? lock.buy_rate)}/克`
: `${priceLockPayerName(lock.buy_payer)}支付,进货料价 ¥${yuan(lock.buy_rate)}/克`}
</small>
{pool ? (
<>
<small>{priceLockAllocationText(priceLockMaterialAllocations(lock))}</small>
<small>{material?.frozen ? '已冻结锁价日成本' : '当天补料继续加权'},不重复记购料付款。</small>
</>
) : (
''
)}
</>
);
return (
<>
{voided}
<div className={'grid three price-lock-facts'}>
<div>
锁价日期<strong>{lock.date}</strong>
</div>
<div>
原锁克重<strong>{grams(lock.locked_mg)}g</strong>
</div>
<div>
锁定销售金价<strong>¥{yuan(lock.sell_rate)}/克</strong>
</div>
<div>
{lock.status === 'delivered' ? '锁价及交付阶段净收款' : '客户实际已付净额'}
<strong>¥{yuan(lock.netReceived)}</strong>
{lock.status === 'delivered' ? (
<>
<small>后续收退款请查看销售单。</small>
</>
) : (
''
)}
</div>
<div>
原锁料费 · {pool ? '当日加权料池' : '手动独立购料'}
<strong>{priceLockMaterialAmountText(lock)}</strong>
{source}
</div>
<div>
状态
<strong>
{lock.status === 'pending' ? '待交付,不计利润' : lock.status === 'cancelled' ? '已作废' : '已交付'}
</strong>
</div>
</div>
{renderPriceLockCardFees(lock)}
</>
);
}
function cancelView(result, approval) {
const id = result.lock.id;
return (
<>
<button className={'dialog-close'} data-action={'close-price-lock'} aria-label={'关闭'}>
×
</button>
<div className={'order-header'}>
<div className={'eyebrow'}>VOID PRICE LOCK</div>
<h2>
{approval ? '申请作废' : '作废'} · {result.lock.customer}
</h2>
</div>
{priceLockFacts(result.lock)}
<div className={'note'}>
<strong>录错作废</strong>
<p>
生效后撤销本单有效收款、手填购料与信用卡手续费记账,同日释放料池预留;跨天按原锁定克重和原成本回到实际作废日料池,参与当天加权,历史订单成本不变。保留原单和作废记录。适用于录错单据。
</p>
<p>本操作不登记真实客户退款,也不登记实物退料。</p>
</div>
<form id={'price-lock-cancel-form'}>
<label>
作废原因<textarea name={'reason'} required={true} maxLength={'200'} rows={'2'}></textarea>
</label>
<label className={'check'}>
<input name={'verified'} type={'checkbox'} required={true} />
已核实这是一张录错的待交付锁价单,确认整单作废。
</label>
{approval ? (
<>
<p className={'note'}>提交申请后,店主复核同意才撤销记账;待批期间原锁价单保持有效。</p>
</>
) : (
''
)}
<div className={'actions'}>
{button('返回锁价详情', 'open-price-lock', 'quiet', {
'data-id': id,
})}
<button className={'danger'} type={'submit'}>
{approval ? '提交作废申请' : '确认整单作废'}
</button>
</div>
<div id={'price-lock-action-error'} aria-live={'polite'}></div>
</form>
</>
);
}
function renderPriceLockRelatedOrders(rows) {
const money = value => (value === null ? '待核算' : Number.isSafeInteger(value) ? '¥' + yuan(value) : '未提供');
return (
<>
<section className={'lock-related-orders'}>
<h3>受影响的销售单({rows.length}张)</h3>
<div className={'table-wrap'}>
<table>
<thead>
<tr>
<th>订单</th>
<th>货品成本:当前 → 生效后</th>
<th>利润:当前 → 生效后</th>
</tr>
</thead>
<tbody>
{Children.toArray(
rows.map(row => (
<>
<tr>
<td>
{row.date} · {row.number || row.id}
</td>
<td>
{money(row.before?.goodsCost)} → {money(row.after?.goodsCost)}
</td>
<td>
{money(row.before?.profit)} → {money(row.after?.profit)}
</td>
</tr>
</>
)),
)}
</tbody>
</table>
</div>
</section>
</>
);
}
const validOrderDate = Values.validDate;
const teamMemberKeys = () => Model.memberKeys(state);
function validateRelatedPriceLocks(items) {
if (items === undefined) return [];
const amount = value => value === null || (Number.isSafeInteger(value) && value >= 0);
const snapshot = value =>
value &&
amount(value.materialAmount) &&
['usedMaterialAmount', 'leftoverCost'].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 renderRelatedPriceLocks(items) {
const locks = validateRelatedPriceLocks(items);
if (!locks.length) return '';
const money = value => (value === null ? '待补齐' : '¥' + yuan(value)),
sources = value =>
value.allocations.length
? value.allocations.map(part => teamMemberName(part.payer) + ' ' + money(part.amount)).join(';')
: value.materialAmount === null
? '待补齐后分摊'
: '无分摊金额';
const pair = (name, before, after) => (
<>
<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'}>
<table
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'].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'].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>
</table>
</div>
</>
)),
)}
</section>
</>
);
}
const accountDisplayName = value => {
const id = Model.accountIdentity(state, value);
return id ? Model.memberName(state, id.member) + id.channel : value;
};
function pocketLabel(key) {
return state?.pocketCatalog?.find(row => row.key === key)?.name || String(key ?? '');
}
function renderPriceLockItems(lock) {
const rows = priceLockLines(lock);
return (
<>
<div className={'table-wrap price-lock-items'}>
<table aria-label={'锁价商品明细'}>
<thead>
<tr>
<th>商品</th>
<th className={'number'}>原锁克重</th>
<th className={'number'}>原锁销售金价</th>
<th>工费与附加项目</th>
<th>原锁料费/付款来源</th>
{lock.status === 'delivered' ? (
<>
<th>实际交付</th>
</>
) : (
''
)}
</tr>
</thead>
<tbody>
{Children.toArray(
rows.map((row, index) => {
const item = row.line || {},
delivery = row.delivery;
return (
<>
<tr>
<td>
<strong>{item.name || '黄金'}</strong>
<div className={'small muted'}>
商品 {index + 1}
{item.code ? ' · ' + item.code : ''}
</div>
</td>
<td className={'number'}>{grams(row.locked_mg)}g</td>
<td className={'number'}>¥{yuan(row.sell_rate)}/克</td>
<td>
{item.laborMode === 'piece'
? `件工费 ¥${yuan(item.laborRate ?? 0)} × ${item.pieces || 1}件`
: `克工费 ¥${yuan(item.laborRate ?? 0)}/克`}
{Children.toArray(
(item.charges || []).map(charge => (
<>
<div className={'small muted'}>
{charge.name} ¥{yuan(charge.amount)}
</div>
</>
)),
)}
</td>
<td>{renderPriceLockItemFacts(row)}</td>
{lock.status === 'delivered' ? (
<>
<td>
{delivery
? `${grams(delivery.finalMg ?? delivery.quantity ?? row.locked_mg)}g${
(delivery.extraMg ?? delivery.extra_mg) ? (
<>
<br />
补重 {grams(delivery.extraMg ?? delivery.extra_mg)}g
</>
) : (
''
)
}${
(delivery.leftoverMg ?? delivery.leftover_mg) ? (
<>
<br />
{priceLockUsesPool(row) ? '解除预留回池 ' : '剩料留盘 '}
{grams(delivery.leftoverMg ?? delivery.leftover_mg)}g
</>
) : (
''
)
}${
delivery.inventory?.pocket ? (
<>
<br />
货盘 {pocketLabel(delivery.inventory.pocket)}
</>
) : delivery.pocket ? (
<>
<br />
货盘 {pocketLabel(delivery.pocket)}
</>
) : (
''
)
}`
: '详见销售单'}
</td>
</>
) : (
''
)}
</tr>
</>
);
}),
)}
</tbody>
</table>
</div>
</>
);
}
function renderPriceLockChangeSnapshot(snapshot, title) {
if (!snapshot)
return (
<>
<div>
<h3>{title}</h3>
<p>未提供</p>
</div>
</>
);
const value = snapshot.lock || snapshot,
rows = value.lines || [],
inputRows = rows[0] && !rows[0].line;
if (!inputRows)
return (
<>
<div className={'lock-change-snapshot'}>
<h3>{title}</h3>
<p>
{value.date || ''} · {value.customer || ''} · 开单人 {value.salesperson || '未提供'}
</p>
{renderPriceLockItems(value)}
<p>
预计成交 {Number.isSafeInteger(value.estimated_total) ? '¥' + yuan(value.estimated_total) : '未提供'} ·
已收净额 {Number.isSafeInteger(value.netReceived) ? '¥' + yuan(value.netReceived) : '未提供'} · 整单优惠{' '}
{Number.isSafeInteger(value.discount) ? '¥' + yuan(value.discount) : '未提供'}
</p>
{value.note ? (
<>
<p>客户备注:{value.note}</p>
</>
) : (
''
)}
</div>
</>
);
return (
<>
<div className={'lock-change-snapshot'}>
<h3>{title}</h3>
<p>
{value.date || ''} · {value.customer || ''} · 开单人 {value.salesperson || '未提供'}
</p>
<div className={'table-wrap'}>
<table>
<thead>
<tr>
<th>商品</th>
<th>锁重/售价</th>
<th>销售工费/附加项目</th>
<th>原锁料费/付款人</th>
</tr>
</thead>
<tbody>
{Children.toArray(
rows.map(row => (
<>
<tr>
<td>{row.name || '未提供'}</td>
<td>
{row.quantity || '未提供'}g<br />¥{row.goldPrice ?? '未提供'}/克
</td>
<td>
{row.laborMode === 'piece' ? '件工费' : '克工费'} ¥{row.laborRate ?? '未提供'}
{row.laborMode === 'piece' ? ' × ' + (row.pieces || 1) + '件' : '/克'}
{Children.toArray(
(row.charges || []).map(charge => (
<>
<br />
{charge.name} ¥{charge.amount}
</>
)),
)}
</td>
<td>
{row.material?.source === 'pool' ? (
'当日加权料池'
) : (
<>
手填 ¥{row.material?.rate ?? '未提供'}/克
<br />
{priceLockPayerName(row.material?.payer)}
</>
)}
</td>
</tr>
</>
)),
)}
</tbody>
</table>
</div>
<p>
客户实际付款 ¥{value.payment?.amount ?? '未提供'} · {accountDisplayName(value.payment?.account || '')} ·
整单优惠 ¥{value.discount ?? '未提供'}
</p>
{value.note ? (
<>
<p>客户备注:{value.note}</p>
</>
) : (
''
)}
</div>
</>
);
}
function changeDetail(result, canReview) {
return (
<>
<button className={'dialog-close'} data-action={'price-lock-changes-close'} aria-label={'关闭'}>
×
</button>
<div className={'eyebrow'}>PRICE LOCK REVIEW</div>
<h2>{result.action === 'cancel' ? '录错作废' : '整单修改'}申请</h2>
<p>
{result.requester_name || ''} · {result.created || ''} ·{' '}
{{
pending: '待复核',
approved: '已批准',
rejected: '已驳回',
}[result.status] || result.status}
</p>
<p>申请原因:{result.reason || '未提供'}</p>
{result.stale ? (
<>
<div className={'error'}>原单或关联料池已有变动,本次申请不能直接批准。请驳回后重新核实提交。</div>
</>
) : (
''
)}
{renderPriceLockChangeSnapshot(result.before, '当前原单')}
{result.action === 'edit' ? (
renderPriceLockChangeSnapshot(result.after, '申请修改后')
) : (
<>
<div className={'note'}>
批准后整单作废,撤销有效收款、手填购料及信用卡手续费记账,同日释放预留;跨天按原克重原成本回到批准当天料池,历史订单成本不变。保留原单与作废记录,不登记真实退款或实物退料。
</div>
</>
)}
{result.relatedPriceLocks?.length ? renderRelatedPriceLocks(result.relatedPriceLocks) : ''}
{result.relatedOrders?.length ? renderPriceLockRelatedOrders(result.relatedOrders) : ''}
{result.note ? (
<>
<p>复核备注:{result.note}</p>
</>
) : (
''
)}
<div className={'actions'}>
{button('返回申请列表', 'price-lock-changes-open', 'quiet')}
{button('查看原锁价单', 'price-lock-change-lock', '', {
'data-id': result.price_lock_id,
})}
</div>
{session.user.role === 'owner' && result.status === 'pending' ? (
<>
<form id={'price-lock-review-form'}>
<label>
复核备注
<textarea name={'review_note'} maxLength={'240'} rows={'2'} placeholder={'驳回时必填'}></textarea>
</label>
{canReview ? (
<>
<label className={'check'}>
<input type={'checkbox'} name={'verified'} />
已逐件核对商品、收款、购料与关联影响,确认批准本次申请。
</label>
</>
) : (
''
)}
<div className={'actions'}>
{canReview ? (
<>
<button className={'primary'} name={'decision'} value={'approve'} type={'submit'}>
批准申请
</button>
</>
) : (
''
)}
<button className={'danger'} name={'decision'} value={'reject'} type={'submit'}>
驳回申请
</button>
</div>
<div id={'price-lock-action-error'} aria-live={'polite'}></div>
</form>
</>
) : (
''
)}
</>
);
}
function changeRows(result) {
return result.rows.length ? (
<>
<div className={'table-wrap'}>
<table className={'price-lock-change-list'}>
<thead>
<tr>
<th>原锁价单/客户</th>
<th>申请</th>
<th>申请人/日期</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{Children.toArray(
result.rows.map(row => (
<>
<tr>
<td>
{row.number || row.before?.number || '锁价单'}
<div className={'small muted'}>{row.customer || row.before?.customer || ''}</div>
</td>
<td>
{row.action === 'cancel' ? '录错作废' : '修改整单'}
<div className={'small muted'}>{row.reason || ''}</div>
</td>
<td>
{row.requester_name || row.requester || ''}
<div className={'small muted'}>{row.created || ''}</div>
</td>
<td>
{{
pending: '待店主复核',
approved: '已批准',
rejected: '已驳回',
}[row.status] || row.status}
</td>
<td>
{button('查看申请', 'price-lock-change-open', '', {
'data-id': row.requestId || row.id,
})}
</td>
</tr>
</>
)),
)}
</tbody>
</table>
</div>
</>
) : (
<>
<p className={'empty'}>暂无符合条件的申请。</p>
</>
);
}
function renderPriceLockPendingButtons(lock) {
return ['owner', 'assistant'].includes(session.user.role) ? (
<>
{button('修改', 'edit-price-lock', 'quiet', {
'data-id': lock.id,
})}
{button('作废', 'cancel-price-lock', 'quiet', {
'data-id': lock.id,
})}
</>
) : (
''
);
}
const button = (text, action, cls = '', props = {}) => (
<button type="button" data-action={action} className={cls} {...props}>
{text}
</button>
);
const materialSourceSegmentsText = sources => describeMaterialSources(sources, teamMemberName);
function priceLockMaterialAllocations(lock) {
return priceLockMaterialPending(lock)
? []
: priceLockUsesPool(lock)
? lock.materialPool?.allocations || []
: [
{
payer: lock.buy_payer,
amount: lock.material_amount,
},
];
}
const teamMemberName = key => Model.memberName(state, key, session);
const priceLockPayerName = payer => (payer ? teamMemberName(payer) : '待补');
function priceLockAllocationText(allocations) {
return allocations.map(part => priceLockPayerName(part.payer) + ' ¥' + yuan(part.amount)).join(';');
}
function priceLockMaterialAmountText(lock) {
const amount =
priceLockUsesPool(lock) && Number.isSafeInteger(lock.materialPool?.amount)
? lock.materialPool.amount
: lock.material_amount;
return priceLockMaterialPending(lock) || !Number.isSafeInteger(amount) ? '料费待补' : '¥' + yuan(amount);
}
const priceLockMaterialPending = lock =>
lock?.material_amount === null ||
(priceLockUsesPool(lock) && (lock.materialPool?.status === 'pending' || lock.materialPool?.amount === null));
const priceLockUsesPool = lock => lock?.material_source === 'pool';
function renderPriceLockItemFacts(lock) {
const pool = priceLockUsesPool(lock),
material = lock.materialPool,
pendingMaterial = priceLockMaterialPending(lock);
return (
<>
{lock.status === 'cancelled' ? (
<>
<div className={'small danger-text'}>原录入成本(已撤销记账)</div>
</>
) : (
''
)}
<strong>{priceLockMaterialAmountText(lock)}</strong>
<div className={'small muted'}>
{pool ? '当日加权料池' : '手动独立购料'}
{pendingMaterial ? (
';补足购料后自动核算付款来源'
) : pool ? (
<>
{' '}
· {material?.date || lock.material_pool_id || lock.date}
<br />
{priceLockAllocationText(priceLockMaterialAllocations(lock))}
<br />
{material?.materialSources?.length ? (
<>
{materialSourceSegmentsText(material.materialSources)}
<br />
</>
) : (
''
)}
{material?.frozen ? '已冻结锁价日成本' : '当天补料继续加权'},不重复记购料付款。
</>
) : (
<>
{' '}
· {priceLockPayerName(lock.buy_payer)}
<br />
进货料价 ¥{yuan(lock.buy_rate)}/克
</>
)}
</div>
</>
);
}
const yuan = Model.yuan;
const grams = Model.grams;
function priceLockLines(lock) {
if (!Array.isArray(lock?.lines) || !lock.lines.length) return lock ? [lock] : [];
return lock.lines.map((item, index) => {
const row = {
...lock,
...item,
id: item.id || item.lineId || item.price_lock_line_id,
line: item.line || item,
line_index: index,
parent_id: lock.id,
};
delete row.lines;
return row;
});
}
function listRecords(result, status) {
return result.rows.length ? (
<>
<div className={'table-wrap'}>
<table className={'price-lock-list'}>
<thead>
<tr>
<th>锁价日期/客户</th>
<th>黄金商品</th>
<th className={'number'}>锁定克重</th>
<th className={'number'}>销售金价</th>
<th className={'number'}>已收净额</th>
<th>{status === 'cancelled' ? '原录入成本(已撤销记账)' : '原料来源/成本'}</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{Children.toArray(
result.rows.map(lock => (
<>
<tr>
<td>
{lock.date}
<br />
{lock.customer}
</td>
<td>
{priceLockLines(lock)
.map(row => row.line?.name || '黄金')
.map((part, i) => (
<Fragment key={i}>
{i > 0 && <br />}
{part}
</Fragment>
))}
</td>
<td className={'number'}>
{grams(priceLockLines(lock).reduce((sum, row) => sum + row.locked_mg, 0))}g
</td>
<td className={'number'}>
{priceLockLines(lock)
.map(row => '¥' + yuan(row.sell_rate) + '/克')
.map((part, i) => (
<Fragment key={i}>
{i > 0 && <br />}
{part}
</Fragment>
))}
</td>
<td className={'number'}>¥{yuan(lock.netReceived)}</td>
<td>
{priceLockLines(lock)
.map(row => renderPriceLockItemFacts(row))
.map((part, i) => (
<Fragment key={i}>
{i > 0 && <hr className="lock-row-divider" />}
{part}
</Fragment>
))}
</td>
<td>
<div className={'actions'}>
{button('查看', 'open-price-lock', '', {
'data-id': lock.id,
})}
{lock.status === 'pending' ? (
<>
{button('交付', 'deliver-price-lock', 'primary', {
'data-id': lock.id,
})}
{renderPriceLockPendingButtons(lock)}
</>
) : (
''
)}
</div>
</td>
</tr>
</>
)),
)}
</tbody>
</table>
</div>
</>
) : status === 'cancelled' ? (
<>
<div className={'empty'}>
<strong>目前没有已作废锁价单</strong>作废后保留的原单会显示在这里。
</div>
</>
) : (
<>
<div className={'empty'}>
<strong>目前没有锁价待交付记录</strong>已交付记录会进入订单列表。
</div>
</>
);
}
return {
listRecords,
changeRows,
changeDetail,
cancelView,
detailView,
priceLockFacts,
priceLockLines,
priceLockLineInputs,
priceLockDeliveryCost,
materialSourceSegmentsText,
validateMaterialQuote,
lockQuantityMg,
};
}