Files
SupplierSystem/server/src/services/orderDeleteService.ts
T
Ubuntu aa2db57b0f
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
feat(main-system): 免入库单取货链路 + 实收数量「事实登记 + 事后同步」
免入库(主系统骑手上门取货):
- 50 展示「待取货」、副文案「待主系统骑手上门取货」、不建我方配送任务(守卫与开关解耦)
- 我方 50 即回写备货完成;两开关(SKIP_INBOUND_AWAIT_PICKUP / FULFILLMENT_EVENTS)改默认开

核货事实镜像(「核货完毕」标记):
- 按主系统 lookup 的 actual_qty 落台账,新增 GET/POST /orders/:orderCode/main-system-prep-facts[/refresh]
- 详情行内显示「核货完毕」(含核货量),分配对账兜底刷新

实收数量/单位口径变更(对方先改 + 我方事后同步):
- 台账加 applied_at;inbound 与 picking_check 同为事实登记(驳回不回滚)
- 同意才落我方值:免入库改装车核货量、送仓改验收实收(已入库走既有库存调整)、已结算/已结案只留痕
- 计划量与金额一起改,并同步结算投影(syncStatementsForOrderSafe)
- 审核页语义改「主系统实际值(已生效)/ 是否同步」+ 已处理历史(双方时间与落值结论)

台账对照与回写修复:
- 行级对照改整单一次性(同名商品不再重复认领)+ 存量纠正 healOrderPrepMapping
- 堵住客户绑定回填旁路(免入库单不再被派我方骑手)
- 回写触发函数改对象参数(修 branch/order 传反导致的静默不回写)

文档:设计文档 4 篇 +《给主系统 AI 的对接改造清单》§2.9(第六批契约)

回归:服务端全量与 HEAD 基线一致(24 个失败文件同集合);前端 140 文件 / 699 测试全绿;tsc 双端干净
2026-10-09 21:52:17 +08:00

809 lines
32 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg';
import { pool } from '../db';
import type { TenantContext } from './tenantScope';
import { getEffectiveBranchCode } from './tenantScope';
import { deleteNotificationsByRelatedOrderCode } from './notificationService';
import { listBellNotifications, publishNotificationEvent } from './notificationStreamService';
import { writeAuditLog } from './auditService';
import { loadOrderItemSnapshot } from './orderDeleteSnapshot';
import { recalculateStatementsAffectedByOrder, recalculateStatementsFromRefs, removeCustomerStatementForOrder, upsertCustomerStatementForOrder } from './financeReconciliationService';
import { releaseReservationsForOrder } from './inventoryStockCoverService';
import { syncWarehouseProcessingDemandForOrder } from './processingDemandSheetService';
export interface OrderDeleteResult {
order_code: string;
deleted_purchases: number;
deleted_preparations: number;
deleted_delivery_tasks: number;
deleted_cost_details: number;
deleted_inspections: number;
deleted_notifications: number;
deleted_related: Record<string, number>;
}
export interface OrderTrashResult {
order_code: string;
trashed: true;
}
export interface OrderRestoreResult {
order_code: string;
restored: true;
}
export interface OrderTrashListRow {
order_code: string;
customer_code: string | null;
company_name: string | null;
branch_code: string | null;
order_status: number;
total_amount: number;
delivery_date: string | null;
cycle_code: string | null;
deleted_at: string;
deleted_by_name: string | null;
cancel_reason: string | null;
item_count: number;
}
function assertOrderDeletePermission(ctx: TenantContext) {
if (ctx.isSuperAdmin || ctx.isBranchAdmin || ctx.roles.includes('admin') || ctx.roles.includes('operator')) {
return;
}
if (!ctx.permissions.some((code) => code === 'order_delete' || code === 'order_manage')) {
throw Object.assign(new Error('无权删除订单'), { status: 403 });
}
}
function assertOrderAccess(ctx: TenantContext, order: { branch_code: string | null }) {
if (ctx.isSuperAdmin) return;
if (!ctx.branchCode) {
throw Object.assign(new Error('当前账号未绑定分公司,无法操作订单'), { status: 403 });
}
if (order.branch_code && order.branch_code !== ctx.branchCode) {
throw Object.assign(new Error('无权操作其他分公司的订单'), { status: 403 });
}
}
/** 未完成自采:待采购/采购中/待验收/质检不合格等(已入库 purchase_status>=30 且非 32 保留) */
export function isIncompletePurchaseStatus(status: unknown): boolean {
const value = Number(status ?? 10);
return value < 30 || value === 32;
}
/** 未完成备货:prepare_status 未达 30(已完成) */
export function isIncompletePrepareStatus(status: unknown): boolean {
return Number(status ?? 10) !== 30;
}
async function tableExists(client: PoolClient, table: string): Promise<boolean> {
// 当前 search_path(tenant)优先,兼容归档后无 public 业务表
const result = await client.query(`SELECT to_regclass($1) AS reg`, [table]);
return Boolean(result.rows[0]?.reg);
}
async function columnExists(client: PoolClient, table: string, column: string): Promise<boolean> {
const result = await client.query(
`SELECT 1
FROM information_schema.columns c
WHERE c.table_name = $1
AND c.column_name = $2
AND c.table_schema = ANY (current_schemas(false))
LIMIT 1`,
[table, column]
);
return (result.rowCount || 0) > 0;
}
async function deleteByOrderCode(
client: PoolClient,
table: string,
orderCode: string,
column = 'order_code'
): Promise<number> {
if (!(await tableExists(client, table))) return 0;
if (!(await columnExists(client, table, column))) return 0;
const result = await client.query(`DELETE FROM ${table} WHERE ${column} = $1`, [orderCode]);
return result.rowCount || 0;
}
async function deleteOrderItemDependants(
client: PoolClient,
table: string,
orderCode: string
): Promise<number> {
if (!(await tableExists(client, table))) return 0;
const hasOrderCode = await columnExists(client, table, 'order_code');
const hasOrderItemId = await columnExists(client, table, 'order_item_id');
if (!hasOrderCode && !hasOrderItemId) return 0;
const predicates: string[] = [];
if (hasOrderCode) predicates.push('t.order_code = $1');
if (hasOrderItemId && (await tableExists(client, 'order_items'))) {
predicates.push(
'EXISTS (SELECT 1 FROM order_items oi WHERE oi.id = t.order_item_id AND oi.order_code = $1)'
);
}
if (!predicates.length) return 0;
const result = await client.query(
`DELETE FROM ${table} t WHERE ${predicates.join(' OR ')}`,
[orderCode]
);
return result.rowCount || 0;
}
/** 成本调整表无 order_code,通过 cost_detail_id 挂到本单成本行 */
async function deleteCostAdjustmentsForOrder(client: PoolClient, orderCode: string): Promise<number> {
if (!(await tableExists(client, 'cost_adjustments'))) return 0;
if (!(await columnExists(client, 'cost_adjustments', 'cost_detail_id'))) return 0;
if (!(await tableExists(client, 'cost_details'))) return 0;
const result = await client.query(
`DELETE FROM cost_adjustments ca
WHERE ca.cost_detail_id IS NOT NULL
AND EXISTS (
SELECT 1 FROM cost_details cd
WHERE cd.id = ca.cost_detail_id AND cd.order_code = $1
)`,
[orderCode]
);
return result.rowCount || 0;
}
/**
* 删除订单关联业务数据(配送/成本/验收/采购等)。
* 多数表对 orders 无 FK CASCADE,必须显式清理,否则留下幽灵配送单与成本行。
* 商品毛利率由订单销售额 + cost_details 即时计算,无独立快照表;清掉订单与成本后即不再参与统计。
*/
async function deleteOrderRelatedRecords(
client: PoolClient,
orderCode: string
): Promise<{
deleted_purchases: number;
deleted_preparations: number;
deleted_delivery_tasks: number;
deleted_cost_details: number;
deleted_inspections: number;
deleted_related: Record<string, number>;
}> {
const related: Record<string, number> = {};
// 删整单时 CASCADE 删 order_item_fulfillments 会触发 trg_cleanup_orphan_fulfillments;
// 删整单不保留完成态自采单(purchase_orders/supplier_preparations 已在本函数按 order_code 先删,
// 触发器多数会因备货/自采单已不存在而短路,GUC 仅作契约兜底)
await client.query(`SELECT set_config('app.preserve_fulfilled_history', 'false', true)`);
const taskCodes = await client.query(
`SELECT task_code FROM delivery_tasks WHERE order_code = $1`,
[orderCode]
);
const codes = taskCodes.rows.map((row) => String(row.task_code)).filter(Boolean);
if (codes.length) {
const sig = await client.query(`DELETE FROM delivery_signatures WHERE task_code = ANY($1::text[])`, [
codes,
]);
related.delivery_signatures = sig.rowCount || 0;
const locs = await client.query(
`DELETE FROM delivery_person_locations WHERE task_code = ANY($1::text[])`,
[codes]
);
related.delivery_person_locations = locs.rowCount || 0;
}
related.delivery_signatures_by_order = await deleteByOrderCode(client, 'delivery_signatures', orderCode);
related.delivery_person_locations_by_order = await deleteByOrderCode(
client,
'delivery_person_locations',
orderCode
);
const deliveryTasks = await deleteByOrderCode(client, 'delivery_tasks', orderCode);
related.sign_records = await deleteByOrderCode(client, 'sign_records', orderCode);
related.cost_adjustments = await deleteCostAdjustmentsForOrder(client, orderCode);
const costDetails = await deleteByOrderCode(client, 'cost_details', orderCode);
related.allocation_tasks = await deleteByOrderCode(client, 'allocation_tasks', orderCode);
related.product_substitutions = await deleteByOrderCode(client, 'product_substitutions', orderCode);
related.after_sales = await deleteByOrderCode(client, 'after_sales', orderCode);
related.processing_logs = await deleteByOrderCode(client, 'processing_logs', orderCode);
related.processing_tasks = await deleteByOrderCode(client, 'processing_tasks', orderCode);
related.statement_lines = await deleteByOrderCode(client, 'statement_lines', orderCode);
related.exception_tickets = await deleteByOrderCode(
client,
'exception_tickets',
orderCode,
'related_order_code'
);
// inspection 子表多数 CASCADE,但仍有 order_code 冗余行,先按订单清一遍更稳妥
related.inspection_returns = await deleteByOrderCode(client, 'inspection_returns', orderCode);
related.inspection_loss_confirmations = await deleteByOrderCode(
client,
'inspection_loss_confirmations',
orderCode
);
const inspections = await deleteByOrderCode(client, 'inspections', orderCode);
// 删除订单时同步清理全部自采/备货(含已完成),避免留下 order_code 孤儿行
const purchaseResult = await deleteByOrderCode(client, 'purchase_orders', orderCode);
const prepResult = await deleteByOrderCode(client, 'supplier_preparations', orderCode);
// tenant schema 的业务 FK 在渐进恢复中;显式按叶子到根清理,兼容无 FK、
// NOT VALID 与已验证三个阶段,并避免物理删单留下订单树孤儿。
related.picking_items = await deleteOrderItemDependants(client, 'picking_items', orderCode);
related.order_item_fulfillments = await deleteOrderItemDependants(
client,
'order_item_fulfillments',
orderCode
);
related.order_item_returns = await deleteOrderItemDependants(
client,
'order_item_returns',
orderCode
);
// 2026-09-23 补齐:分拣容器/任务、预留、竞价轮次、备货改单申请原先漏清,
// 会留下无订单的孤儿行(实测 br003:picking_tasks 49、picking_containers 29、
// inventory_reservations 312、bid_rounds 11、supplier_prep_amend_requests 2)。
// 顺序:picking_items / order_item_fulfillments 已在上方先删,此处删其父行。
related.picking_containers = await deleteByOrderCode(client, 'picking_containers', orderCode);
related.picking_tasks = await deleteByOrderCode(client, 'picking_tasks', orderCode);
related.inventory_reservations = await deleteByOrderCode(client, 'inventory_reservations', orderCode);
related.bid_rounds = await deleteByOrderCode(client, 'bid_rounds', orderCode);
related.supplier_prep_amend_requests = await deleteByOrderCode(
client,
'supplier_prep_amend_requests',
orderCode
);
// ⚠️ 有意**不**清理 `inventory_logs`(库存流水台账):硬删订单**不回滚 `inventory`
// 数量**(本文件对 inventory 零引用,只有 releaseReservationsForOrder 改预留状态),
// 删流水会变成「有库存/已出库、无流水」,与 inventory-freeze「出库事实唯一以
// inventory_logs 为准」冲突。定性见 docs/design/20260920-inventory-freeze.md §11;
// server/tests/orderDeleteDependencies.test.ts 已 pin 住「不得出现该表」。
// notifications 也不在此处:由 deleteOrderWithDependencies 调
// deleteNotificationsByRelatedOrderCode 单独清理(见本文件下方)。
related.order_items = await deleteByOrderCode(client, 'order_items', orderCode);
return {
deleted_purchases: purchaseResult,
deleted_preparations: prepResult,
deleted_delivery_tasks: deliveryTasks,
deleted_cost_details: costDetails,
deleted_inspections: inspections,
deleted_related: related,
};
}
async function resolveOperatorName(userId: string, client: PoolClient): Promise<string | null> {
const result = await client.query(
`SELECT COALESCE(NULLIF(TRIM(full_name), ''), NULLIF(TRIM(username), '')) AS operator_name
FROM profiles WHERE id = $1`,
[userId]
);
return result.rows[0]?.operator_name ? String(result.rows[0].operator_name) : null;
}
/** 移入垃圾桶:保留明细与履约数据,财务/列表不再计入(B7: deleted_at=已取消,附 cancel_reason) */
/**
* 主系统分配过来的订单**禁止删除**(开发者 2026-10-10)。
* 台账里有对照(`main_system_order_imports.our_order_code`)即认定;
* 原生订单不受影响(反向对照见 tests/mainSystemDayMergeAndStockout.test.ts 与实测)。
*/
async function assertNotMainSystemOrder(
client: { query: (text: string, values?: unknown[]) => Promise<{ rowCount: number | null }> },
orderCode: string,
branchCode: string | null
): Promise<void> {
const imported = await client.query(
`SELECT 1 FROM public.main_system_order_imports
WHERE branch_code = $1 AND our_order_code = $2
LIMIT 1`,
[branchCode, orderCode]
);
if (imported.rowCount) {
throw Object.assign(
new Error('主系统分配过来的订单不能删除;商品供不了请用明细上的「缺货」'),
{ status: 409, code: 'main_system_order_locked' }
);
}
}
export async function moveOrderToTrash(
orderCode: string,
ctx: TenantContext,
meta?: { ipAddress?: string | null; cancelReason?: string | null }
): Promise<OrderTrashResult> {
const code = String(orderCode || '').trim();
if (!code) {
throw Object.assign(new Error('缺少 order_code'), { status: 400 });
}
assertOrderDeletePermission(ctx);
const cancelReason = String(meta?.cancelReason || '').trim().slice(0, 500) || null;
const client = await pool.connect();
try {
await client.query('BEGIN');
const orderResult = await client.query(
`SELECT o.order_code, o.branch_code, o.order_status, o.customer_code, o.total_amount,
o.delivery_date, o.cycle_code, o.deleted_at,
(SELECT COUNT(*)::int FROM order_items oi WHERE oi.order_code = o.order_code) AS item_count
FROM orders o
WHERE o.order_code = $1
FOR UPDATE`,
[code]
);
const order = orderResult.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404 });
}
assertOrderAccess(ctx, order);
if (order.deleted_at) {
throw Object.assign(new Error('订单已在垃圾桶中'), { status: 409, code: 'already_trashed' });
}
// 主系统分配过来的订单**不能删**(开发者 2026-10-10 口径):它是主系统备货任务的镜像,
// 删掉会让退货跟随/发车回写失去锚点,而主系统那边仍认为我们在备货。
// "这单供不了"要用明细上的「缺货」按钮(报主系统 status=40 转自采)。
await assertNotMainSystemOrder(client, code, order.branch_code || ctx.branchCode || null);
const itemSnapshot = await loadOrderItemSnapshot(client, code);
const operatorName = await resolveOperatorName(ctx.userId, client);
const updated = await client.query(
`UPDATE orders
SET deleted_at = NOW(),
deleted_by = $2,
deleted_by_name = $3,
cancel_reason = $4,
updated_at = NOW()
WHERE order_code = $1 AND deleted_at IS NULL
RETURNING order_code`,
[code, ctx.userId, operatorName, cancelReason]
);
if (!updated.rowCount) {
throw Object.assign(new Error('移入垃圾桶失败'), { status: 500 });
}
await removeCustomerStatementForOrder(code, client);
const statementSync = await recalculateStatementsAffectedByOrder(code, client);
await releaseReservationsForOrder(client, code);
await syncWarehouseProcessingDemandForOrder(code, client);
await client.query('COMMIT');
await writeAuditLog({
operatorId: ctx.userId,
operatorName,
operatorRole: ctx.roles.join(','),
operationType: 'order_trash',
targetTable: 'orders',
targetId: code,
oldValue: {
order_code: code,
order_status: Number(order.order_status),
customer_code: order.customer_code,
total_amount: Number(order.total_amount ?? 0),
delivery_date: order.delivery_date,
cycle_code: order.cycle_code,
item_count: Number(order.item_count ?? 0),
branch_code: order.branch_code,
items: itemSnapshot.items,
items_truncated: itemSnapshot.items_truncated,
},
newValue: {
trashed: true,
cancel_reason: cancelReason,
statement_sync: statementSync,
customer_statement: 'removed',
},
ipAddress: meta?.ipAddress || null,
branchCode: order.branch_code,
actionCategory: 'order',
}).catch((auditError) => {
console.error('[order-trash] 写入审计失败:', auditError);
});
return { order_code: code, trashed: true };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
/** 从垃圾桶恢复 */
export async function restoreOrderFromTrash(
orderCode: string,
ctx: TenantContext,
meta?: { ipAddress?: string | null }
): Promise<OrderRestoreResult> {
const code = String(orderCode || '').trim();
if (!code) {
throw Object.assign(new Error('缺少 order_code'), { status: 400 });
}
assertOrderDeletePermission(ctx);
const client = await pool.connect();
try {
await client.query('BEGIN');
const orderResult = await client.query(
`SELECT o.order_code, o.branch_code, o.order_status, o.customer_code, o.total_amount,
o.delivery_date, o.cycle_code, o.deleted_at, o.deleted_by_name
FROM orders o
WHERE o.order_code = $1
FOR UPDATE`,
[code]
);
const order = orderResult.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404 });
}
assertOrderAccess(ctx, order);
if (!order.deleted_at) {
throw Object.assign(new Error('订单不在垃圾桶中'), { status: 409, code: 'not_trashed' });
}
const updated = await client.query(
`UPDATE orders
SET deleted_at = NULL,
deleted_by = NULL,
deleted_by_name = NULL,
cancel_reason = NULL,
updated_at = NOW()
WHERE order_code = $1 AND deleted_at IS NOT NULL
RETURNING order_code`,
[code]
);
if (!updated.rowCount) {
throw Object.assign(new Error('恢复失败'), { status: 500 });
}
const customerStatement =
Number(order.order_status) >= 90
? await upsertCustomerStatementForOrder(code, client)
: 'empty';
const statementSync = await recalculateStatementsAffectedByOrder(code, client);
await syncWarehouseProcessingDemandForOrder(code, client);
await client.query('COMMIT');
const operatorName = await resolveOperatorName(ctx.userId, client);
await writeAuditLog({
operatorId: ctx.userId,
operatorName,
operatorRole: ctx.roles.join(','),
operationType: 'order_restore',
targetTable: 'orders',
targetId: code,
oldValue: {
deleted_at: order.deleted_at,
deleted_by_name: order.deleted_by_name,
order_status: Number(order.order_status),
customer_code: order.customer_code,
total_amount: Number(order.total_amount ?? 0),
},
newValue: { restored: true, statement_sync: statementSync, customer_statement: customerStatement },
ipAddress: meta?.ipAddress || null,
branchCode: order.branch_code,
actionCategory: 'order',
}).catch((auditError) => {
console.error('[order-restore] 写入审计失败:', auditError);
});
return { order_code: code, restored: true };
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
export async function listOrdersInTrash(
ctx: TenantContext,
operatingBranchCode?: string | null
): Promise<OrderTrashListRow[]> {
assertOrderDeletePermission(ctx);
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
if (ctx.isSuperAdmin && !branchCode) {
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
}
if (!ctx.isSuperAdmin && !branchCode) {
throw Object.assign(new Error('未分配分公司,无法查看垃圾桶'), { status: 403 });
}
const params: unknown[] = [];
let branchSql = '';
if (branchCode) {
params.push(branchCode);
branchSql = ` AND o.branch_code = $${params.length}`;
}
const result = await pool.query(
`SELECT o.order_code, o.customer_code, c.company_name, o.branch_code,
o.order_status, COALESCE(o.total_amount, 0)::float8 AS total_amount,
to_char(o.delivery_date::date, 'YYYY-MM-DD') AS delivery_date,
o.cycle_code,
o.deleted_at::text AS deleted_at,
o.deleted_by_name,
o.cancel_reason,
(SELECT COUNT(*)::int FROM order_items oi WHERE oi.order_code = o.order_code) AS item_count
FROM orders o
LEFT JOIN customers c ON c.customer_code = o.customer_code
WHERE o.deleted_at IS NOT NULL
${branchSql}
ORDER BY o.deleted_at DESC
LIMIT 500`,
params
);
return result.rows.map((row) => ({
order_code: String(row.order_code),
customer_code: row.customer_code ? String(row.customer_code) : null,
company_name: row.company_name ? String(row.company_name) : null,
branch_code: row.branch_code ? String(row.branch_code) : null,
order_status: Number(row.order_status) || 0,
total_amount: Number(row.total_amount) || 0,
delivery_date: row.delivery_date ? String(row.delivery_date) : null,
cycle_code: row.cycle_code ? String(row.cycle_code) : null,
deleted_at: String(row.deleted_at),
deleted_by_name: row.deleted_by_name ? String(row.deleted_by_name) : null,
cancel_reason: row.cancel_reason ? String(row.cancel_reason) : null,
item_count: Number(row.item_count) || 0,
}));
}
/** 垃圾桶内彻底删除(物理清理关联数据) */
export async function deleteOrderWithDependencies(
orderCode: string,
ctx: TenantContext,
existingClient?: PoolClient,
meta?: { ipAddress?: string | null; requireTrashed?: boolean }
): Promise<OrderDeleteResult> {
const code = String(orderCode || '').trim();
if (!code) {
throw Object.assign(new Error('缺少 order_code'), { status: 400 });
}
assertOrderDeletePermission(ctx);
const client = existingClient || (await pool.connect());
const ownsClient = !existingClient;
const requireTrashed = meta?.requireTrashed !== false;
try {
if (ownsClient) await client.query('BEGIN');
const orderResult = await client.query(
`SELECT o.order_code, o.branch_code, o.order_status, o.customer_code, o.total_amount,
o.delivery_date, o.cycle_code, o.deleted_at,
(SELECT COUNT(*)::int FROM order_items oi WHERE oi.order_code = o.order_code) AS item_count
FROM orders o
WHERE o.order_code = $1
FOR UPDATE`,
[code]
);
const order = orderResult.rows[0];
if (!order) {
throw Object.assign(new Error('订单不存在'), { status: 404 });
}
assertOrderAccess(ctx, order);
if (requireTrashed && !order.deleted_at) {
throw Object.assign(new Error('请先移入垃圾桶,再彻底删除'), {
status: 409,
code: 'not_trashed',
});
}
// 主系统分配过来的订单**不能删**(开发者 2026-10-10):这是通用数据网关
// (`/api/data` 的 orders delete 特判)与"垃圾桶彻底删除"共用的入口,
// 只拦 `moveOrderToTrash` 会漏掉这两条路。
await assertNotMainSystemOrder(client, code, order.branch_code || ctx.branchCode || null);
const itemSnapshot = await loadOrderItemSnapshot(client, code);
const statementRefs = await client.query(
`SELECT DISTINCT statement_no, statement_type
FROM statement_lines
WHERE order_code = $1`,
[code]
);
// order_code 一并带上:冻结单(statement_status >= 20)被红冲时要按订单号去重落异议
const refs: Array<{ statement_no: string; statement_type: string; order_code?: string }> =
statementRefs.rows.map((row) => ({
statement_no: String(row.statement_no),
statement_type: String(row.statement_type),
order_code: code,
}));
if (!refs.some((r) => r.statement_type === 'customer' && r.statement_no === code)) {
refs.push({ statement_no: code, statement_type: 'customer', order_code: code });
}
await removeCustomerStatementForOrder(code, client);
const related = await deleteOrderRelatedRecords(client, code);
// 预留行已随 deleteOrderRelatedRecords 一并删除,此调用在硬删路径上已是
// 「清 stock_cover_qty」的兜底(order_items 也已删除,故通常 0 行);
// 保留它是为了兼容 deleteOrderRelatedRecords 将来调整清理范围。移入垃圾桶
// (moveOrderToTrash)路径仍然依赖它把预留置 30——那条路径不删任何行。
await releaseReservationsForOrder(client, code);
const orderDeleteResult = await client.query(
`DELETE FROM orders WHERE order_code = $1 RETURNING order_code`,
[code]
);
if (!orderDeleteResult.rowCount) {
throw Object.assign(new Error('订单删除失败'), { status: 500 });
}
const statementSync = await recalculateStatementsFromRefs(refs, client);
const notificationCleanup = await deleteNotificationsByRelatedOrderCode(code, client);
if (ownsClient) await client.query('COMMIT');
const result: OrderDeleteResult = {
order_code: code,
deleted_purchases: related.deleted_purchases,
deleted_preparations: related.deleted_preparations,
deleted_delivery_tasks: related.deleted_delivery_tasks,
deleted_cost_details: related.deleted_cost_details,
deleted_inspections: related.deleted_inspections,
deleted_notifications: notificationCleanup.deleted,
deleted_related: related.deleted_related,
};
const operatorName = await resolveOperatorName(ctx.userId, client);
await writeAuditLog({
operatorId: ctx.userId,
operatorName,
operatorRole: ctx.roles.join(','),
operationType: 'order_purge',
targetTable: 'orders',
targetId: code,
oldValue: {
order_code: code,
order_status: Number(order.order_status),
customer_code: order.customer_code,
total_amount: Number(order.total_amount ?? 0),
delivery_date: order.delivery_date,
cycle_code: order.cycle_code,
item_count: Number(order.item_count ?? 0),
branch_code: order.branch_code,
deleted_at: order.deleted_at,
items: itemSnapshot.items,
items_truncated: itemSnapshot.items_truncated,
},
newValue: {
purged: true,
statement_sync: statementSync,
deleted_purchases: result.deleted_purchases,
deleted_preparations: result.deleted_preparations,
deleted_delivery_tasks: result.deleted_delivery_tasks,
deleted_cost_details: result.deleted_cost_details,
deleted_inspections: result.deleted_inspections,
deleted_notifications: result.deleted_notifications,
deleted_related: result.deleted_related,
},
ipAddress: meta?.ipAddress || null,
branchCode: order.branch_code,
actionCategory: 'order',
}).catch((auditError) => {
console.error('[order-purge] 写入审计失败:', auditError);
});
for (const userId of notificationCleanup.userIds) {
try {
const items = await listBellNotifications(userId, 20);
await publishNotificationEvent(userId, 'notifications_refresh', {
items,
unread_count: items.filter((item) => !item.is_read).length,
});
} catch (error) {
console.warn(`[order-purge] 通知刷新失败 user=${userId}:`, error);
}
}
return result;
} catch (error) {
if (ownsClient) await client.query('ROLLBACK');
throw error;
} finally {
if (ownsClient) client.release();
}
}
/**
* 清理已无订单的孤儿配送单 / 成本 / 验收等(历史删除遗留)。
*
* ⚠️ 当前**全仓无调用方**(只有本定义与 dist 产物)——要真用来清历史存量,必须先接一个
* 入口(脚本/管理接口)。本清单同时是「订单硬删应当清理哪些表」的第二份口径,两份必须一致。
*
* ⚠️ 有意**不含**两表:
* - `inventory_logs`:库存流水台账,随订单硬删保留(见 20260920-inventory-freeze.md §11);
* - `notifications`:`related_order_code` **混存 UUID 形态**(BR002 实测 1186 条非订单通知),
* 本函数的通用 `NOT EXISTS(orders)` 模板会把它们全部误判为孤儿并删除。通知只按
* `related_order_code LIKE 'ORD%'` 清,且活路径已由
* `deleteNotificationsByRelatedOrderCode` 负责。
*/
export async function cleanupOrphanOrderDependencies(
existingClient?: PoolClient
): Promise<Record<string, number>> {
const client = existingClient || (await pool.connect());
const ownsClient = !existingClient;
const counts: Record<string, number> = {};
const targets: Array<{ table: string; column: string }> = [
{ table: 'delivery_signatures', column: 'order_code' },
{ table: 'delivery_person_locations', column: 'order_code' },
{ table: 'delivery_tasks', column: 'order_code' },
{ table: 'sign_records', column: 'order_code' },
{ table: 'cost_details', column: 'order_code' },
{ table: 'allocation_tasks', column: 'order_code' },
{ table: 'product_substitutions', column: 'order_code' },
{ table: 'after_sales', column: 'order_code' },
{ table: 'processing_logs', column: 'order_code' },
{ table: 'processing_tasks', column: 'order_code' },
{ table: 'statement_lines', column: 'order_code' },
{ table: 'inspection_returns', column: 'order_code' },
{ table: 'inspection_loss_confirmations', column: 'order_code' },
{ table: 'inspections', column: 'order_code' },
{ table: 'purchase_orders', column: 'order_code' },
{ table: 'supplier_preparations', column: 'order_code' },
{ table: 'exception_tickets', column: 'related_order_code' },
// 2026-09-23 补齐(与 deleteOrderRelatedRecords 对齐):子表先于 order_items
{ table: 'picking_items', column: 'order_code' },
{ table: 'order_item_fulfillments', column: 'order_code' },
{ table: 'order_item_returns', column: 'order_code' },
{ table: 'picking_containers', column: 'order_code' },
{ table: 'picking_tasks', column: 'order_code' },
{ table: 'inventory_reservations', column: 'order_code' },
{ table: 'bid_rounds', column: 'order_code' },
{ table: 'supplier_prep_amend_requests', column: 'order_code' },
{ table: 'order_items', column: 'order_code' },
];
try {
if (ownsClient) await client.query('BEGIN');
for (const target of targets) {
if (!(await tableExists(client, target.table))) {
counts[target.table] = 0;
continue;
}
if (!(await columnExists(client, target.table, target.column))) {
counts[target.table] = 0;
continue;
}
const result = await client.query(
`DELETE FROM ${target.table} t
WHERE t.${target.column} IS NOT NULL
AND TRIM(t.${target.column}::text) <> ''
AND NOT EXISTS (
SELECT 1 FROM orders o WHERE o.order_code = t.${target.column}
)`
);
counts[target.table] = result.rowCount || 0;
}
// 孤儿成本调整:cost_detail 已不存在
if (
(await tableExists(client, 'cost_adjustments')) &&
(await columnExists(client, 'cost_adjustments', 'cost_detail_id'))
) {
const adj = await client.query(
`DELETE FROM cost_adjustments ca
WHERE ca.cost_detail_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM cost_details cd WHERE cd.id = ca.cost_detail_id
)`
);
counts.cost_adjustments = adj.rowCount || 0;
}
if (ownsClient) await client.query('COMMIT');
return counts;
} catch (error) {
if (ownsClient) await client.query('ROLLBACK');
throw error;
} finally {
if (ownsClient) client.release();
}
}