仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
790 lines
42 KiB
JavaScript
790 lines
42 KiB
JavaScript
'use strict';
|
||
// 原订单实际售后与独立“售后费用”分开;预览不写账,最终沿用原单变更审批。
|
||
let orderAfterSaleFormEntry = null,
|
||
orderAfterSaleRead = 0;
|
||
let returnedStockLots = [],
|
||
returnedStockLotsUser = '',
|
||
returnedStockLotsRequest = 0,
|
||
returnedStockLotsScope = '';
|
||
function orderAfterSaleRecord(order) {
|
||
return order?.orderAfterSale || null;
|
||
}
|
||
function orderAfterSalePocketKeys() {
|
||
return activePocketKeys().filter(key => state.pocketCatalog?.some(row => row.key === key && row.self === true));
|
||
}
|
||
function invalidateOrderAfterSaleForm() {
|
||
++orderAfterSaleRead;
|
||
orderAfterSaleFormEntry = null;
|
||
}
|
||
function orderAfterSaleActionHTML(order, { blocked = false } = {}) {
|
||
if (
|
||
order.status !== 'delivered' ||
|
||
blocked ||
|
||
orderAfterSaleRecord(order) ||
|
||
order.recovery_id ||
|
||
order.lines.some(line => line.unit !== 'g' || LedgerCalc.isSilver(line.name))
|
||
)
|
||
return '';
|
||
return button('处理售后', 'order-after-sale-open', 'primary order-after-sale-trigger', `data-id="${e(order.id)}"`);
|
||
}
|
||
function orderAfterSaleLegacyActionHTML(order, needsApproval) {
|
||
if (order.lines.some(line => line.priceLockPool)) return '';
|
||
const action = button(
|
||
needsApproval ? '申请整单退货' : '整单退货',
|
||
'show-return',
|
||
'quiet',
|
||
`title="旧入口:仅登记退货,实际退款另行登记"`,
|
||
);
|
||
if (order.lines.some(line => line.unit !== 'g' || LedgerCalc.isSilver(line.name))) return action;
|
||
return `<details class="order-legacy-actions"><summary>旧版退货入口</summary><p class="small muted">原先分开办理退货、退款的入口。实际整单售后请优先使用“处理售后”核对退款、损失和回库。</p>${action}</details>`;
|
||
}
|
||
function orderAfterSaleApproval(date = state.today) {
|
||
return (
|
||
orderAfterSaleFormEntry?.forceApproval || (state.user.role === 'assistant' && !orderActionCanDirect('return', date))
|
||
);
|
||
}
|
||
function orderAfterSaleModeText(date = state.today) {
|
||
return orderAfterSaleApproval(date)
|
||
? '本次提交原订单售后申请,店主同意后一次登记退货、退款、费用与利润调整。复核前原账保持原值。'
|
||
: '核实后一次登记退货、实际退款与售后成本。系统只记账,退款须已在实际账户完成。';
|
||
}
|
||
function orderAfterSaleExpenseHTML(value = {}) {
|
||
return `<div class="order-after-sale-expense grid four">${field('售后成本项目', 'expense_note', value.note || '', 'text', 'required maxlength="150" placeholder="如寄件费、重新编绳"')}${moneyField('实际成本(元)', 'expense_amount', value.amount ?? '')}${choice('实际付款人', 'expense_payer', teamMemberOptions(), value.payer || currentMember())}${button('移除', 'order-after-sale-remove-expense', 'quiet')}</div>`;
|
||
}
|
||
function orderAfterSaleLineHTML(line, index) {
|
||
const pockets = orderAfterSalePocketKeys(),
|
||
pocket = pockets.includes(line.pocket) ? line.pocket : pockets[0] || '';
|
||
return `<article class="order-after-sale-line" data-after-sale-line="${index}"><div class="panel-title"><h3>${index + 1} · ${e(line.name)}</h3><span class="small muted">原出库 ${grams(line.quantity)}g${Number.isSafeInteger(line.stockCount) ? ' · ' + e(stockCountText(line.stockCount)) : pocketCountsEnabled(line.pocket) ? ' · 未记录对数' : ''}</span></div><div class="grid two">${field('实际退回克重(g)', 'return_quantity', grams(line.quantity), 'number', `required min="0.001" max="${grams(line.quantity)}" step="0.001" inputmode="decimal"`)}${choice(
|
||
'退回后的状态',
|
||
'return_disposition',
|
||
[
|
||
['stock', '完好退回现货(保留工费)'],
|
||
['scrap', '退回旧料(工费损失)'],
|
||
],
|
||
'stock',
|
||
)}${choice(
|
||
'实际退入自有货盘',
|
||
'return_pocket',
|
||
pockets.map(key => [key, pocketLabel(key)]),
|
||
pocket,
|
||
)}${stockCountField(pocket, line.stockCount, { name: 'return_count', title: '实际退回数量(对)', help: '按实际清点填写,不使用计工费件数。' })}</div><p class="small muted" data-after-sale-line-note>按实际退重以原料费成本回售后日料池,不新增采购付款。完好现货的原进货工费保留为库存成本,下一单选择对应退回现货时继承。</p></article>`;
|
||
}
|
||
function orderAfterSaleFormHTML(order) {
|
||
const receipts = order.payments?.filter(row => row.kind === 'receipt') || [],
|
||
account =
|
||
receipts.find(
|
||
row =>
|
||
order.payments
|
||
.filter(item => item.account === row.account)
|
||
.reduce((sum, item) => sum + (item.kind === 'receipt' ? item.amount : -item.amount), 0) > 0,
|
||
)?.account || order.payment_account;
|
||
const accounts = activePaymentAccounts(normalizePaymentAccount(account));
|
||
if (account && !accounts.includes(normalizePaymentAccount(account))) accounts.push(normalizePaymentAccount(account));
|
||
const payer = accountIdentity(account)?.member || currentMember();
|
||
return `<form id="order-after-sale-form" class="panel order-after-sale-form" data-order-id="${e(order.id)}"><h2>处理售后</h2><p id="order-after-sale-mode" class="note" aria-live="polite">${e(orderAfterSaleModeText())}</p><div class="grid two">${field('售后日期', 'date', state.today, 'date', `required max="${e(state.today)}"`)}<label>售后原因<textarea name="reason" rows="2" maxlength="200" required placeholder="填写客户实际退货退款原因。"></textarea></label></div><section class="order-after-sale-products"><h3>实物回库</h3>${order.lines.map(orderAfterSaleLineHTML).join('')}</section><section class="order-after-sale-refund internal"><h3>实际退款</h3><div class="grid three">${moneyField('实际退款金额(元,可修改)', 'refund_amount', (order.netReceived / 100).toFixed(2))}${choice('退款账户', 'refund_account', accounts, normalizePaymentAccount(account))}${choice('实际退款付款人', 'refund_payer', teamMemberOptions(), payer)}</div>${field('退款凭据备注(选填)', 'refund_reference', '', 'text', 'maxlength="100"')}<div class="order-after-sale-retained"><span>本次扣留客户款(系统计算)</span><strong id="order-after-sale-retained">¥0.00</strong><small class="muted">原净实收 ¥${yuan(order.netReceived)} − 本次实际退款</small></div><label>扣留款原因<textarea name="deduction_reason" rows="2" maxlength="200" placeholder="有扣留款时填写,如约定扣除不可退工费或实际损耗。"></textarea></label><p class="small muted">扣留款与支付渠道手续费分开核对。原单已经发生的支付手续费、邮费等成本继续保留。</p></section><section class="order-after-sale-expenses internal"><div class="panel-title"><h3>新增售后成本(选填)</h3>${button('+ 添加售后成本', 'order-after-sale-add-expense')}</div><p class="small muted">只填这次新发生且实际已付的成本;原单已记费用不要重复填写。</p><div id="order-after-sale-expenses"></div></section><div class="form-actions">${button('核对售后预览', 'order-after-sale-preview', 'primary')}<span class="small muted" id="order-after-sale-preview-status" aria-live="polite">填好后先预览,核对回库、回料、退款和利润。</span></div><div id="order-after-sale-preview" aria-live="polite"></div><label class="check"><input type="checkbox" name="verified" required disabled>已按实际退回商品、退款凭据和新增成本,核对以下预览。</label><div id="order-after-sale-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="primary" data-order-after-sale-submit disabled>${orderAfterSaleApproval() ? '提交售后申请' : '确认并保存售后'}</button>${button('收起', 'order-after-sale-close', 'quiet')}</div></form>`;
|
||
}
|
||
async function showOrderAfterSaleForm() {
|
||
const { order, data } = requireOrderChangeDetail();
|
||
if (orderAfterSaleRecord(order) || order.status !== 'delivered')
|
||
throw new Error('本单已办理退货或售后,请查看处理记录,不能重复退货退款。');
|
||
if (data.pending || order.cancellationPending || order.ownershipPending)
|
||
throw new Error('本单有待复核申请,请复核完成后再处理售后。');
|
||
if (order.recovery_id) throw new Error('回收/置换订单请从原业务入口处理。');
|
||
const eligibility = data.actions?.return;
|
||
if (eligibility && !eligibility.eligible) throw new Error(eligibility.reason || '本单当前不能办理售后。');
|
||
if (state.user.role === 'assistant') prepareOrderActionChange('return');
|
||
const entry = {
|
||
id: order.id,
|
||
user: orderChangeUser(),
|
||
revision: order.revision,
|
||
request: ++orderAfterSaleRead,
|
||
previewRead: 0,
|
||
preview: null,
|
||
signature: '',
|
||
loading: true,
|
||
};
|
||
orderAfterSaleFormEntry = entry;
|
||
$('#detail-error').innerHTML = '';
|
||
$('#detail-form').innerHTML =
|
||
'<form class="panel"><p role="status">正在读取售后资料…</p>' +
|
||
button('收起', 'order-after-sale-close', 'quiet') +
|
||
'</form>';
|
||
updateOrderDetailNavigation();
|
||
try {
|
||
const context = await api('/api/orders/' + encodeURIComponent(order.id) + '/after-sale');
|
||
if (
|
||
entry !== orderAfterSaleFormEntry ||
|
||
entry.request !== orderAfterSaleRead ||
|
||
entry.user !== orderChangeUser() ||
|
||
currentOrder?.id !== entry.id ||
|
||
currentOrder.revision !== entry.revision
|
||
)
|
||
return;
|
||
if (
|
||
!context ||
|
||
context.orderId !== order.id ||
|
||
context.revision !== order.revision ||
|
||
typeof context.eligible !== 'boolean'
|
||
)
|
||
throw new Error('售后资料未完整返回,请重新读取订单。');
|
||
if (!context.eligible || context.record) throw new Error(context.blockedReason || '本单当前不能重复办理售后。');
|
||
if (!orderAfterSalePocketKeys().length) throw new Error('没有已启用的自有货盘,请先由店主核对货盘设置。');
|
||
if (
|
||
order.lines.some(
|
||
line => line.unit !== 'g' || !line.costParts || line.costParts.material == null || line.costParts.labor == null,
|
||
)
|
||
)
|
||
throw new Error(
|
||
'本入口需明确每件黄金的原料费与工费;按件商品或成本未分项的旧单,请由' +
|
||
teamMemberName('owner') +
|
||
'先核对处理。',
|
||
);
|
||
entry.context = context;
|
||
entry.loading = false;
|
||
$('#detail-form').innerHTML = orderAfterSaleFormHTML(order);
|
||
syncOrderAfterSaleForm();
|
||
$('#detail-form').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||
} catch (err) {
|
||
if (entry === orderAfterSaleFormEntry) {
|
||
entry.loading = false;
|
||
$('#detail-form').innerHTML =
|
||
`<section class="panel"><h2>本单售后需要先核对</h2><div id="order-after-sale-error" aria-live="polite"></div><div class="actions">${button('收起', 'order-after-sale-close', 'quiet')}</div></section>`;
|
||
orderAfterSaleError(err);
|
||
}
|
||
}
|
||
}
|
||
function closeOrderAfterSaleForm() {
|
||
invalidateOrderAfterSaleForm();
|
||
if ($('#order-after-sale-form') || $('#detail-form')?.querySelector?.('[data-action="order-after-sale-close"]'))
|
||
$('#detail-form').innerHTML = '';
|
||
orderDetailSwitchError = '';
|
||
updateOrderDetailNavigation();
|
||
}
|
||
function orderAfterSaleInput(form = $('#order-after-sale-form')) {
|
||
const order = currentOrder,
|
||
entry = orderAfterSaleFormEntry,
|
||
get = name => String(form.querySelector(`[name="${name}"]`)?.value ?? '').trim();
|
||
if (
|
||
!entry ||
|
||
entry.id !== order?.id ||
|
||
entry.user !== orderChangeUser() ||
|
||
entry.revision !== order.revision ||
|
||
form.dataset.orderId !== entry.id
|
||
)
|
||
throw new Error('请重新读取订单后核对售后。');
|
||
const date = get('date'),
|
||
reason = get('reason');
|
||
if (!validOrderDate(date) || date > state.today || date < (order.delivered_date || order.date))
|
||
throw new Error('售后日期应为交付当天至今天之间的有效日期。');
|
||
if (!reason || reason.length > 200) throw new Error('售后原因请填写1~200字。');
|
||
const rows = [...form.querySelectorAll('[data-after-sale-line]')];
|
||
if (rows.length !== order.lines.length) throw new Error('请核对全部退回商品后再提交。');
|
||
const lines = rows.map((row, lineIndex) => {
|
||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
||
original = order.lines[lineIndex],
|
||
quantity = read('return_quantity'),
|
||
mg = materialPoolMg(quantity),
|
||
pocket = read('return_pocket'),
|
||
disposition = read('return_disposition');
|
||
if (!mg || mg > original.quantity)
|
||
throw new Error('商品 ' + (lineIndex + 1) + '实际退回克重须大于0且不超过原出库克重。');
|
||
if (!orderAfterSalePocketKeys().includes(pocket))
|
||
throw new Error('商品 ' + (lineIndex + 1) + '请选择已启用的自有退入货盘。');
|
||
if (!['stock', 'scrap'].includes(disposition)) throw new Error('请选择退回后的实物状态。');
|
||
if (disposition === 'scrap' && pocketCountsEnabled(pocket))
|
||
throw new Error('旧料不恢复成品对数,请选择不按对计数的旧料货盘。');
|
||
const stockCount =
|
||
disposition === 'stock' && pocketCountsEnabled(pocket)
|
||
? stockCountValue(read('return_count'), { title: '商品 ' + (lineIndex + 1) + '实际退回数量(对)' })
|
||
: null;
|
||
if (Number.isSafeInteger(original.stockCount) && stockCount > original.stockCount)
|
||
throw new Error('商品 ' + (lineIndex + 1) + '实际退回对数不能超过原出库对数。');
|
||
return { lineIndex, quantity, pocket, disposition, stockCount };
|
||
});
|
||
const refundAmount = get('refund_amount'),
|
||
refundCents = LedgerCalc.cents(refundAmount, '实际退款金额');
|
||
if (refundCents > order.netReceived) throw new Error('实际退款不能超过本单尚未退回的净实收金额。');
|
||
const deductionReason = get('deduction_reason');
|
||
if (deductionReason.length > 200 || (order.netReceived - refundCents > 0 && !deductionReason))
|
||
throw new Error('有扣留客户款时,请填写1~200字扣留原因。');
|
||
const account = normalizePaymentAccount(get('refund_account')),
|
||
payer = get('refund_payer');
|
||
if (!account || !teamMemberKeys().includes(payer)) throw new Error('请选择退款账户与实际退款付款人。');
|
||
if (payer !== orderAfterSaleAccountPayer(account)) throw new Error('实际退款付款人须与退款账户一致。');
|
||
const reference = get('refund_reference');
|
||
if (reference.length > 100) throw new Error('退款凭据备注最多100字。');
|
||
const expenses = [...form.querySelectorAll('.order-after-sale-expense')].map(row => {
|
||
const read = name => String(row.querySelector(`[name="${name}"]`)?.value ?? '').trim(),
|
||
amount = read('expense_amount'),
|
||
note = read('expense_note'),
|
||
payer = read('expense_payer');
|
||
if (LedgerCalc.cents(amount, '新增售后成本') <= 0) throw new Error('新增售后成本须大于0,没有发生请移除此项。');
|
||
if (!note || note.length > 150 || !teamMemberKeys().includes(payer))
|
||
throw new Error('请填写新增售后成本项目并选择实际付款人。');
|
||
return { amount, payer, note };
|
||
});
|
||
if (expenses.length > 30) throw new Error('一次售后最多填写30项新增成本。');
|
||
return {
|
||
date,
|
||
revision: entry.revision,
|
||
reason,
|
||
verified: true,
|
||
afterSale: { lines, refund: { amount: refundAmount, account, payer, reference }, deductionReason, expenses },
|
||
};
|
||
}
|
||
function syncOrderAfterSaleForm(target = null) {
|
||
const form = $('#order-after-sale-form'),
|
||
entry = orderAfterSaleFormEntry;
|
||
if (!form || !entry) return;
|
||
if (target && target.name !== 'verified') {
|
||
entry.preview = null;
|
||
entry.signature = '';
|
||
entry.previewLoading = false;
|
||
++entry.previewRead;
|
||
const checked = form.querySelector('[name="verified"]');
|
||
if (checked) checked.checked = false;
|
||
if ($('#order-after-sale-preview')) $('#order-after-sale-preview').innerHTML = '';
|
||
if ($('#order-after-sale-preview-status'))
|
||
$('#order-after-sale-preview-status').textContent = '资料已修改,请重新核对售后预览。';
|
||
}
|
||
for (const row of form.querySelectorAll('[data-after-sale-line]')) {
|
||
const pocket = row.querySelector('[name="return_pocket"]')?.value,
|
||
stock = row.querySelector('[name="return_disposition"]')?.value === 'stock';
|
||
syncStockCountField(row, { pocket, name: 'return_count', visible: stock && pocketCountsEnabled(pocket) });
|
||
const note = row.querySelector('[data-after-sale-line-note]');
|
||
if (note)
|
||
note.textContent = stock
|
||
? '实退材料按原料费回售后日料池;原进货工费保留为这件现货的库存成本,再销售时选择对应退回现货继承,不重复付款。'
|
||
: '实退材料按原料费回售后日料池;原进货工费计入本单售后损失,不恢复成品对数。';
|
||
}
|
||
const retained = $('#order-after-sale-retained');
|
||
let amount = null;
|
||
try {
|
||
amount = currentOrder.netReceived - LedgerCalc.cents(form.querySelector('[name="refund_amount"]').value);
|
||
if (retained) retained.textContent = amount < 0 ? '退款超出净实收' : '¥' + yuan(amount);
|
||
} catch {
|
||
if (retained) retained.textContent = '待填写退款金额';
|
||
}
|
||
const reason = form.querySelector('[name="deduction_reason"]');
|
||
if (reason) reason.required = amount > 0;
|
||
if (target?.name === 'refund_account') {
|
||
const payer = form.querySelector('[name="refund_payer"]');
|
||
if (payer) payer.value = orderAfterSaleAccountPayer(target.value);
|
||
}
|
||
const mode = $('#order-after-sale-mode');
|
||
if (mode) mode.textContent = orderAfterSaleModeText(form.querySelector('[name="date"]')?.value);
|
||
const submit = form.querySelector('[data-order-after-sale-submit]');
|
||
if (submit)
|
||
submit.textContent = orderAfterSaleApproval(form.querySelector('[name="date"]')?.value)
|
||
? '提交售后申请'
|
||
: '确认并保存售后';
|
||
applyOrderAfterSaleRestrictions();
|
||
}
|
||
function applyOrderAfterSaleRestrictions() {
|
||
const form = $('#order-after-sale-form'),
|
||
entry = orderAfterSaleFormEntry;
|
||
if (!form) return;
|
||
const blocked = busy || !!pending() || !entry || entry.stale || entry.loading;
|
||
form.querySelectorAll('input,select,textarea,button').forEach(control => {
|
||
control.disabled = control.dataset.action === 'order-after-sale-close' ? busy : blocked;
|
||
});
|
||
for (const row of form.querySelectorAll('[data-after-sale-line]')) {
|
||
row.dataset.stale = String(!!blocked);
|
||
syncStockCountField(row, {
|
||
pocket: row.querySelector('[name="return_pocket"]')?.value,
|
||
name: 'return_count',
|
||
visible:
|
||
row.querySelector('[name="return_disposition"]')?.value === 'stock' &&
|
||
pocketCountsEnabled(row.querySelector('[name="return_pocket"]')?.value),
|
||
});
|
||
}
|
||
const ready = !!entry?.preview && !entry.previewLoading && !blocked;
|
||
const checked = form.querySelector('[name="verified"]'),
|
||
submit = form.querySelector('[data-order-after-sale-submit]');
|
||
if (checked) checked.disabled = !ready;
|
||
if (submit) submit.disabled = !ready;
|
||
const preview = form.querySelector('[data-action="order-after-sale-preview"]');
|
||
if (preview) preview.disabled = blocked || !!entry?.previewLoading;
|
||
}
|
||
async function previewOrderAfterSale() {
|
||
const input = orderAfterSaleInput(),
|
||
entry = orderAfterSaleFormEntry,
|
||
signature = JSON.stringify(input),
|
||
request = (entry.previewRead || 0) + 1;
|
||
entry.previewRead = request;
|
||
entry.previewLoading = true;
|
||
entry.preview = null;
|
||
const form = $('#order-after-sale-form'),
|
||
checkbox = form.querySelector('[name="verified"]');
|
||
if (checkbox) checkbox.checked = false;
|
||
$('#order-after-sale-error').innerHTML = '';
|
||
$('#order-after-sale-preview-status').textContent = '正在按原单成本核对售后…';
|
||
applyOrderAfterSaleRestrictions();
|
||
try {
|
||
const result = await api('/api/orders/' + encodeURIComponent(entry.id) + '/after-sale-preview', input);
|
||
if (
|
||
entry !== orderAfterSaleFormEntry ||
|
||
entry.user !== orderChangeUser() ||
|
||
request !== entry.previewRead ||
|
||
form !== $('#order-after-sale-form')
|
||
)
|
||
return;
|
||
const record = result.afterSale || orderAfterSaleRecord(result.after);
|
||
validateOrderAfterSaleRecord(record);
|
||
if (result.before?.id !== entry.id || result.after?.id !== entry.id || result.before.revision !== entry.revision)
|
||
throw new Error('售后预览与当前订单不一致,请重新读取。');
|
||
entry.preview = result;
|
||
entry.record = record;
|
||
entry.signature = signature;
|
||
$('#order-after-sale-preview').innerHTML = orderAfterSaleSummaryHTML(record, { preview: true });
|
||
$('#order-after-sale-preview-status').textContent = '预览已更新,请核对后勾选确认。';
|
||
} catch (err) {
|
||
if (entry === orderAfterSaleFormEntry && request === entry.previewRead) {
|
||
if ($('#order-after-sale-preview-status'))
|
||
$('#order-after-sale-preview-status').textContent = '预览未完成,请核对提示后重新预览。';
|
||
orderAfterSaleError(err);
|
||
}
|
||
} finally {
|
||
if (entry === orderAfterSaleFormEntry && request === entry.previewRead) {
|
||
entry.previewLoading = false;
|
||
applyOrderAfterSaleRestrictions();
|
||
}
|
||
}
|
||
}
|
||
async function submitOrderAfterSale(form) {
|
||
const { order, data } = requireOrderChangeDetail(),
|
||
entry = orderAfterSaleFormEntry,
|
||
input = orderAfterSaleInput(form);
|
||
if (
|
||
form !== $('#order-after-sale-form') ||
|
||
entry?.stale ||
|
||
entry?.previewLoading ||
|
||
!entry?.preview ||
|
||
entry.signature !== JSON.stringify(input)
|
||
)
|
||
throw new Error('请先重新核对本次售后预览。');
|
||
if (data.pending || order.cancellationPending || orderAfterSaleRecord(order))
|
||
throw new Error('本单已变动或有待复核申请,请重新读取。');
|
||
if (!form.querySelector('[name="verified"]')?.checked)
|
||
throw new Error('请核对售后预览,并勾选实物、实际退款和成本确认。');
|
||
const approval = orderAfterSaleApproval(input.date),
|
||
payload = approval ? { ...input, action: 'return' } : input,
|
||
url = '/api/orders/' + encodeURIComponent(order.id) + (approval ? '/change' : '/return'),
|
||
detailContext = captureOrderDetailReload(order.id);
|
||
entry.submittedDirect = !approval;
|
||
$('#order-after-sale-error').innerHTML = '';
|
||
try {
|
||
const result = await mutate(url, payload);
|
||
return await finishOrderAfterSaleSave(url, payload, result, detailContext);
|
||
} catch (err) {
|
||
orderAfterSaleError(err);
|
||
}
|
||
}
|
||
function orderAfterSaleError(err) {
|
||
const entry = orderAfterSaleFormEntry;
|
||
err.message = err.message.replace('不要重新开单', '不要重复提交售后');
|
||
if (err.status === 403 && entry?.submittedDirect && !pending()) {
|
||
entry.forceApproval = true;
|
||
entry.submittedDirect = false;
|
||
const checkbox = $('#order-after-sale-form [name="verified"]');
|
||
if (checkbox) checkbox.checked = false;
|
||
syncOrderAfterSaleForm();
|
||
err.message += ' 输入已保留,重新核实后提交店主复核。';
|
||
} else if ([403, 404, 409].includes(err.status) && entry) {
|
||
entry.stale = true;
|
||
entry.preview = null;
|
||
const checked = $('#order-after-sale-form [name="verified"]');
|
||
if (checked) checked.checked = false;
|
||
}
|
||
const target = $('#order-after-sale-error') || $('#detail-error');
|
||
if (target)
|
||
target.innerHTML = `<div class="error">${e(err.message)}${pending() ? ' ' + button('恢复原操作', 'retry', 'danger') : entry?.id ? ' ' + button('重新读取订单', 'reload-order-change', '', `data-id="${e(entry.id)}"`) : ''}</div>`;
|
||
applyOrderAfterSaleRestrictions();
|
||
toast(err.message, true);
|
||
}
|
||
async function finishOrderAfterSaleSave(url, input, result, detailContext) {
|
||
if (url.endsWith('/change')) return await finishOrderChangeSave(url, input, result, detailContext);
|
||
const id = result.id || result.order?.id || currentOrder?.id;
|
||
invalidateOrderAfterSaleForm();
|
||
invalidateMaterialPools();
|
||
invalidateReport();
|
||
returnedStockLots = [];
|
||
returnedStockLotsScope = '';
|
||
if ($('#detail-form')) $('#detail-form').innerHTML = '';
|
||
if ($('#order-content'))
|
||
$('#order-content').innerHTML =
|
||
`<section class="panel"><h2>售后已保存</h2><p>退货、退款与售后成本已经按本次核实结果记账。</p>${button('重新读取订单', 'reload-order-change', 'primary', `data-id="${e(id)}"`)}</section>`;
|
||
try {
|
||
await refreshOrderDetailAfterSave(id, detailContext);
|
||
toast('售后已保存');
|
||
} catch {
|
||
toast('售后已保存,最新资料暂未读到。请重新读取订单,不要重复办理。', true);
|
||
}
|
||
}
|
||
function validateOrderAfterSaleRecord(record) {
|
||
if (
|
||
!record ||
|
||
!Array.isArray(record.lines) ||
|
||
!record.lines.length ||
|
||
!record.lines.every(line =>
|
||
['quantity', 'materialReturnedCost', 'laborRestockedCost', 'costLoss'].every(key =>
|
||
Number.isSafeInteger(line[key]),
|
||
),
|
||
) ||
|
||
!record.summary ||
|
||
![
|
||
'refundAmount',
|
||
'retainedAmount',
|
||
'materialReturnedCost',
|
||
'laborRestockedCost',
|
||
'costLoss',
|
||
'directCost',
|
||
'profit',
|
||
'profitAdjustment',
|
||
].every(key => Number.isSafeInteger(record.summary[key]))
|
||
)
|
||
throw new Error('售后核算资料未完整返回,请重新读取订单。');
|
||
return record;
|
||
}
|
||
function orderAfterSaleAccountPayer(account) {
|
||
return accountIdentity(account)?.member || currentMember();
|
||
}
|
||
function orderAfterSaleSummaryHTML(raw, { preview = false } = {}) {
|
||
const record = validateOrderAfterSaleRecord(raw),
|
||
summary = record.summary,
|
||
money = value => '¥' + yuan(value),
|
||
facts = [
|
||
['实际退款', summary.refundAmount],
|
||
['扣留客户款', summary.retainedAmount],
|
||
['回料池原料成本', summary.materialReturnedCost],
|
||
['现货保留工费', summary.laborRestockedCost],
|
||
['本单货品成本损失', summary.costLoss],
|
||
['售后最终利润', summary.profit],
|
||
['本次售后利润调整', summary.profitAdjustment],
|
||
];
|
||
return `<section class="order-after-sale-summary${preview ? ' is-preview' : ''}" aria-label="${preview ? '售后核对预览' : '已保存售后详情'}"><div class="panel-title"><h3>${preview ? '售后核对预览' : '售后处理结果'}</h3><span class="badge">${preview ? '尚未保存' : '已记账'}</span></div><dl class="order-after-sale-totals">${facts.map(([name, amount]) => `<div><dt>${e(name)}</dt><dd${amount < 0 ? ' class="danger-text"' : ''}>${money(amount)}</dd></div>`).join('')}</dl><div class="table-wrap"><table aria-label="逐件售后回库与成本"><thead><tr><th>商品与实际去向</th><th>实际退回</th><th>回料成本</th><th>保留工费</th><th>成本损失</th></tr></thead><tbody>${record.lines.map(line => `<tr><td>${e(line.name || '商品 ' + (line.lineIndex + 1))}<div class="small muted">${e(pocketLabel(line.pocket))} · ${line.disposition === 'stock' ? '完好现货' : '旧料/损坏'}</div></td><td>${grams(line.quantity)}g${line.disposition === 'stock' && pocketCountsEnabled(line.pocket) ? '<div class="small">' + e(stockCountText(line.stockCount)) + '</div>' : ''}</td><td>${money(line.materialReturnedCost)}</td><td>${money(line.laborRestockedCost)}</td><td>${money(line.costLoss)}</td></tr>`).join('')}</tbody></table></div><p class="small muted">实退材料按原成本回售后日料池,不新增采购付款。完好现货工费留在退回现货批次;旧料工费与未退回材料成本计损失。原单实际费用继续保留。</p></section>`;
|
||
}
|
||
function orderAfterSaleDetailHTML(order) {
|
||
const record = orderAfterSaleRecord(order);
|
||
if (!record) return '';
|
||
try {
|
||
return `<section class="panel order-after-sale-detail"><div class="panel-title"><h2>已处理售后</h2><span class="small muted">售后日 ${e(record.date || order.returned_date)}</span></div><p class="change-reason">售后原因:${e(record.reason)}</p>${orderAfterSaleSummaryHTML(record)}<dl class="order-after-sale-facts"><div><dt>实际退款账户/付款人</dt><dd>${e(accountDisplayName(record.refund?.account))} · ${e(teamMemberName(record.refund?.payer))}</dd></div>${record.deductionReason ? `<div><dt>扣留原因</dt><dd>${e(record.deductionReason)}</dd></div>` : ''}${record.refund?.reference ? `<div><dt>退款凭据备注</dt><dd>${e(record.refund.reference)}</dd></div>` : ''}</dl>${record.expenses?.length ? `<h3>本次新增售后成本</h3><ul>${record.expenses.map(item => `<li>${e(item.note)} · ¥${yuan(item.amount)} · ${e(teamMemberName(item.payer))}支付</li>`).join('')}</ul>` : '<p class="small muted">本次没有新增售后成本。</p>'}</section>`;
|
||
} catch (err) {
|
||
return `<section class="panel"><h2>已处理售后</h2><p class="danger-text">${e(err.message)}</p>${button('重新读取订单', 'reload-order-change', '', `data-id="${e(order.id)}"`)}</section>`;
|
||
}
|
||
}
|
||
function orderAfterSaleCostsHTML(order) {
|
||
const record = orderAfterSaleRecord(order),
|
||
summary = record.summary,
|
||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost,
|
||
total = summary.costLoss + direct;
|
||
return `<section class="panel detail-costs" aria-label="售后保留成本"><div class="panel-title"><h2>售后成本怎么算</h2><span class="small muted">原真实费用继续保留</span></div><div class="detail-total-row"><span>货品成本损失</span><b>¥${yuan(summary.costLoss)}</b></div><div class="detail-total-row"><span>原单费用与新增售后成本</span><b>¥${yuan(direct)}</b></div><div class="detail-total-row detail-total-final"><span>售后保留成本</span><strong>¥${yuan(total)}</strong></div><p class="small muted">回料成本 ¥${yuan(summary.materialReturnedCost)} 与现货保留工费 ¥${yuan(summary.laborRestockedCost)} 回到库存,不计本单损失。</p><details><summary>查看原货品成本与费用记录</summary>${orderCostRowsHTML(LedgerCalc.orderCosts(order).rows, '原货品成本与实际费用')}</details></section>`;
|
||
}
|
||
function orderAfterSaleProfitHTML(order) {
|
||
const summary = orderAfterSaleRecord(order).summary,
|
||
direct = Number.isSafeInteger(summary.directCost) ? summary.directCost : order.directCost;
|
||
return `<section class="panel detail-profit detail-profit-known" aria-label="售后最终利润"><div class="detail-profit-heading"><h2>售后最终利润</h2><strong>¥${yuan(summary.profit)}</strong></div><p class="detail-profit-formula">扣留客户款 ¥${yuan(summary.retainedAmount)} − 货品成本损失 ¥${yuan(summary.costLoss)} − 已发生费用 ¥${yuan(direct)} = ¥${yuan(summary.profit)}</p><p class="small muted">本次售后利润调整 ¥${yuan(summary.profitAdjustment)},记在售后日期;原成交计算保留供追溯。</p></section>`;
|
||
}
|
||
function orderAfterSaleOperation(url, input) {
|
||
return !!input?.afterSale && /^\/api\/orders\/[^/]+\/(?:return|change)$/.test(url);
|
||
}
|
||
async function orderAfterSaleAction(action, source) {
|
||
try {
|
||
if (action === 'order-after-sale-open') return await showOrderAfterSaleForm();
|
||
if (action === 'order-after-sale-close') return closeOrderAfterSaleForm();
|
||
if (action === 'order-after-sale-preview') return await previewOrderAfterSale();
|
||
if (action === 'order-after-sale-add-expense') {
|
||
const root = $('#order-after-sale-expenses');
|
||
if (root.children.length >= 30) throw new Error('一次售后最多填写30项新增成本。');
|
||
root.insertAdjacentHTML('beforeend', orderAfterSaleExpenseHTML());
|
||
syncOrderAfterSaleForm(source);
|
||
return;
|
||
}
|
||
if (action === 'order-after-sale-remove-expense') {
|
||
source.closest('.order-after-sale-expense')?.remove();
|
||
syncOrderAfterSaleForm(source);
|
||
return;
|
||
}
|
||
if (action === 'order-after-sale-reload-stock') return await loadReturnedStockLots(true);
|
||
} catch (err) {
|
||
orderAfterSaleError(err);
|
||
}
|
||
}
|
||
function returnedStockScope(form = $('#order-form')) {
|
||
return form
|
||
? JSON.stringify({
|
||
user: orderChangeUser(),
|
||
member: form.querySelector('[name="member"]')?.value || currentMember(),
|
||
date: form.querySelector('[name="date"]')?.value || state.today,
|
||
})
|
||
: '';
|
||
}
|
||
function returnedStockLotChoiceHTML(line = {}) {
|
||
return `<div class="returned-stock-choice" data-returned-stock-choice ${line.returnedStockId ? '' : 'hidden'}><label>售后退回现货(已有工费)<select name="returnedStockId"><option value="">普通现货/本次新采购</option>${line.returnedStockId ? `<option value="${e(line.returnedStockId)}" selected>正在核对原退回现货…</option>` : ''}</select></label><p class="small muted" data-returned-stock-note>选择对应退回现货后,沿用原工费和付款来源,不重复登记工费付款。</p>${button('刷新退回现货', 'order-after-sale-reload-stock', 'quiet')}</div>`;
|
||
}
|
||
function returnedStockLotOptions(row) {
|
||
const selected = row.querySelector('[name="returnedStockId"]')?.value || '',
|
||
form = $('#order-form'),
|
||
date = form?.querySelector('[name="date"]')?.value || state.today;
|
||
const lots =
|
||
returnedStockLotsUser === orderChangeUser() && returnedStockLotsScope === returnedStockScope(form)
|
||
? returnedStockLots.filter(
|
||
lot =>
|
||
lot.available === true &&
|
||
lot.remainingMg > 0 &&
|
||
activePocketKeys().includes(lot.pocket) &&
|
||
(!lot.date || lot.date <= date),
|
||
)
|
||
: [];
|
||
const used = new Set(
|
||
[...(form?.querySelectorAll?.('[name="returnedStockId"]') || [])]
|
||
.filter(select => select !== row.querySelector('[name="returnedStockId"]'))
|
||
.map(select => select.value)
|
||
.filter(Boolean),
|
||
);
|
||
return lots.map(lot => [
|
||
lot.id,
|
||
`${lot.date} · ${lot.name} · ${grams(lot.remainingMg)}g${Number.isSafeInteger(lot.remainingCount) ? ' · ' + stockCountText(lot.remainingCount) : ''} · 已有工费 ¥${yuan(lot.laborCost)}`,
|
||
used.has(lot.id),
|
||
]);
|
||
}
|
||
function refreshReturnedStockChoices() {
|
||
const form = $('#order-form');
|
||
if (!form || form.dataset.orderEdit === 'true') return;
|
||
for (const row of form.querySelectorAll('.line-item')) {
|
||
const box = row.querySelector('[data-returned-stock-choice]'),
|
||
select = row.querySelector('[name="returnedStockId"]');
|
||
if (!box || !select) continue;
|
||
const selected = select.value,
|
||
options = returnedStockLotOptions(row),
|
||
exists = options.some(option => option[0] === selected);
|
||
select.innerHTML = opts(
|
||
[
|
||
['', '普通现货/本次新采购'],
|
||
...options,
|
||
...(selected && !exists ? [[selected, '原退回现货已无可用库存,请重新选择', true]] : []),
|
||
],
|
||
selected,
|
||
);
|
||
box.hidden = !options.length && !selected;
|
||
if (selected) syncReturnedStockCost(row);
|
||
}
|
||
}
|
||
async function loadReturnedStockLots(force = false) {
|
||
const form = $('#order-form');
|
||
if (!form || form.dataset.orderEdit === 'true') return;
|
||
const scope = returnedStockScope(form),
|
||
user = orderChangeUser();
|
||
if (!force && returnedStockLotsUser === user && returnedStockLotsScope === scope) {
|
||
refreshReturnedStockChoices();
|
||
return;
|
||
}
|
||
const request = ++returnedStockLotsRequest,
|
||
member = form.querySelector('[name="member"]')?.value || currentMember(),
|
||
date = form.querySelector('[name="date"]')?.value || state.today;
|
||
try {
|
||
const result = await api('/api/returned-stock-lots?' + new URLSearchParams({ member, date }));
|
||
if (
|
||
request !== returnedStockLotsRequest ||
|
||
scope !== returnedStockScope() ||
|
||
user !== orderChangeUser() ||
|
||
form !== $('#order-form')
|
||
)
|
||
return;
|
||
if (
|
||
!result ||
|
||
!Array.isArray(result.lots) ||
|
||
result.lots.some(
|
||
lot =>
|
||
typeof lot.id !== 'string' ||
|
||
!Number.isSafeInteger(lot.remainingMg) ||
|
||
!Number.isSafeInteger(lot.laborCost) ||
|
||
!teamMemberKeys().includes(lot.laborPayer),
|
||
)
|
||
)
|
||
throw new Error('售后退回现货列表未完整返回。');
|
||
returnedStockLots = result.lots;
|
||
returnedStockLotsUser = user;
|
||
returnedStockLotsScope = scope;
|
||
refreshReturnedStockChoices();
|
||
updateTotal();
|
||
} catch (err) {
|
||
if (request !== returnedStockLotsRequest || form !== $('#order-form') || user !== orderChangeUser()) return;
|
||
for (const row of form.querySelectorAll('.line-item')) {
|
||
const note = row.querySelector('[data-returned-stock-note]'),
|
||
box = row.querySelector('[data-returned-stock-choice]');
|
||
if (note) {
|
||
if (box) box.hidden = false;
|
||
note.textContent = err.message + ' 如本次销售售后退回现货,请刷新列表后选择对应批次。';
|
||
note.classList.add('danger-text');
|
||
}
|
||
}
|
||
}
|
||
}
|
||
function applyReturnedStockSelection(row) {
|
||
const select = row?.querySelector('[name="returnedStockId"]');
|
||
if (!select) return;
|
||
const id = select.value,
|
||
get = name => row.querySelector(`[name="${name}"]`),
|
||
keys = [
|
||
'nameType',
|
||
'customName',
|
||
'unit',
|
||
'quantity',
|
||
'pocket',
|
||
'stockCount',
|
||
'cost-laborMode',
|
||
'cost-laborRate',
|
||
'cost-labor',
|
||
'cost-laborPayer',
|
||
'cost-materialSource',
|
||
'cost-materialPoolId',
|
||
];
|
||
const set = (name, value) => {
|
||
const input = get(name);
|
||
if (input) input.value = value ?? '';
|
||
};
|
||
if (!id) {
|
||
if (row.dataset.returnedStockOriginal) {
|
||
const original = JSON.parse(row.dataset.returnedStockOriginal);
|
||
for (const key of keys) if (Object.hasOwn(original, key)) set(key, original[key]);
|
||
}
|
||
delete row.dataset.returnedStockApplied;
|
||
delete row.dataset.returnedStockOriginal;
|
||
delete row.dataset.returnedStockCode;
|
||
const note = row.querySelector('[data-returned-stock-note]');
|
||
if (note) note.textContent = '选择对应退回现货后,沿用原工费和付款来源,不重复登记工费付款。';
|
||
for (const name of keys) {
|
||
const input = get(name);
|
||
if (input) {
|
||
input.disabled = false;
|
||
input.readOnly = false;
|
||
}
|
||
}
|
||
const funding = row.querySelector('.purchase-labor .cost-funding');
|
||
if (funding) funding.hidden = false;
|
||
refreshReturnedStockChoices();
|
||
return;
|
||
}
|
||
const lot = returnedStockLots.find(item => item.id === id && item.available === true);
|
||
if (!lot) throw new Error('这件退回现货已不可用,请刷新页面后重新核对。');
|
||
if (
|
||
[...$('#order-form').querySelectorAll('[name="returnedStockId"]')].some(
|
||
other => other !== select && other.value === id,
|
||
)
|
||
)
|
||
throw new Error('同一件退回现货不能在本单重复选择。');
|
||
if (!row.dataset.returnedStockOriginal)
|
||
row.dataset.returnedStockOriginal = JSON.stringify(
|
||
Object.fromEntries(keys.filter(name => get(name)).map(name => [name, get(name).value])),
|
||
);
|
||
if (row.dataset.legacy === 'true') throw new Error('旧版未分项成本请先拆分,再选择退回现货。');
|
||
set('nameType', productNames.includes(lot.name) ? lot.name : '其他');
|
||
set('customName', productNames.includes(lot.name) ? '' : lot.name);
|
||
set('unit', 'g');
|
||
set('quantity', grams(lot.remainingMg));
|
||
set('pocket', lot.pocket);
|
||
set('stockCount', lot.remainingCount ?? lot.stockCount ?? '');
|
||
const poolId = lot.effectivePoolId || $('#order-form [name="date"]')?.value || state.today,
|
||
controls = row.querySelector('.material-source-controls'),
|
||
poolSelect = get('cost-materialPoolId');
|
||
if (controls) {
|
||
controls.dataset.defaultDate = 'false';
|
||
controls.dataset.poolId = poolId;
|
||
controls.dataset.preferredSource = 'pool';
|
||
}
|
||
if (poolSelect && !poolSelect.querySelector(`option[value="${poolId}"]`))
|
||
poolSelect.insertAdjacentHTML('beforeend', `<option value="${e(poolId)}">${e(poolId)}</option>`);
|
||
set('cost-materialSource', 'pool');
|
||
set('cost-materialPoolId', poolId);
|
||
set('cost-laborMode', 'total');
|
||
set('cost-laborRate', '');
|
||
set('cost-labor', (lot.laborCost / 100).toFixed(2));
|
||
set('cost-laborPayer', lot.laborPayer);
|
||
row.dataset.returnedStockApplied = id;
|
||
row.dataset.returnedStockCode = lot.code || '';
|
||
syncReturnedStockCost(row);
|
||
refreshReturnedStockChoices();
|
||
}
|
||
function syncReturnedStockCost(row) {
|
||
const id = row.querySelector('[name="returnedStockId"]')?.value;
|
||
if (!id) return;
|
||
const lot = returnedStockLots.find(item => item.id === id && item.available === true),
|
||
get = name => row.querySelector(`[name="${name}"]`);
|
||
if (!lot) return;
|
||
const locked = [
|
||
'nameType',
|
||
'customName',
|
||
'unit',
|
||
'quantity',
|
||
'pocket',
|
||
'stockCount',
|
||
'cost-laborMode',
|
||
'cost-laborRate',
|
||
'cost-labor',
|
||
'cost-laborPayer',
|
||
'cost-materialSource',
|
||
'cost-materialPoolId',
|
||
];
|
||
for (const name of locked) {
|
||
const input = get(name);
|
||
if (input) {
|
||
if (input.tagName === 'SELECT') input.disabled = true;
|
||
else input.readOnly = true;
|
||
}
|
||
}
|
||
const funding = row.querySelector('.purchase-labor .cost-funding');
|
||
if (funding) {
|
||
funding.hidden = true;
|
||
for (const input of funding.querySelectorAll('input,select')) input.disabled = true;
|
||
}
|
||
const note = row.querySelector('[data-returned-stock-note]');
|
||
if (note) {
|
||
note.classList.remove('danger-text');
|
||
note.textContent = `本件已有进货工费 ¥${yuan(lot.laborCost)},沿用${teamMemberName(lot.laborPayer)}原付款来源,不新增付款。按原克重整批出库。${lot.materialPoolNotice || '料费按本单使用的料池计算。'}`;
|
||
}
|
||
}
|
||
function returnedStockLineInput(row, values) {
|
||
const id = row.querySelector('[name="returnedStockId"]')?.value;
|
||
if (!id) {
|
||
delete values.returnedStockId;
|
||
return values;
|
||
}
|
||
const lot = returnedStockLots.find(item => item.id === id && item.available === true);
|
||
if (!lot || returnedStockLotsScope !== returnedStockScope()) return { ...values, returnedStockId: id };
|
||
return {
|
||
...values,
|
||
returnedStockId: id,
|
||
code: lot.code || '',
|
||
name: lot.name,
|
||
unit: 'g',
|
||
quantity: grams(lot.remainingMg),
|
||
pocket: lot.pocket,
|
||
...(pocketCountsEnabled(lot.pocket)
|
||
? { stockCount: lot.remainingCount ?? lot.stockCount }
|
||
: { stockCount: undefined }),
|
||
costParts: { ...values.costParts, labor: (lot.laborCost / 100).toFixed(2) },
|
||
costLabor: { mode: 'total' },
|
||
costPayers: { ...values.costPayers, labor: lot.laborPayer },
|
||
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId || $('#order-form [name="date"]')?.value || state.today },
|
||
costFundings: undefined,
|
||
};
|
||
}
|
||
function validateReturnedStockSelections(form) {
|
||
const selected = [...form.querySelectorAll('[name="returnedStockId"]')].map(select => select.value).filter(Boolean);
|
||
if (!selected.length) return;
|
||
if (form.dataset.orderEdit === 'true') return;
|
||
if (
|
||
returnedStockLotsUser !== orderChangeUser() ||
|
||
returnedStockLotsScope !== returnedStockScope(form) ||
|
||
selected.some(
|
||
id =>
|
||
!returnedStockLots.some(
|
||
lot => lot.id === id && lot.available === true && activePocketKeys().includes(lot.pocket),
|
||
),
|
||
)
|
||
)
|
||
throw new Error('所选售后退回现货需要重新核对,请刷新现货列表。');
|
||
if (new Set(selected).size !== selected.length) throw new Error('同一件售后退回现货不能重复开单。');
|
||
}
|