Files
weiguang-jewelry-ledger/新账系统/public/order-changes-ui.js
T

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

832 lines
46 KiB
JavaScript
Raw Normal View History

'use strict';
// 助理修改已保存订单时先留申请;复核通过才由服务端更正原单。
let orderChangeDetail = null,
orderChangeFormEntry = null,
orderActionChangeEntry = null;
let orderChangeCountRequest = 0,
orderChangeListRequest = 0,
orderChangeListStatus = 'pending';
const orderChangeStatus = { pending: '待店主复核', approved: '已同意变更', rejected: '已驳回' };
const orderChangeActionLabels = {
edit: '修改订单',
expense: '费用补记',
fees: '旧费用核实',
refund: '退款',
return: '退货',
cost: '成本补录',
};
function orderChangeActionLabel(request) {
if ((request.action_input || request.action_details)?.afterSale) return '处理订单售后';
return request.action_label || orderChangeActionLabels[request.action || 'edit'] || '订单变更';
}
function orderActionUsesChangeForm(kind) {
return state.user.role === 'assistant' && ['expense', 'fees', 'refund', 'return', 'cost'].includes(kind);
}
function orderActionCanDirect(kind, date = state.today, order = currentOrder) {
const data = currentOrderChange(order)?.data,
entry = orderActionChangeEntry;
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 &&
!(entry?.id === order.id && entry.kind === kind && entry.forceApproval)
);
}
function orderActionRequiresApproval(kind, date = state.today) {
return orderActionUsesChangeForm(kind) && !orderActionCanDirect(kind, date);
}
function orderChangeUser() {
return session?.user?.id || '';
}
function orderChangeTime(value) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN');
}
function validateOrderChangeRequest(request, orderId) {
const validSnapshot = order =>
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 => 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'].every(
side =>
request.summary?.[side] &&
['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(request.summary[side][key])) &&
['goodsCost', 'profit', 'settlementDue'].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'].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 useOrderChangeDetail(order, result, error) {
orderChangeFormEntry = null;
orderActionChangeEntry = null;
const entry = { id: order.id, user: orderChangeUser(), revision: order.revision, data: null, error: '' };
try {
if (error) throw error;
if (
!result ||
typeof result.eligible !== 'boolean' ||
typeof result.canApprove !== 'boolean' ||
!Number.isSafeInteger(result.revision) ||
!Array.isArray(result.requests) ||
(result.pending !== null && typeof result.pending !== 'object')
)
throw new Error('修改复核资料尚未完整返回,请重新读取。');
if (result.revision !== order.revision) throw new Error('订单已有新记录,请重新读取订单后复核修改申请。');
result.requests.forEach(request => validateOrderChangeRequest(request, order.id));
if (result.pending) validateOrderChangeRequest(result.pending, order.id);
entry.data = result;
} catch (err) {
entry.error = err.name === 'AbortError' ? '修改申请读取超时,请重新读取。' : err.message;
}
orderChangeDetail = entry;
return entry;
}
function currentOrderChange(order = currentOrder) {
return order &&
orderChangeDetail?.id === order.id &&
orderChangeDetail.user === orderChangeUser() &&
orderChangeDetail.revision === order.revision
? orderChangeDetail
: null;
}
function orderChangePending(order) {
return currentOrderChange(order)?.data?.pending || order?.changePending || null;
}
function orderChangeHistoryHTML(request) {
return `<li><div class="change-record-title"><strong>${e(orderChangeStatus[request.status])}</strong><span class="badge">${e(orderChangeActionLabel(request))}</span>${request.stale && request.status === 'pending' ? '<span class="badge danger">订单已有变动</span>' : ''}</div><div>申请人:${e(request.requester_name)} · ${e(orderChangeTime(request.created))}</div><p class="change-reason">申请原因:${e(request.reason)}</p>${request.status !== 'pending' ? `<div class="small muted">复核人:${e(request.reviewer_name || '未提供')} · ${e(orderChangeTime(request.reviewed))}${request.note ? `<p class="change-reason">${request.status === 'rejected' ? '驳回意见' : '复核备注'}:${e(request.note)}</p>` : ''}</div>` : ''}<details><summary>查看本次原值与申请值</summary>${orderChangeActionSummaryHTML(request)}${orderChangeComparisonHTML(request)}</details></li>`;
}
function orderChangeDetailHTML(order) {
const entry = currentOrderChange(order),
data = entry?.data,
request = orderChangePending(order);
if (!data)
return `<section class="panel order-change-panel"><h2>变更申请与复核</h2><p class="${entry?.error ? 'danger-text' : 'muted'}" role="status">${e(entry?.error || '变更申请资料尚未读取,请先重新读取订单。')}</p>${button('重新读取订单', 'reload-order-change', '', `data-id="${e(order.id)}"`)}</section>`;
if (!request && !data.requests.length) return '';
const canReview = state.user.role === 'owner' && data.canApprove && request?.status === 'pending';
return `<section class="panel order-change-panel" id="order-change-panel"><div class="panel-title"><h2>变更申请与复核</h2>${request ? '<span class="badge warn">待店主复核</span>' : ''}</div>${request ? `<p><strong>本次申请:${e(orderChangeActionLabel(request))}。</strong>申请期间仍按原订单计账,本次申请尚未生效。店主同意后才更新原单;复核完成前暂停本单其他记账和取消申请。</p>${request.stale ? '<div class="error" role="status">订单在申请后已有变动,原申请不能同意。请店主驳回后按最新订单重新申请。</div>' : ''}${canReview ? `<div class="actions">${!request.stale ? button('查看变更并复核', 'approve-order-change', 'primary', `data-id="${e(request.id)}"`) : ''}${button('驳回变更申请', 'reject-order-change', '', `data-id="${e(request.id)}"`)}</div>` : '<p class="small muted">由店主账号核对原值与申请值后复核。</p>'}` : ''}<details ${request ? 'open' : ''}><summary>变更申请与复核记录(${data.requests.length})</summary><ul class="timeline change-history">${data.requests.map(orderChangeHistoryHTML).join('')}</ul></details></section>`;
}
function orderChangeMoney(value) {
return value == null ? '待补齐' : '¥' + yuan(value);
}
function orderChangePayer(value) {
return value ? teamMemberName(value) : '待补齐';
}
function orderChangeCell(value) {
return e(value == null || value === '' ? '未填写' : value).replace(/\n/g, '<br>');
}
function orderChangePair(title, before, after) {
const changed = String(before ?? '') !== String(after ?? '');
return `<tr${changed ? ' class="order-change-modified"' : ''}><th scope="row">${e(title)}${changed ? '<span class="change-mark">已修改</span>' : ''}</th><td>${orderChangeCell(before)}</td><td>${orderChangeCell(after)}</td></tr>`;
}
function orderChangeLineValue(line, kind) {
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 orderChangeEffectiveExpenses(order) {
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) {
return (
orderChangeEffectiveExpenses(order)
.map(
row =>
`${row.date} · ${row.note || '实际费用'}\n${orderChangeMoney(row.amount)} · ${orderChangePayer(row.payer)}支付`,
)
.join('\n\n') || '无已记费用'
);
}
function orderChangePaymentsValue(order) {
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 orderChangeInputMoney(value) {
try {
return orderChangeMoney(LedgerCalc.cents(value));
} catch {
return '金额未提供';
}
}
function orderChangeActionSummaryHTML(request) {
const action = request.action || 'edit',
input = request.action_input || request.action_details || {};
if (action === 'edit') return '';
if (input.afterSale && typeof orderAfterSaleSummaryHTML === 'function') {
const record = orderAfterSaleRecord(request.after);
return `<section class="order-change-action-summary"><h3>本次售后申请</h3><p>售后日期:${e(input.date)} · 申请原因:${e(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 class="order-change-action-summary"><h3>本次申请动作</h3><dl class="order-change-action-facts">${facts.map(([title, value]) => `<div><dt>${e(title)}</dt><dd>${orderChangeCell(value)}</dd></div>`).join('')}</dl><p class="small muted">下方对照为服务器试算;批准后才登记这笔变更,不会由系统发起真实收款、退款或转账。</p></section>`;
}
function orderChangeInventoryHTML(inventory) {
if (!inventory) return '';
const table = (title, rows, changes = false) =>
`<h3>${title}</h3>${rows.length ? `<div class="table-wrap"><table class="order-change-inventory"><thead><tr><th>日期</th><th>货盘</th>${changes ? '' : '<th>库存业务</th>'}<th class="number">${changes ? '本次增减' : '已记克重'}</th></tr></thead><tbody>${rows.map(row => `<tr><td>${e(row.date)}</td><td>${e(pocketLabel(row.pocket))}</td>${changes ? '' : `<td>${e(row.kind || '未提供')}</td>`}<td class="number">${row.mg > 0 ? '+' : ''}${grams(row.mg)}g${inventoryCountHTML(row, { signed: true })}</td></tr>`).join('')}</tbody></table></div>` : `<p class="small muted">${changes ? '本次没有黄金货盘净变动。' : '没有本单库存流水。'}</p>`}`;
return `<section class="order-change-inventory-summary"><h3>库存原值与批准后变化</h3><p class="small muted">以下为本单各日期、货盘的库存流水;正数为增加,负数为减少。按件商品或退回供应商不计黄金货盘。</p>${inventory.legacyCountNotice ? '<p class="note">' + e(inventory.legacyCountNotice) + '</p>' : ''}${table('原库存记录', inventory.before)}${table('同意后的库存记录', inventory.after)}${table('本次库存净变化', inventory.changes, true)}</section>`;
}
function orderChangePriceLockCostsHTML(before, after) {
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 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 } },
).replace('锁价购料成本</th>', '商品 ' + (index + 1) + ' · 锁价购料成本</th>');
})
.join('');
}
const a = before.priceLockCosts || {},
b = after.priceLockCosts || {},
source = value => (value === 'pool' ? '原锁料池' : value === 'manual' ? '手填原锁料价' : '未提供');
return (
'<tr class="change-section-row"><th colspan="3" scope="colgroup">锁价购料成本</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 orderChangeComparisonHTML(raw) {
const request = validateOrderChangeRequest(raw),
before = request.before,
after = request.after;
const basic =
[
['业务日期', 'date'],
['客户称呼/代号', 'customer'],
['开单人', 'salesperson'],
['收款方式与收款人', 'payment_account'],
['客户单备注', 'note'],
['内部备注(客户不可见)', 'internal_note'],
]
.map(([title, key]) =>
orderChangePair(
title,
key === 'payment_account' ? accountDisplayName(before[key]) : before[key],
key === 'payment_account' ? accountDisplayName(after[key]) : after[key],
),
)
.join('') +
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 = [
['成交金额', 'total'],
['收款净额', 'netReceived'],
['货品成本', 'goodsCost'],
['实际费用合计', 'directCost'],
['利润', 'profit'],
['双方待结净额', 'settlementDue'],
]
.map(([title, key]) =>
orderChangePair(
title,
orderChangeMoney(request.summary.before[key]),
orderChangeMoney(request.summary.after[key]),
),
)
.join('');
const lines = Array.from(
{ length: Math.max(before.lines.length, after.lines.length) },
(_, index) =>
`<tr class="change-section-row"><th colspan="3" scope="colgroup">商品 ${index + 1}</th></tr>${[
['商品与销售计价说明', '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),
),
)
.join('')}`,
).join('');
const related = (request.relatedOrders || [])
.map(
item =>
`<section class="order-change-related"><h3>同时受影响的关联订单:${e(item.number || item.id)}</h3><p class="small muted">本次修改会重新分配同批购料的成本及付款人。以下关联订单的利润与待结金额也会随批准一起更新。</p>${orderChangeComparisonHTML({ ...request, order_id: item.id, before: item.before, after: item.after, summary: item.summary, relatedOrders: [], relatedPriceLocks: [] })}</section>`,
)
.join('');
return `<div class="order-change-comparison"><p class="small muted">原值为申请时快照,申请值由服务器按本次变更试算。批准前请核对客户实付、商品、成本、费用及付款人。</p><div class="table-wrap"><table class="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 class="change-section-row"><th colspan="3" scope="colgroup">逐笔收退款与实际费用</th></tr>${orderChangePair('有效客户收退款/账户', orderChangePaymentsValue(before), orderChangePaymentsValue(after))}${orderChangePair('已记实际费用/日期/付款人', orderChangeExpensesValue(before), orderChangeExpensesValue(after))}</tbody></table></div>${orderChangeInventoryHTML(request.summary.inventory)}${related}${relatedPriceLocksHTML(request.relatedPriceLocks)}<p class="small muted">双方已发生的实际交款保留;试算不会发起真实收款、退款或转账。批准时仍会校验订单和关联资料版本。</p></div>`;
}
function requireOrderChangeDetail() {
if (busy) throw new Error('正在保存,请稍候。');
if (pending()) throw new Error('请先点击顶部“恢复原操作”,确认上次提交结果后再处理修改申请。');
const order = currentOrder,
entry = currentOrderChange(order);
if (!order || !entry?.data || entry.error) throw new Error('请重新读取订单并核对修改申请。');
if (typeof orderOwnershipPending === 'function' ? orderOwnershipPending(order) : order.ownershipPending)
throw new Error('归属申请待店主复核,请处理完成后再修改订单。');
return { order, entry, data: entry.data };
}
function prepareOrderActionChange(kind) {
const { order, data } = requireOrderChangeDetail(),
eligibility = data.actions?.[kind] || { eligible: data.eligible, reason: data.reason };
if (!orderActionUsesChangeForm(kind)) throw new Error('请重新打开订单后核对本次操作。');
if (!eligibility.eligible || data.pending || order.cancellationPending)
throw new Error(eligibility.reason || '本单暂不能提交变更申请,请重新读取。');
orderActionChangeEntry = { kind, id: order.id, user: orderChangeUser(), revision: order.revision };
return orderActionChangeEntry;
}
function orderActionChangeReviewHTML(kind) {
const approval = orderActionRequiresApproval(kind);
return `<div class="note" id="order-action-mode" aria-live="polite">${orderActionModeText(kind, approval)}</div>${kind === 'return' ? '' : `<label><span id="order-action-reason-label">${approval ? '申请原因' : '登记原因'}</span><textarea name="change_reason" maxlength="200" rows="2" required placeholder="写清本次需要登记或更正的原因。"></textarea></label>`}${['cost', 'expense'].includes(kind) ? '<label class="check"><input type="checkbox" name="verified" required>已核实本次金额、实际付款人与凭据一致。</label>' : ''}<div id="order-action-change-error" aria-live="polite"></div>`;
}
function orderActionModeText(kind, approval) {
return approval
? `本次提交${e(orderChangeActionLabels[kind])}申请。店主同意后才记账;待批期间原订单、收退款、费用、库存和利润均不变。系统不会发起真实付款。`
: '原单与本次业务日期均为今天,核实后直接记账,无需店主审批。改为其他业务日期须提交申请。系统不会发起真实付款。';
}
function syncOrderActionChangeMode() {
const form = $('#action-form[data-order-change="true"]'),
entry = orderActionChangeEntry;
if (!form || !entry) return;
const approval = orderActionRequiresApproval(entry.kind, form.querySelector('[name="date"]')?.value || state.today),
direct = String(!approval),
changed = form.dataset.orderDirect !== undefined && form.dataset.orderDirect !== direct;
if (changed) {
const checkbox = form.querySelector('[name="verified"]');
if (checkbox) checkbox.checked = false;
}
form.dataset.orderDirect = direct;
const title = form.querySelector('h2'),
submit = form.querySelector('[data-order-action-submit]'),
mode = $('#order-action-mode'),
reason = $('#order-action-reason-label');
if (title) title.textContent = approval ? '申请' + orderChangeActionLabels[entry.kind] : actionName[entry.kind];
if (submit) submit.textContent = approval ? '提交变更申请' : '核实并保存';
if (mode) mode.textContent = orderActionModeText(entry.kind, approval);
if (reason) reason.textContent = approval ? '申请原因' : '登记原因';
return { approval, changed };
}
function applyOrderActionChangeRestrictions() {
const form = $('#action-form[data-order-change="true"]');
if (!form) return;
const blocked = busy || !!pending() || !orderActionChangeEntry;
form.querySelectorAll('input,select,textarea,button').forEach(control => {
const action = control.dataset.action;
control.disabled =
action === 'hide-action' ? false : ['reload-order-change', 'retry'].includes(action) ? busy : blocked;
});
}
function orderActionChangeError(err, operation = null) {
err.message = err.message.replace('不要重新开单', '不要重复提交变更申请');
const id = orderActionChangeEntry?.id || currentOrder?.id || operation?.orderId;
if (
err.status === 403 &&
orderActionChangeEntry?.submittedDirect &&
orderActionChangeEntry.id === currentOrder?.id &&
!pending()
) {
orderActionChangeEntry.forceApproval = true;
orderActionChangeEntry.submittedDirect = false;
const checkbox = $('#action-form[data-order-change="true"] [name="verified"]');
if (checkbox) checkbox.checked = false;
syncOrderActionChangeMode();
const message = err.message + ' 输入已保留,请重新核实后提交店主审批。',
target = $('#order-action-change-error') || $('#detail-error');
if (target) target.innerHTML = `<div class="error">${e(message)}</div>`;
applyOrderActionChangeRestrictions();
toast(message, true);
return;
}
if ([403, 404, 409].includes(err.status)) {
orderActionChangeEntry = null;
const checkbox = $('#action-form[data-order-change="true"] [name="verified"]');
if (checkbox) checkbox.checked = false;
if (orderChangeDetail)
orderChangeDetail = { ...orderChangeDetail, data: null, error: '订单或变更申请已有新记录,请重新读取。' };
}
const target = $('#order-action-change-error') || $('#detail-error');
if (target)
target.innerHTML = `<div class="error">${e(err.message)}${pending() ? ' ' + button('恢复原操作', 'retry', 'danger') : id ? ' ' + button('重新读取订单后申请', 'reload-order-change', '', `data-id="${e(id)}"`) : ''}</div>`;
applyOrderActionChangeRestrictions();
toast(err.message, true);
}
async function submitOrderActionChange(form, input) {
const { order, data } = requireOrderChangeDetail(),
entry = orderActionChangeEntry;
if (
form !== $('#action-form[data-order-change="true"]') ||
!entry ||
entry.id !== order.id ||
entry.user !== orderChangeUser() ||
entry.revision !== order.revision ||
entry.kind !== form.dataset.kind ||
!orderActionUsesChangeForm(entry.kind)
)
throw new Error('请重新读取订单后核对本次申请。');
const eligibility = data.actions?.[entry.kind] || { eligible: data.eligible, reason: data.reason };
if (!eligibility.eligible || data.pending) throw new Error(eligibility.reason || '这张订单当前不能重复申请变更。');
const mode = syncOrderActionChangeMode(),
approval = orderActionRequiresApproval(entry.kind, input.date || state.today);
if (mode?.changed) input = { ...input, verified: false };
const reason = String(form.querySelector('[name="change_reason"]')?.value || input.reason || '').trim();
if (!reason || reason.length > 200) throw new Error((approval ? '申请原因' : '登记原因') + '请填写1~200字。');
if (input.verified !== true || !form.querySelector('[name="verified"]')?.checked)
throw new Error('请核实本次金额、付款人或账户、退货去向,并勾选确认。');
const url = '/api/orders/' + encodeURIComponent(entry.id) + '/' + (approval ? 'change' : entry.kind),
payload = {
...input,
...(approval ? { action: entry.kind } : {}),
revision: entry.revision,
reason,
verified: true,
};
$('#order-action-change-error').innerHTML = '';
const detailContext = captureOrderDetailReload(order.id);
entry.submittedDirect = !approval;
try {
const result = await mutate(url, payload);
if (approval) return await finishOrderChangeSave(url, payload, result, detailContext);
invalidateMaterialPools();
await refreshOrderDetailAfterSave(order.id, detailContext);
toast(actionName[entry.kind] + '已保存');
} catch (err) {
orderActionChangeError(err);
}
}
function showOrderChangeForm(kind) {
const { order, data } = requireOrderChangeDetail(),
request = data.pending;
if (!['approve', 'reject'].includes(kind)) throw new Error('修改复核操作无效,请重新读取订单。');
if (state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending')
throw new Error('修改申请由店主账号复核。');
if (kind === 'approve' && (!request.canApprove || request.stale || request.order_revision !== order.revision))
throw new Error('订单已有变动,请重新读取后复核;过期申请需驳回后重新申请。');
orderChangeFormEntry = {
kind,
id: order.id,
user: orderChangeUser(),
revision: order.revision,
requestId: request.id,
requestRevision: request.order_revision,
};
const reason = `<p><strong>本次申请:${e(orderChangeActionLabel(request))}</strong></p><p>申请人:${e(request.requester_name)} · ${e(orderChangeTime(request.created))}</p><p class="change-reason">申请原因:${e(request.reason)}</p>`;
const html =
kind === 'approve'
? `${reason}${orderChangeActionSummaryHTML(request)}${orderChangeComparisonHTML(request)}<label>复核备注(选填)<textarea name="note" maxlength="200" rows="2"></textarea></label><label class="check"><input type="checkbox" name="verified" required>已核对本次申请动作、金额、日期、账户或付款人、退货去向及库存,确认原值与申请值,以及以上关联订单的本次修改。</label>`
: `${reason}<p>驳回后原单继续计账,申请人可按最新原单重新申请。</p><label>驳回意见<textarea name="note" required maxlength="200" rows="3" placeholder="写清需要重新核对或补充的地方。"></textarea></label>`;
$('#detail-error').innerHTML = '';
$('#detail-form').innerHTML =
`<form class="panel order-change-form" id="order-change-form" data-kind="${kind}"><h2>${kind === 'approve' ? '复核并同意变更' : '驳回变更申请'}</h2>${html}<div id="order-change-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="primary">${kind === 'approve' ? '同意变更并更新原单' : '确认驳回'}</button>${button('收起', 'close-order-change-form', 'quiet')}</div></form>`;
$('#detail-form').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
$('#order-change-form textarea')?.focus();
}
function closeOrderChangeForm() {
orderChangeFormEntry = null;
if ($('#order-change-form')) $('#detail-form').innerHTML = '';
}
function orderChangeOperation(url) {
const application = url.match(/^\/api\/orders\/([^/]+)\/change$/),
decision = url.match(/^\/api\/order-changes\/([^/]+)\/(approve|reject)$/);
return application
? { kind: 'request', orderId: decodeURIComponent(application[1]) }
: decision
? { kind: decision[2], requestId: decodeURIComponent(decision[1]) }
: null;
}
function applyOrderChangeRestrictions() {
applyOrderActionChangeRestrictions();
if (typeof applyOrderAfterSaleRestrictions === 'function') applyOrderAfterSaleRestrictions();
const form = $('#order-change-form');
if (!form) return;
const blocked = busy || !!pending() || !orderChangeFormEntry;
form.querySelectorAll('input,textarea,button').forEach(control => {
const action = control.dataset.action;
control.disabled =
action === 'close-order-change-form' ? false : ['reload-order-change', 'retry'].includes(action) ? busy : blocked;
});
}
function orderChangeError(err, operation = null) {
err.message = err.message.replace('不要重新开单', '不要重复提交修改申请或复核');
operation = operation || orderChangeOperation(pending()?.url || '');
const id = orderChangeFormEntry?.id || currentOrder?.id || operation?.orderId;
if (operation?.kind === 'request' && $('#order-after-sale-form') && typeof orderAfterSaleError === 'function')
return orderAfterSaleError(err);
if (operation?.kind === 'request' && $('#action-form[data-order-change="true"]'))
return orderActionChangeError(err, operation);
if (
operation?.kind === 'request' &&
typeof orderEditError === 'function' &&
typeof orderEditEntry !== 'undefined' &&
orderEditEntry?.id === operation.orderId
)
return orderEditError(err, operation.orderId);
if ([409, 403, 404].includes(err.status)) {
orderChangeFormEntry = null;
if (orderChangeDetail)
orderChangeDetail = { ...orderChangeDetail, data: null, error: '修改申请或订单已有新记录,请重新读取后复核。' };
const checkbox = $('#order-change-form [name="verified"]');
if (checkbox) checkbox.checked = false;
if ($('#order-change-panel'))
$('#order-change-panel').innerHTML =
'<h2>请重新读取后复核</h2><p>修改申请或订单已有变动,当前页面不能继续复核。</p>';
}
const target = $('#order-change-error') || $('#detail-error');
if (target)
target.innerHTML = `<div class="error">${e(err.message)}${pending() ? ' ' + button('恢复原操作', 'retry', 'danger') : id ? ' ' + button('重新读取订单并复核', 'reload-order-change', '', `data-id="${e(id)}"`) : ''}</div>`;
applyOrderChangeRestrictions();
toast(err.message, true);
}
async function submitOrderChange(form) {
const { order, data } = requireOrderChangeDetail(),
entry = orderChangeFormEntry;
if (
form !== $('#order-change-form') ||
!entry ||
entry.id !== order.id ||
entry.user !== orderChangeUser() ||
entry.revision !== order.revision
)
throw new Error('请重新读取订单后核对修改申请。');
const request = data.pending;
if (
state.user.role !== 'owner' ||
!data.canApprove ||
request?.status !== 'pending' ||
request.id !== entry.requestId
)
throw new Error('修改申请由店主账号复核,请重新读取。');
const note = String(form.querySelector('[name="note"]')?.value || '').trim();
if (note.length > 200 || (entry.kind === 'reject' && !note))
throw new Error(entry.kind === 'reject' ? '驳回意见请填写1~200字。' : '复核备注最多200字。');
let input = { note };
if (entry.kind === 'approve') {
if (!request.canApprove || request.stale || entry.requestRevision !== order.revision)
throw new Error('订单已有变动,请重新读取后复核,不能同意旧申请。');
if (!form.querySelector('[name="verified"]')?.checked) throw new Error('请先核对原值与申请值,并勾选修改确认。');
input = { revision: entry.requestRevision, verified: true, note };
}
const url = '/api/order-changes/' + encodeURIComponent(entry.requestId) + '/' + entry.kind;
$('#order-change-error').innerHTML = '';
const detailContext = captureOrderDetailReload(order.id);
try {
const result = await mutate(url, input);
return await finishOrderChangeSave(url, input, result, detailContext);
} catch (err) {
orderChangeError(err);
}
}
async function finishOrderChangeSave(
url,
input,
result,
detailContext = captureOrderDetailReload(result.id || result.order?.id),
) {
const operation = orderChangeOperation(url),
id = result.id || result.order?.id || operation?.orderId;
if (!id) throw new Error('操作已保存,请重新读取订单列表查看结果。');
const actionLabel = orderChangeActionLabel(result.request || { action: input.action || 'edit' }),
title =
operation?.kind === 'approve'
? '已同意' + actionLabel + ',原订单已更新'
: operation?.kind === 'reject'
? actionLabel + '申请已驳回'
: actionLabel + '申请已提交,等待店主复核';
const fromEdit = operation?.kind === 'request' && tab === 'order-edit';
if (operation?.kind === 'request' && typeof orderEditDraftKey === 'function') {
localStorage.removeItem(orderEditDraftKey(id));
if (localStorage.getItem(orderEditActiveKey()) === id) localStorage.removeItem(orderEditActiveKey());
++orderEditRequest;
orderEditEntry = null;
}
if (typeof invalidateOrderAfterSaleForm === 'function') invalidateOrderAfterSaleForm();
orderChangeFormEntry = null;
orderActionChangeEntry = null;
orderChangeDetail = null;
currentOrder = null;
invalidateMaterialPools();
invalidateReport();
invalidatePriceLockViews();
if (typeof invalidateOrderCancellationViews === 'function') invalidateOrderCancellationViews();
inventoryPage = null;
++orderBookRequest;
if (detailContext) detailContext = { ...detailContext, bookRequest: orderBookRequest };
const savedHTML = `<div class="order-header"><h2>${title}</h2><p>操作已经保存。${operation?.kind === 'approve' ? '原订单、原单号和复核记录保留。' : '原订单继续计账。'}</p><div id="order-change-saved-status" aria-live="polite"></div><div class="actions">${button('重新读取原订单', 'reload-order-change', 'primary', `data-id="${e(id)}"`)}</div></div>`;
if (fromEdit) {
tab = 'orders';
$('#order-dialog')?.close();
$('#main').innerHTML =
heading('ORDER CHANGE', title, '原订单与申请记录可以重新读取。') +
`<section class="panel">${savedHTML}</section>`;
document
.querySelectorAll('nav button')
.forEach(button => button.classList.toggle('active', button.dataset.tab === tab));
} else if ($('#order-content')) $('#order-content').innerHTML = savedHTML;
try {
await refreshOrderDetailAfterSave(id, fromEdit ? null : detailContext);
toast(title);
} catch {
if ($('#order-change-saved-status'))
$('#order-change-saved-status').textContent = '保存已成功,最新资料暂未读到。请重新读取原订单查看。';
toast('操作已经保存,请重新读取原订单查看,不要重复提交。', true);
}
}
function validateOrderChangeList(result) {
if (
!result ||
!Array.isArray(result.requests) ||
typeof result.canApprove !== 'boolean' ||
!['pending', 'approved', 'rejected'].every(
key => Number.isSafeInteger(result.counts?.[key]) && result.counts[key] >= 0,
)
)
throw new Error('修改复核列表未完整返回,请重新读取。');
result.requests.forEach(request => validateOrderChangeRequest(request));
return result;
}
async function loadOrderChangeCount() {
const request = ++orderChangeCountRequest,
user = orderChangeUser();
try {
const result = validateOrderChangeList(await api('/api/order-changes?status=pending')),
entry = $('#order-changes-entry');
if (request !== orderChangeCountRequest || user !== orderChangeUser() || tab !== 'orders' || !entry) return;
entry.textContent = '待变更复核(' + result.counts.pending + ')';
entry.classList.toggle('danger', result.counts.pending > 0);
entry.title = '所有日期的修改申请,不受订单筛选影响';
} catch {
const entry = $('#order-changes-entry');
if (request === orderChangeCountRequest && user === orderChangeUser() && tab === 'orders' && entry) {
entry.textContent = '待变更复核(读取失败)';
entry.title = '点击重新读取全部日期的变更申请';
}
}
}
function orderChangeListHTML(result) {
const owner = state.user.role === 'owner' && result.canApprove;
return `<div class="change-list-tabs" role="group" aria-label="变更申请状态">${[
['pending', '待复核'],
['approved', '已同意'],
['rejected', '已驳回'],
['all', '全部'],
]
.map(([value, name]) =>
button(
name + (value === 'all' ? '' : '(' + result.counts[value] + ')'),
'filter-order-changes',
orderChangeListStatus === value ? 'primary' : '',
`data-status="${value}" aria-pressed="${orderChangeListStatus === value}"`,
),
)
.join(
'',
)}</div>${result.requests.length ? `<div class="table-wrap"><table class="change-list-table" aria-label="全部日期的变更申请"><thead><tr><th>原订单/日期</th><th>申请人/申请时间</th><th>动作/申请原因</th><th>状态/复核意见</th><th>查看</th></tr></thead><tbody>${result.requests.map(request => `<tr><td><strong>${e(request.order_number)}</strong><div class="small muted">${e(request.order_date)}</div><div class="small">原成交 ${orderChangeMoney(request.summary.before.total)}<br>申请成交 ${orderChangeMoney(request.summary.after.total)}</div></td><td>${e(request.requester_name)}<div class="small muted">${e(orderChangeTime(request.created))}</div></td><td class="change-reason"><strong>${e(orderChangeActionLabel(request))}</strong><br>${e(request.reason)}</td><td>${e(orderChangeStatus[request.status])}${request.stale && request.status === 'pending' ? '<div class="small danger-text">原单已有变动,需驳回后重新申请</div>' : ''}${request.note ? `<div class="small change-reason">${e(request.note)}</div>` : ''}${request.reviewer_name ? `<div class="small muted">${e(request.reviewer_name)} · ${e(orderChangeTime(request.reviewed))}</div>` : ''}</td><td>${button(owner && request.status === 'pending' ? '查看并复核' : '查看订单', 'open-change-order', '', `data-id="${e(request.order_id)}"`)}</td></tr>`).join('')}</tbody></table></div>` : '<p class="empty">全部日期均无此状态的变更申请。</p>'}`;
}
async function openOrderChanges(status = 'pending') {
orderChangeListStatus = Object.hasOwn(orderChangeStatus, status) || status === 'all' ? status : 'pending';
let dialog = $('#order-changes-dialog');
if (!dialog) {
dialog = document.createElement('dialog');
dialog.id = 'order-changes-dialog';
dialog.setAttribute('aria-labelledby', 'order-changes-title');
dialog.addEventListener('cancel', () => {
++orderChangeListRequest;
});
document.body.append(dialog);
}
dialog.innerHTML = `<button class="dialog-close" data-action="close-order-changes" aria-label="关闭变更申请列表">×</button><h2 id="order-changes-title">变更申请与复核</h2><p class="small muted">全部日期,不受订单页的日期、搜索或状态筛选影响。待批期间仍按原订单计账,包含改单、费用、成本、退款与退货;店主同意后才更新原单。</p><div id="order-changes-list" aria-live="polite" aria-busy="true">正在读取…</div>`;
if (!dialog.open) dialog.showModal();
return await loadOrderChanges();
}
async function loadOrderChanges() {
const dialog = $('#order-changes-dialog'),
target = $('#order-changes-list');
if (!dialog?.open || !target) return;
const request = ++orderChangeListRequest,
user = orderChangeUser(),
status = orderChangeListStatus;
target.setAttribute('aria-busy', 'true');
target.innerHTML = '正在读取全部日期的变更申请…';
try {
const result = validateOrderChangeList(await api('/api/order-changes?' + new URLSearchParams({ status })));
if (
request !== orderChangeListRequest ||
user !== orderChangeUser() ||
!dialog.open ||
status !== orderChangeListStatus
)
return;
target.innerHTML = orderChangeListHTML(result);
target.setAttribute('aria-busy', 'false');
const entry = $('#order-changes-entry');
if (entry) entry.textContent = '待变更复核(' + result.counts.pending + ')';
} catch (err) {
if (request !== orderChangeListRequest || user !== orderChangeUser() || !dialog.open) return;
target.setAttribute('aria-busy', 'false');
target.innerHTML = `<div class="error">${e(err.name === 'AbortError' ? '读取超时,请重新读取。' : err.message)} ${button('重新读取', 'retry-order-changes')}</div>`;
}
}
function closeOrderChanges() {
++orderChangeListRequest;
$('#order-changes-dialog')?.close();
}
function invalidateOrderChangeViews() {
++orderChangeCountRequest;
closeOrderChanges();
orderChangeDetail = null;
orderChangeFormEntry = null;
orderActionChangeEntry = null;
}