'use strict'; // 取消是录错作废,申请与复核均沿用原操作号,不产生真实退款。 let orderCancellationDetail = null, orderCancellationFormEntry = null; let orderCancellationCountRequest = 0, orderCancellationListRequest = 0, orderCancellationListStatus = 'pending'; const orderCancellationStatus = { pending: '待店主复核', approved: '已同意取消', rejected: '已驳回' }; function orderCancellationUser() { return session?.user?.id || ''; } function orderCancellationTime(value) { const date = new Date(value); return Number.isNaN(date.getTime()) ? '时间未提供' : date.toLocaleString('zh-CN'); } function validateOrderCancellationRequest(request, orderId) { const summary = request?.summary, 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(orderCancellationStatus, 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' || !summary || !['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) || !['goodsCost', 'profit', 'settlementDue'].every(key => nullable(summary[key])) || !Array.isArray(summary.inventory) || !summary.inventory.every( item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg), ) ) throw new Error('取消申请资料未完整返回,请重新读取订单后复核。'); return request; } function useOrderCancellationDetail(order, result, error) { orderCancellationFormEntry = null; const entry = { id: order.id, user: orderCancellationUser(), 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 => validateOrderCancellationRequest(request, order.id)); if (result.pending) validateOrderCancellationRequest(result.pending, order.id); entry.data = result; } catch (err) { entry.error = err.name === 'AbortError' ? '取消申请读取超时,请重新读取。' : err.message; } orderCancellationDetail = entry; return entry; } function currentOrderCancellation(order = currentOrder) { return order && orderCancellationDetail?.id === order.id && orderCancellationDetail.user === orderCancellationUser() && orderCancellationDetail.revision === order.revision ? orderCancellationDetail : null; } function orderCancellationPending(order) { return currentOrderCancellation(order)?.data?.pending || order.cancellationPending || null; } function orderCancellationApproved(order) { return ( order.cancellationApproved || currentOrderCancellation(order)?.data?.requests.find(request => request.status === 'approved') || null ); } function orderCancellationCanDirect(order = currentOrder) { const data = currentOrderCancellation(order)?.data; if ( !data?.eligible || data.pending || data.directToday !== true || !/^\d{4}-\d{2}-\d{2}$/.test(data.directActionDate || '') || order.date !== data.directActionDate || order.price_lock_id || !['draft', 'confirmed', 'delivered'].includes(order.status) ) return false; try { validateOrderCancellationSummary(data.summary); return true; } catch { return false; } } function orderCancellationRecordStatus(request) { return request.direct === true ? '当天直接取消' : orderCancellationStatus[request.status]; } function orderCancellationActionHTML(order) { const entry = currentOrderCancellation(order), data = entry?.data; if (typeof orderOwnershipPending === 'function' ? orderOwnershipPending(order) : order.ownershipPending) return ''; if ( order.price_lock_id || !['draft', 'confirmed', 'delivered'].includes(order.status) || orderCancellationPending(order) || (typeof orderChangePending === 'function' ? orderChangePending(order) : order.changePending) || !data?.eligible ) return ''; return button( orderCancellationCanDirect(order) ? '取消订单' : '申请取消', 'request-order-cancellation', 'danger', `data-id="${e(order.id)}"`, ); } function orderCancellationHistoryHTML(request) { if (request.direct === true) return `
  • 当天直接取消
    经办人:${e(request.operator_name || request.requester_name)} · ${e(orderCancellationTime(request.executedAt || request.created))}

    ${e(request.reason)}

    ${request.note ? `

    处理备注:${e(request.note)}

    ` : ''}
  • `; return `
  • ${e(orderCancellationStatus[request.status])}${request.stale && request.status === 'pending' ? '订单已有变动' : ''}
    申请人:${e(request.requester_name)} · ${e(orderCancellationTime(request.created))}

    ${e(request.reason)}

    ${request.status !== 'pending' ? `
    复核人:${e(request.reviewer_name || '未提供')} · ${e(orderCancellationTime(request.reviewed))}${request.note ? `

    ${request.status === 'rejected' ? '驳回意见' : '复核备注'}:${e(request.note)}

    ` : ''}
    ` : ''}
  • `; } function orderCancellationDetailHTML(order) { if (order.price_lock_id) return ''; const entry = currentOrderCancellation(order), data = entry?.data, request = orderCancellationPending(order), approved = orderCancellationApproved(order); if (!data) return `

    取消申请与复核

    ${e(entry?.error || '取消申请资料尚未读取,请先重新读取订单。')}

    ${button('重新读取订单', 'reload-order-cancellation', '', `data-id="${e(order.id)}"`)}
    `; if (!request && !data.requests.length) return ''; const canReview = state.user.role === 'owner' && data.canApprove && request?.status === 'pending'; return `

    ${approved ? '已取消 · 录错作废' : '取消申请与复核'}

    ${request ? '待店主复核' : ''}
    ${request ? `

    申请期间仍按原订单计账,尚未取消。复核完成前暂停本单财务修改和退货。

    ${request.stale ? '
    订单在申请后已有变动,原申请不能同意。请店主驳回后重新申请,再按最新资料核对。
    ' : ''}${canReview ? `
    ${!request.stale ? button('同意取消', 'approve-order-cancellation', 'danger', `data-id="${e(request.id)}"`) : ''}${button('驳回', 'reject-order-cancellation', '', `data-id="${e(request.id)}"`)}
    ` : '

    由店主账号查看撤销摘要并复核。

    '}` : ''}${approved ? '

    本单为录错作废:销售、成本、收款及费用已撤销,原有库存出入已冲回。原单、原流水与处理记录保留;本次没有登记真实退货或发起退款。

    双方已登记的实际交款保留,请继续核对下方待结金额。

    ' : ''}
    取消申请与处理记录(${data.requests.length})
    `; } function validateOrderCancellationSummary(summary) { if ( !summary || !['total', 'netReceived', 'directCost'].every(key => Number.isSafeInteger(summary[key])) || !['goodsCost', 'profit', 'settlementDue'].every( key => summary[key] === null || Number.isSafeInteger(summary[key]), ) || !Array.isArray(summary.inventory) || !summary.inventory.every( item => typeof item.date === 'string' && typeof item.pocket === 'string' && Number.isSafeInteger(item.mg), ) ) throw new Error('取消撤销摘要未完整返回,请重新读取订单。'); return summary; } function orderCancellationSummaryHTML(request) { return orderCancellationSummaryDataHTML(validateOrderCancellationRequest(request).summary); } function orderCancellationSummaryDataHTML(value) { const summary = validateOrderCancellationSummary(value), amount = value => (value === null ? '待补齐' : '¥' + yuan(value)); return `
    本次按“录错作废”撤销本单记账,不是实际退货退款。原单和冲回明细保留,不会向客户付款。
    撤销原成交金额
    ${amount(summary.total)}
    撤销收款净额
    ${amount(summary.netReceived)}
    撤销货品成本
    ${amount(summary.goodsCost)}
    撤销已记费用
    ${amount(summary.directCost)}
    撤销原记账利润
    ${amount(summary.profit)}
    当前双方待结净额
    ${amount(summary.settlementDue)}

    库存冲回摘要

    ${summary.legacyCountNotice ? '

    ' + e(summary.legacyCountNotice) + '

    ' : ''}${summary.inventory.length ? `
    ${summary.inventory.map(item => ``).join('')}
    原日期货盘恢复/冲回克重
    ${e(item.date)}${e(pocketLabel(item.pocket))}${item.mg > 0 ? '+' : ''}${grams(item.mg)}g${inventoryCountHTML(item, { signed: true })}
    ` : '

    本单没有需要冲回的库存出入。

    '}

    按原日期、原货盘冲回库存。收款与费用撤回后仍能查看原记录和冲回行;双方实际交款保留,不会自动抹掉或转账。日购料真实采购付款保留,本单耗用将释放并重算相关成本与待结金额。

    `; } function requireOrderCancellationDetail() { if (busy) throw new Error('正在保存,请稍候。'); if (pending()) throw new Error('请先点击顶部“恢复原操作”,确认上次提交结果后再处理取消申请。'); const order = currentOrder, entry = currentOrderCancellation(order); if (!order || !entry?.data || entry.error) throw new Error('请重新读取订单并核对取消申请。'); if (order.price_lock_id) throw new Error('锁价单暂不支持取消。'); if (typeof orderOwnershipPending === 'function' ? orderOwnershipPending(order) : order.ownershipPending) throw new Error('归属申请待店主复核,请处理完成后再申请取消。'); if (typeof orderChangePending === 'function' ? orderChangePending(order) : order.changePending) throw new Error('修改申请待店主复核,请复核完成后再申请取消。'); return { order, entry, data: entry.data }; } function showOrderCancellationForm(kind) { const { order, data } = requireOrderCancellationDetail(), request = data.pending; if (kind === 'request' && orderCancellationCanDirect(order)) kind = 'direct'; if ( ['request', 'direct'].includes(kind) && (!data.eligible || request || !['draft', 'confirmed', 'delivered'].includes(order.status)) ) throw new Error(data.reason || '这张订单当前不能申请取消。'); if (kind === 'direct' && !orderCancellationCanDirect(order)) throw new Error('当前不能直接取消,请重新读取订单。'); if ( !['request', 'direct'].includes(kind) && (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('订单已有变动,请重新读取后复核;过期申请需驳回后重新申请。'); orderCancellationFormEntry = { kind, id: order.id, user: orderCancellationUser(), revision: order.revision, requireVerified: kind === 'direct', requestId: request?.id || '', requestRevision: request?.order_revision, }; let html = '', title = '', submit = ''; if (kind === 'direct') { title = '取消今天的订单'; submit = '核实并取消订单'; html = `
    这张订单是今天开的,核实后直接按录错作废,无需另行审批。业务日期:${e(data.directActionDate)}。本入口不办理真实退货或退款。
    ${orderCancellationSummaryDataHTML(data.summary)}`; } else if (kind === 'request') { title = '申请取消这张订单'; submit = '提交取消申请'; html = '

    仅用于开错、重复录入等需要整单作废的登记错误。提交后仍按原单计账,店主同意后才取消、恢复库存并撤销本单销售、成本、收款和费用记账。

    真实退货请从“整单退货”办理;这里不会发起真实退款。

    '; } else if (kind === 'approve') { title = '复核并同意取消'; submit = '同意取消并作废'; html = `

    申请人:${e(request.requester_name)} · ${e(orderCancellationTime(request.created))}

    取消原因:${e(request.reason)}

    ${orderCancellationSummaryHTML(request)}`; } else if (kind === 'reject') { title = '驳回取消申请'; submit = '确认驳回'; html = `

    取消原因:${e(request.reason)}

    驳回后原订单继续计账,申请人可核对后重新申请。

    `; } else throw new Error('取消操作无效,请重新读取订单。'); if (kind !== 'reject') html += legacyCountConfirmationHTML( kind === 'approve' ? request.summary : data.requiresLegacyCountVerified ? data : data.summary, ); $('#detail-error').innerHTML = ''; $('#detail-form').innerHTML = `

    ${title}

    ${html}
    ${button('收起', 'close-order-cancellation-form', 'quiet')}
    `; $('#detail-form').scrollIntoView({ block: 'nearest', behavior: 'smooth' }); $('#order-cancellation-form textarea')?.focus(); } function closeOrderCancellationForm() { orderCancellationFormEntry = null; if ($('#order-cancellation-form')) $('#detail-form').innerHTML = ''; } function orderCancellationOperation(url) { const application = url.match(/^\/api\/orders\/([^/]+)\/(cancellation|canceltoday)$/), decision = url.match(/^\/api\/order-cancellations\/([^/]+)\/(approve|reject)$/); return application ? { kind: application[2] === 'canceltoday' ? 'direct' : 'request', orderId: decodeURIComponent(application[1]) } : decision ? { kind: decision[2], requestId: decodeURIComponent(decision[1]) } : null; } function applyOrderCancellationRestrictions() { const form = $('#order-cancellation-form'); if (!form) return; const blocked = busy || !!pending() || !orderCancellationFormEntry; form.querySelectorAll('input,textarea,button').forEach(control => { const action = control.dataset.action; control.disabled = action === 'close-order-cancellation-form' ? false : ['reload-order-cancellation', 'retry'].includes(action) ? busy : blocked; }); } function orderCancellationError(err) { err.message = err.message.replace('不要重新开单', '不要重复提交取消申请或复核'); const entry = orderCancellationFormEntry, id = entry?.id || currentOrder?.id; if (err.status === 403 && entry?.kind === 'direct' && entry.id === currentOrder?.id && !pending()) { entry.kind = 'request'; if (orderCancellationDetail?.data) orderCancellationDetail.data = { ...orderCancellationDetail.data, directToday: false }; const form = $('#order-cancellation-form'), checkbox = form?.querySelector('[name="verified"]'); if (checkbox) checkbox.checked = false; if (form) { form.dataset.kind = 'request'; const title = form.querySelector('h2'), submit = form.querySelector('[data-order-cancellation-submit]'); if (title) title.textContent = '申请取消这张订单'; if (submit) submit.textContent = '提交取消申请'; } const mode = $('#order-cancellation-mode'); if (mode) mode.textContent = '当前不能直接取消。输入已保留,重新核实后提交取消申请,店主同意后才按录错作废。'; const message = err.message + ' 输入已保留,请重新核实后提交店主审批。', target = $('#order-cancellation-error') || $('#detail-error'); if (target) target.innerHTML = `
    ${e(message)}
    `; applyOrderCancellationRestrictions(); toast(message, true); return; } if (err.status === 409 || err.status === 403 || err.status === 404) { orderCancellationFormEntry = null; if (orderCancellationDetail) orderCancellationDetail = { ...orderCancellationDetail, data: null, error: '取消申请或订单已有新记录,请重新读取后复核。', }; const checkbox = $('#order-cancellation-form [name="verified"]'); if (checkbox) checkbox.checked = false; if ($('#order-cancellation-panel')) $('#order-cancellation-panel').innerHTML = '

    请重新读取后复核

    取消申请或订单已有变动,当前页面不能继续复核。

    '; } const target = $('#order-cancellation-error') || $('#detail-error'); if (target) target.innerHTML = `
    ${e(err.message)}${pending() ? ' ' + button('恢复原操作', 'retry', 'danger') : id ? ' ' + button('重新读取订单并复核', 'reload-order-cancellation', '', `data-id="${e(id)}"`) : ''}
    `; applyOrderCancellationRestrictions(); toast(err.message, true); } async function submitOrderCancellation(form) { const { order, data } = requireOrderCancellationDetail(), entry = orderCancellationFormEntry; if ( form !== $('#order-cancellation-form') || !entry || entry.id !== order.id || entry.user !== orderCancellationUser() || entry.revision !== order.revision ) throw new Error('请重新读取订单后核对取消申请。'); const get = name => form.querySelector(`[name="${name}"]`), text = name => String(get(name)?.value || '').trim(); let input, url; if (['request', 'direct'].includes(entry.kind)) { if (!data.eligible || data.pending) throw new Error('这张订单当前不能重复申请取消。'); const reason = text('reason'); if (!reason || reason.length > 200) throw new Error('取消原因请填写1~200字。'); const direct = entry.kind === 'direct'; if (direct && !orderCancellationCanDirect(order)) throw new Error('当前不能直接取消,请重新读取订单。'); if (entry.requireVerified && !get('verified')?.checked) throw new Error('请先核对撤销金额、成本和库存,并勾选录错作废确认。'); input = { revision: entry.revision, reason, ...(direct ? { date: data.directActionDate, verified: true } : {}) }; url = '/api/orders/' + encodeURIComponent(order.id) + '/' + (direct ? 'canceltoday' : 'cancellation'); } else { const request = data.pending; if ( state.user.role !== 'owner' || !data.canApprove || request?.status !== 'pending' || request.id !== entry.requestId ) throw new Error('取消申请由店主账号复核,请重新读取。'); const note = text('note'); if (note.length > 200 || (entry.kind === 'reject' && !note)) throw new Error(entry.kind === 'reject' ? '驳回意见请填写1~200字。' : '复核备注最多200字。'); if (entry.kind === 'approve') { if (!request.canApprove || request.stale || entry.requestRevision !== order.revision) throw new Error('订单已有变动,请重新读取后复核,不能同意旧申请。'); if (!get('verified')?.checked) throw new Error('请先核对撤销金额、成本和库存,并勾选录错作废确认。'); input = { revision: entry.requestRevision, verified: true, note }; } else input = { note }; url = '/api/order-cancellations/' + encodeURIComponent(entry.requestId) + '/' + entry.kind; } if (entry.kind !== 'reject') Object.assign( input, requireLegacyCountConfirmation( form, entry.kind === 'approve' ? data.pending.summary : data.requiresLegacyCountVerified ? data : data.summary, ), ); $('#order-cancellation-error').innerHTML = ''; const detailContext = captureOrderDetailReload(order.id); try { const result = await mutate(url, input); return await finishOrderCancellationSave(url, input, result, detailContext); } catch (err) { orderCancellationError(err); } } async function finishOrderCancellationSave( url, input, result, detailContext = captureOrderDetailReload(result.id || result.order?.id), ) { const operation = orderCancellationOperation(url), id = result.id || result.order?.id || operation?.orderId, title = operation?.kind === 'direct' ? '当天直接取消,原订单已作废' : operation?.kind === 'approve' ? '已同意取消,原订单已作废' : operation?.kind === 'reject' ? '取消申请已驳回' : '取消申请已提交,等待店主复核'; orderCancellationFormEntry = null; orderCancellationDetail = null; currentOrder = null; invalidateMaterialPools(); invalidateReport(); invalidatePriceLockViews(); inventoryPage = null; ++orderBookRequest; if (detailContext) detailContext = { ...detailContext, bookRequest: orderBookRequest }; if ($('#order-content')) $('#order-content').innerHTML = `

    ${title}

    操作已经保存。${operation?.kind === 'request' ? '复核期间仍按原单计账。' : ['approve', 'direct'].includes(operation?.kind) ? '没有发起真实退款,原单和处理记录已保留。' : '原订单继续计账。'}

    ${button('重新读取原订单', 'reload-order-cancellation', 'primary', `data-id="${e(id)}"`)}
    `; try { await refreshOrderDetailAfterSave(id, detailContext); toast(title); } catch { if ($('#order-cancellation-saved-status')) $('#order-cancellation-saved-status').textContent = '保存已成功,最新资料暂未读到。请重新读取原订单查看。'; toast('操作已经保存,请重新读取原订单查看,不要重复提交。', true); } } function validateOrderCancellationList(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 => validateOrderCancellationRequest(request)); return result; } async function loadOrderCancellationCount() { const request = ++orderCancellationCountRequest, user = orderCancellationUser(); try { const result = validateOrderCancellationList(await api('/api/order-cancellations?status=pending')); const entry = $('#order-cancellations-entry'); if (request !== orderCancellationCountRequest || user !== orderCancellationUser() || tab !== 'orders' || !entry) return; entry.textContent = '待取消复核(' + result.counts.pending + ')'; entry.classList.toggle('danger', result.counts.pending > 0); entry.title = '所有日期的取消申请,不受订单筛选影响'; } catch { const entry = $('#order-cancellations-entry'); if (request === orderCancellationCountRequest && user === orderCancellationUser() && tab === 'orders' && entry) { entry.textContent = '待取消复核(读取失败)'; entry.title = '点击重新读取全部日期的取消申请'; } } } function orderCancellationListHTML(result) { const owner = state.user.role === 'owner' && result.canApprove; return `
    ${[ ['pending', '待复核'], ['approved', '已取消'], ['rejected', '已驳回'], ['all', '全部'], ] .map(([value, name]) => button( name + (value === 'all' ? '' : '(' + result.counts[value] + ')'), 'filter-order-cancellations', orderCancellationListStatus === value ? 'primary' : '', `data-status="${value}" aria-pressed="${orderCancellationListStatus === value}"`, ), ) .join( '', )}
    ${result.requests.length ? `
    ${result.requests.map(request => ``).join('')}
    原订单/日期经办/申请人及时间取消原因状态/处理记录查看
    ${e(request.order_number)}
    ${e(request.order_date)}
    原成交 ¥${yuan(request.summary.total)}
    ${request.direct === true ? '经办人:' : ''}${e(request.operator_name || request.requester_name)}
    ${e(orderCancellationTime(request.executedAt || request.created))}
    ${e(request.reason)}${e(orderCancellationRecordStatus(request))}${request.stale && request.status === 'pending' ? '
    原单已有变动,需驳回后重新申请
    ' : ''}${request.note ? `
    ${e(request.note)}
    ` : ''}${request.reviewer_name ? `
    ${e(request.reviewer_name)} · ${e(orderCancellationTime(request.reviewed))}
    ` : ''}
    ${button(owner && request.status === 'pending' ? '查看并复核' : '查看订单', 'open-cancellation-order', '', `data-id="${e(request.order_id)}"`)}
    ` : '

    全部日期均无此状态的取消申请。

    '}`; } async function openOrderCancellations(status = 'pending') { orderCancellationListStatus = Object.hasOwn(orderCancellationStatus, status) || status === 'all' ? status : 'pending'; let dialog = $('#order-cancellations-dialog'); if (!dialog) { dialog = document.createElement('dialog'); dialog.id = 'order-cancellations-dialog'; dialog.setAttribute('aria-labelledby', 'order-cancellations-title'); dialog.addEventListener('cancel', () => { ++orderCancellationListRequest; }); document.body.append(dialog); } dialog.innerHTML = `

    取消申请与复核

    全部日期,不受订单页的日期、搜索或状态筛选影响。申请期间仍按原订单计账;店主同意后才按录错作废。当天直接取消的记录单独标明经办人。

    正在读取…
    `; if (!dialog.open) dialog.showModal(); return await loadOrderCancellations(); } async function loadOrderCancellations() { const dialog = $('#order-cancellations-dialog'), target = $('#order-cancellations-list'); if (!dialog?.open || !target) return; const request = ++orderCancellationListRequest, user = orderCancellationUser(), status = orderCancellationListStatus; target.setAttribute('aria-busy', 'true'); target.innerHTML = '正在读取全部日期的取消申请…'; try { const result = validateOrderCancellationList( await api('/api/order-cancellations?' + new URLSearchParams({ status })), ); if ( request !== orderCancellationListRequest || user !== orderCancellationUser() || !dialog.open || status !== orderCancellationListStatus ) return; target.innerHTML = orderCancellationListHTML(result); target.setAttribute('aria-busy', 'false'); const entry = $('#order-cancellations-entry'); if (entry) entry.textContent = '待取消复核(' + result.counts.pending + ')'; } catch (err) { if (request !== orderCancellationListRequest || user !== orderCancellationUser() || !dialog.open) return; target.setAttribute('aria-busy', 'false'); target.innerHTML = `
    ${e(err.name === 'AbortError' ? '读取超时,请重新读取。' : err.message)} ${button('重新读取', 'retry-order-cancellations')}
    `; } } function closeOrderCancellations() { ++orderCancellationListRequest; $('#order-cancellations-dialog')?.close(); } function invalidateOrderCancellationViews() { ++orderCancellationCountRequest; closeOrderCancellations(); orderCancellationDetail = null; orderCancellationFormEntry = null; }