960 lines
41 KiB
TypeScript
960 lines
41 KiB
TypeScript
/**
|
||
* 主系统「商品退回」→ 售后记录 + **立即生成补送单**(2026-10-20 确认稿
|
||
* docs/design/20261020-主系统退回与补送.md)。
|
||
*
|
||
* 要点(与开发者确认):
|
||
* · 退回一发生就建补送单,**不等退回货物回来**(在途也可能);
|
||
* · 补送单是**普通订单**(`orders.source='return_resupply'`、`linked_order_code=原单`),
|
||
* 后续走完全既有的链路:库存抵扣 → 待分拣 → 分拣 → 通知/状态 → 配送 → 完成;
|
||
* · 回写主系统仍用**原 prep_id**(主系统已把该行打回"重新供货"),不给新单号;
|
||
* · 退回货物处置是后续独立动作(重新入库=待检 / 丢弃),不阻塞补送;
|
||
* · 幂等键:`(branch_code, main_return_code, sku_code)`(迁移 20261067 的唯一索引)。
|
||
*/
|
||
import type { PoolClient } from 'pg';
|
||
import { pool } from '../db';
|
||
|
||
export interface IngestMainSystemReturnInput {
|
||
branchCode: string;
|
||
/** 主系统退货码(幂等键;缺失时用 `${orderCode}:${skuCode}:${returnedAt}` 兜底) */
|
||
mainReturnCode?: string | null;
|
||
/** 主系统侧订单号(台账里的 main_order_code) */
|
||
mainOrderCode?: string | null;
|
||
/** 我方原订单号 */
|
||
ourOrderCode: string;
|
||
/** 主系统备货行 id(回写时复用) */
|
||
mainPrepId?: string | null;
|
||
skuCode: string;
|
||
itemName?: string | null;
|
||
/** 退回数量 */
|
||
quantity: number;
|
||
unit?: string | null;
|
||
reason?: string | null;
|
||
returnedAt?: string | null;
|
||
operatorId?: string | null;
|
||
}
|
||
|
||
export interface IngestMainSystemReturnResult {
|
||
returnCode: string;
|
||
afterSaleCode: string;
|
||
resupplyOrderCode: string | null;
|
||
/** true = 命中幂等(之前已处理过这条退回) */
|
||
duplicated: boolean;
|
||
}
|
||
|
||
/**
|
||
* 行级判据(容差 1e-6):累加后的退回量是否达到该行数量 ⇒ 整行标退。
|
||
* 部分退回**不**标 is_returned / 不写 return_code(裁决 2)。
|
||
*/
|
||
export function judgeReturnLine(input: { quantity: number; returnedQtyAfter: number }): { markReturned: boolean } {
|
||
const quantity = Number(input.quantity) || 0;
|
||
const returnedQtyAfter = Number(input.returnedQtyAfter) || 0;
|
||
return { markReturned: quantity > 0 ? returnedQtyAfter >= quantity - 1e-6 : returnedQtyAfter >= -1e-6 };
|
||
}
|
||
|
||
/**
|
||
* 整单判据:所有行都已标退、或剩余有效量 <= 1e-6 ⇒ 整单无有效剩余,应软取消。
|
||
* 生产链路用 SQL COUNT 判定;本函数用于单测与口径复核。
|
||
*/
|
||
export function shouldCancelOrder(
|
||
rows: Array<{ quantity: number | string; returnedQty: number | string; isReturned?: boolean | null }>
|
||
): boolean {
|
||
if (!Array.isArray(rows) || rows.length === 0) return true;
|
||
return rows.every((row) => {
|
||
if (row?.isReturned === true) return true;
|
||
const quantity = Number(row?.quantity) || 0;
|
||
const returnedQty = Number(row?.returnedQty) || 0;
|
||
return quantity - returnedQty <= 1e-6;
|
||
});
|
||
}
|
||
|
||
|
||
/**
|
||
* 取"带租户上下文"的连接:优先复用 `runWithTenantDbContext` 建立的会话连接
|
||
* (它已 SET search_path + app.branch_code);没有时才自己 connect。
|
||
* 不能直接 `pool.connect()`:那样会拿到没设上下文的连接 ⇒ FORCE RLS 拒绝写入
|
||
* (本地实测:`new row violates row-level security policy for table "after_sales"`)。
|
||
*/
|
||
async function acquireBranchClient(
|
||
branchCode: string
|
||
): Promise<{ client: PoolClient; release: () => void }> {
|
||
const { getTenantDbStore } = await import('./tenantDbContext');
|
||
const shared = getTenantDbStore()?.client;
|
||
if (shared) return { client: shared as PoolClient, release: () => undefined };
|
||
/**
|
||
* 自己拿连接时**必须走平台官方入口** `acquireTenantSessionClient`:
|
||
* 它除了 search_path 还会设置 `app.branch_code`(FORCE RLS 必需),
|
||
* 手工 set_config 不够(本地实测:`new row violates row-level security policy for table "after_sales"`)。
|
||
*/
|
||
const code = String(branchCode || '').trim();
|
||
if (!code) throw Object.assign(new Error('缺少分公司上下文'), { status: 400, code: 'branch_required' });
|
||
const { resolveActiveTenantSchema } = await import('./tenantSchemaService');
|
||
const schema = await resolveActiveTenantSchema(code);
|
||
if (!schema) throw Object.assign(new Error('分公司未启用租户 schema'), { status: 400, code: 'tenant_schema_missing' });
|
||
const { acquireTenantSessionClient, releaseTenantSessionClient } = await import('../db');
|
||
const client = await acquireTenantSessionClient(schema, code);
|
||
return { client, release: () => void releaseTenantSessionClient(client) };
|
||
}
|
||
|
||
const newCode = (prefix: string) =>
|
||
`${prefix}${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
||
|
||
/** 主系统退回 → 售后记录 + 补送单(幂等;单事务建单,分配在提交后 best-effort 触发) */
|
||
async function ingestMainSystemReturnInner(
|
||
input: IngestMainSystemReturnInput
|
||
): Promise<IngestMainSystemReturnResult> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const ourOrderCode = String(input.ourOrderCode || '').trim();
|
||
const skuCode = String(input.skuCode || '').trim();
|
||
const quantity = Number(input.quantity) || 0;
|
||
if (!branchCode || !ourOrderCode || !skuCode) {
|
||
throw Object.assign(new Error('缺少分公司/原订单/SKU'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
if (!(quantity > 0)) {
|
||
throw Object.assign(new Error('退回数量必须大于 0'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
const mainReturnCode =
|
||
String(input.mainReturnCode || '').trim() ||
|
||
`${ourOrderCode}:${skuCode}:${String(input.returnedAt || '')}`;
|
||
|
||
const { client, release } = await acquireBranchClient(branchCode);
|
||
let resupplyOrderCode: string | null = null;
|
||
let returnCode = '';
|
||
let afterSaleCode = '';
|
||
let duplicated = false;
|
||
let cancelledOrder = false;
|
||
try {
|
||
await client.query('BEGIN');
|
||
|
||
/**
|
||
* 0) 先解析**本地 SKU**(主/我方 SKU 可能不同:payload SKU98644620619 / 本地 SKU04114073410)。
|
||
* 优先台账 our_order_item_id → 本地行;再回退同单同 payload SKU;再回退台账 item_name。
|
||
* 后续 after_sales / after_sale_returns / 幂等查询 / 候选行全部用这个本地 SKU。
|
||
*/
|
||
type ReturnTargetLine = {
|
||
id: string;
|
||
sku_code: string | null;
|
||
customer_code: string | null;
|
||
item_name: string | null;
|
||
unit: string | null;
|
||
price: string | number | null;
|
||
category_code: string | null;
|
||
category_name: string | null;
|
||
processing_method: string | null;
|
||
processing_owner: string | null;
|
||
delivery_date: string | null;
|
||
quantity: string | number;
|
||
returned_qty: string | number;
|
||
order_deleted_at: string | null;
|
||
};
|
||
const targetSelect = `SELECT oi.id, oi.sku_code, o.customer_code, oi.item_name, oi.unit, oi.price,
|
||
oi.category_code, oi.category_name, oi.processing_method, oi.processing_owner,
|
||
to_char(o.delivery_date, 'YYYY-MM-DD') AS delivery_date,
|
||
oi.quantity, COALESCE(oi.returned_qty, 0) AS returned_qty,
|
||
o.deleted_at AS order_deleted_at
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code`;
|
||
let ledgerItemId = '';
|
||
let ledgerItemName = '';
|
||
if (input.mainPrepId) {
|
||
const ledger = await client.query<{ our_order_item_id: string | null; item_name: string | null }>(
|
||
`SELECT our_order_item_id::text AS our_order_item_id, item_name
|
||
FROM public.main_system_order_import_items
|
||
WHERE branch_code = $1 AND prep_id = $2
|
||
LIMIT 1`,
|
||
[branchCode, String(input.mainPrepId)]
|
||
);
|
||
ledgerItemId = String(ledger.rows[0]?.our_order_item_id || '').trim();
|
||
ledgerItemName = String(ledger.rows[0]?.item_name || '').trim();
|
||
}
|
||
let target: ReturnTargetLine | null = null;
|
||
if (ledgerItemId) {
|
||
const byId = await client.query<ReturnTargetLine>(
|
||
`${targetSelect}
|
||
WHERE oi.id = $2::uuid AND oi.order_code = $1 AND COALESCE(oi.is_returned, false) = false
|
||
LIMIT 1`,
|
||
[ourOrderCode, ledgerItemId]
|
||
);
|
||
target = byId.rows[0] || null;
|
||
}
|
||
if (!target) {
|
||
const byPayloadSku = await client.query<ReturnTargetLine>(
|
||
`${targetSelect}
|
||
WHERE oi.order_code = $1 AND oi.sku_code = $2 AND COALESCE(oi.is_returned, false) = false
|
||
ORDER BY oi.created_at ASC, oi.id ASC
|
||
LIMIT 1`,
|
||
[ourOrderCode, skuCode]
|
||
);
|
||
target = byPayloadSku.rows[0] || null;
|
||
}
|
||
if (!target && ledgerItemName) {
|
||
const byName = await client.query<ReturnTargetLine>(
|
||
`${targetSelect}
|
||
WHERE oi.order_code = $1 AND oi.item_name = $2 AND COALESCE(oi.is_returned, false) = false
|
||
ORDER BY oi.created_at ASC, oi.id ASC
|
||
LIMIT 1`,
|
||
[ourOrderCode, ledgerItemName]
|
||
);
|
||
target = byName.rows[0] || null;
|
||
}
|
||
const localSkuCode = String(target?.sku_code || skuCode).trim();
|
||
const targetIdForOrder = target?.id || ledgerItemId || '';
|
||
|
||
/**
|
||
* 1) 幂等:`(分公司 + 退货码 + SKU)` 只落一条。
|
||
* 主系统 2026-10-20 确认:**一次退回事件一个 return_code**,同一分公司内唯一;
|
||
* 重试/重复推送复用同一个码。因此**不能再把 order_code 放进幂等键** ——
|
||
* 否则同一退货码挂到别的订单时会被当成新退货,重复建售后 + 补送单(本地实测踩过)。
|
||
*/
|
||
const existed = await client.query<{ return_code: string; aftersale_code: string }>(
|
||
`SELECT return_code, aftersale_code FROM after_sale_returns
|
||
WHERE branch_code = $1 AND main_return_code = $2 AND sku_code = $3
|
||
LIMIT 1`,
|
||
[branchCode, mainReturnCode, localSkuCode]
|
||
);
|
||
if (existed.rowCount) {
|
||
await client.query('COMMIT');
|
||
return {
|
||
returnCode: String(existed.rows[0].return_code),
|
||
afterSaleCode: String(existed.rows[0].aftersale_code),
|
||
resupplyOrderCode: null,
|
||
duplicated: true,
|
||
};
|
||
}
|
||
|
||
// 1.5) 已无可退行(例如整单全退后主系统又发一个新退回码):
|
||
// 不新建售后/退回/补送;订单若还没软取消则补一次,然后按 2xx duplicated 返回。
|
||
const activeBefore = await client.query(
|
||
`SELECT 1
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(quantity, 0) - COALESCE(returned_qty, 0) > 1e-6
|
||
LIMIT 1`,
|
||
[ourOrderCode]
|
||
);
|
||
if (!activeBefore.rowCount) {
|
||
const recent = await client.query<{ return_code: string | null; aftersale_code: string | null }>(
|
||
`SELECT return_code, aftersale_code
|
||
FROM after_sale_returns
|
||
WHERE branch_code = $1 AND order_code = $2 AND sku_code = $3
|
||
ORDER BY created_at DESC
|
||
LIMIT 1`,
|
||
[branchCode, ourOrderCode, localSkuCode]
|
||
);
|
||
const recentReturnCode = String(recent.rows[0]?.return_code || '');
|
||
const recentAfterSaleCode = String(recent.rows[0]?.aftersale_code || '');
|
||
const cancelReason = `主系统全额退回:${mainReturnCode || recentReturnCode}`;
|
||
const cancelled = await client.query<{ order_code: string }>(
|
||
`UPDATE orders
|
||
SET deleted_at = COALESCE(deleted_at, NOW()),
|
||
cancel_reason = $2,
|
||
updated_at = NOW()
|
||
WHERE order_code = $1 AND deleted_at IS NULL
|
||
RETURNING order_code`,
|
||
[ourOrderCode, cancelReason]
|
||
);
|
||
const cancelledNow = (cancelled.rowCount || 0) > 0;
|
||
if (cancelledNow) {
|
||
const { recalculateStatementsAffectedByOrder } = await import('./financeReconciliationService');
|
||
await recalculateStatementsAffectedByOrder(ourOrderCode, client);
|
||
}
|
||
await client.query('COMMIT');
|
||
if (cancelledNow) {
|
||
try {
|
||
const { clearDayPointerIfPointsTo } = await import('./mirrorOrderClosureService');
|
||
await clearDayPointerIfPointsTo(branchCode, ourOrderCode);
|
||
} catch (error) {
|
||
console.warn('[main-system-return] 清当日占坑指针失败(不影响取消):', (error as Error)?.message || error);
|
||
}
|
||
}
|
||
return {
|
||
returnCode: recentReturnCode,
|
||
afterSaleCode: recentAfterSaleCode,
|
||
resupplyOrderCode: null,
|
||
duplicated: true,
|
||
};
|
||
}
|
||
|
||
// 2) 售后主单
|
||
afterSaleCode = newCode('AS');
|
||
returnCode = newCode('R');
|
||
const afterSale = await client.query<{ id: string }>(
|
||
`INSERT INTO after_sales
|
||
(aftersale_code, order_code, customer_code, aftersale_type, sku_code, quantity, reason, status, branch_code)
|
||
-- ⚠️ $2 同时用于 VALUES(varchar) 与子查询(orders.order_code varchar):显式 ::varchar 收敛
|
||
-- ⚠️ 必须写 branch_code:tenant RLS 策略是 branch_code = app.branch_code(否则写不进去)
|
||
VALUES ($1, $2::varchar, (SELECT customer_code FROM orders WHERE order_code = $2::varchar LIMIT 1),
|
||
'main_system_return', $3::varchar, $4, $5, 10, $6::varchar)
|
||
RETURNING id`,
|
||
[afterSaleCode, ourOrderCode, localSkuCode, quantity, input.reason || null, branchCode]
|
||
);
|
||
const afterSaleId = afterSale.rows[0]?.id || null;
|
||
|
||
// 3) 退回行(处置默认 pending,后续在售后里选 重新入库/丢弃)
|
||
await client.query(
|
||
`INSERT INTO after_sale_returns
|
||
(return_code, aftersale_code, after_sale_id, order_code, sku_code, quantity, reason,
|
||
status, branch_code, main_return_code, disposition, source, returned_at, quality_status)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, '10', $8, $9, 'pending', 'main_system', $10, 'pending')`,
|
||
[
|
||
returnCode,
|
||
afterSaleCode,
|
||
afterSaleId,
|
||
ourOrderCode,
|
||
localSkuCode,
|
||
quantity,
|
||
input.reason || null,
|
||
branchCode,
|
||
mainReturnCode,
|
||
input.returnedAt ? new Date(input.returnedAt) : new Date(),
|
||
]
|
||
);
|
||
|
||
// 4) 候选行:用第 0 步解析出的**本地 SKU** 过滤;目标行(台账 id)优先,其余按 created_at/id。
|
||
// 候选 = 同单同**本地 SKU** 的所有未标退行;台账目标行优先,其余按 created_at/id 稳定排序。
|
||
let candidates = (
|
||
await client.query<ReturnTargetLine>(
|
||
`${targetSelect}
|
||
WHERE oi.order_code = $1 AND oi.sku_code = $2 AND COALESCE(oi.is_returned, false) = false
|
||
ORDER BY CASE WHEN oi.id = $3::uuid THEN 0 ELSE 1 END ASC, oi.created_at ASC, oi.id ASC
|
||
FOR UPDATE OF oi`,
|
||
[ourOrderCode, localSkuCode, targetIdForOrder || '00000000-0000-0000-0000-000000000000']
|
||
)
|
||
).rows;
|
||
|
||
// 台账目标行陈旧/本地 SKU 对不上时,再用台账 item_name 在同单未退行里兜底(尽力避免 409)。
|
||
if (!candidates.length && ledgerItemName) {
|
||
candidates = (
|
||
await client.query<ReturnTargetLine>(
|
||
`${targetSelect}
|
||
WHERE oi.order_code = $1 AND oi.item_name = $2 AND COALESCE(oi.is_returned, false) = false
|
||
ORDER BY oi.created_at ASC, oi.id ASC
|
||
FOR UPDATE OF oi`,
|
||
[ourOrderCode, ledgerItemName]
|
||
)
|
||
).rows;
|
||
}
|
||
|
||
// 按行分配本次退回量;不足则整体拒绝(不静默截断,事务由外层 ROLLBACK)。
|
||
let remaining = quantity;
|
||
const allocations: Array<{
|
||
row: ReturnTargetLine;
|
||
take: number;
|
||
markReturned: boolean;
|
||
code: string;
|
||
}> = [];
|
||
for (const row of candidates) {
|
||
if (remaining <= 1e-6) break;
|
||
const rowQuantity = Number(row.quantity) || 0;
|
||
const alreadyReturned = Number(row.returned_qty) || 0;
|
||
const rowRemaining = Math.max(0, rowQuantity - alreadyReturned);
|
||
if (rowRemaining <= 1e-6) continue;
|
||
const take = Math.min(remaining, rowRemaining);
|
||
const { markReturned } = judgeReturnLine({
|
||
quantity: rowQuantity,
|
||
returnedQtyAfter: alreadyReturned + take,
|
||
});
|
||
allocations.push({
|
||
row,
|
||
take,
|
||
markReturned,
|
||
// return_code 全局唯一:首行用本次码,后续行加序号后缀
|
||
code: allocations.length === 0 ? returnCode : `${returnCode}_${allocations.length}`,
|
||
});
|
||
remaining -= take;
|
||
}
|
||
if (remaining > 1e-6) {
|
||
throw Object.assign(new Error('退回数量超过该订单行可退量'), {
|
||
status: 409,
|
||
code: 'return_qty_exceeds_line',
|
||
});
|
||
}
|
||
// 本次退回货值:按实际分配行计价(同 SKU 多行可能单价不同) = Σ(take × price)。
|
||
const returnAmount = Number(
|
||
allocations
|
||
.reduce((sum, allocation) => sum + allocation.take * (Number(allocation.row.price) || 0), 0)
|
||
.toFixed(2)
|
||
);
|
||
// 售后单补上金额;否则前端 Number(amount)||0 会显示 ¥0。
|
||
if (afterSaleId) {
|
||
await client.query(`UPDATE after_sales SET amount = $2 WHERE id = $1`, [afterSaleId, returnAmount]);
|
||
}
|
||
|
||
const line = candidates[0] || null;
|
||
// Root-cause guard: one unfinished resupply order per original order (DB unique index 20261070).
|
||
// Reuse it instead of inserting a second one (previously threw 23505 -> 500).
|
||
const preExistingResupply = await client.query<{ order_code: string }>(
|
||
`SELECT order_code FROM orders
|
||
WHERE source = 'return_resupply' AND linked_order_code = $1 AND order_status < 90
|
||
LIMIT 1`,
|
||
[ourOrderCode]
|
||
);
|
||
const existingResupplyCode = String(preExistingResupply.rows[0]?.order_code || '');
|
||
if (existingResupplyCode) resupplyOrderCode = existingResupplyCode;
|
||
if (line && !line.order_deleted_at && !existingResupplyCode) {
|
||
resupplyOrderCode = newCode('ORD_RS_');
|
||
// 补送单复用同一货值,不重复计算。
|
||
const resupplyTotal = returnAmount;
|
||
// 补送行单价用加权均价(总额/数量),金额用总额,避免按首行单价重复计。
|
||
const resupplyUnitPrice = quantity > 0 ? Number((resupplyTotal / quantity).toFixed(2)) : 0;
|
||
await client.query(
|
||
`INSERT INTO orders
|
||
(order_code, cycle_code, bid_code, customer_code, order_status, total_amount, total_weight,
|
||
remark, created_by, branch_code, delivery_date, self_pickup, source, linked_order_code)
|
||
VALUES ($1, 'MOBILE', 'MOBILE', $2, 20, $3, $4, $5, $6, $7,
|
||
COALESCE($8::date, CURRENT_DATE), false, 'return_resupply', $9)`,
|
||
[
|
||
resupplyOrderCode,
|
||
line.customer_code,
|
||
resupplyTotal,
|
||
quantity,
|
||
`主系统退回补送(原单 ${ourOrderCode},退回单 ${returnCode})`,
|
||
input.operatorId || null,
|
||
branchCode,
|
||
line.delivery_date,
|
||
ourOrderCode,
|
||
]
|
||
);
|
||
const insertedItem = await client.query<{ id: string }>(
|
||
`INSERT INTO order_items
|
||
(order_code, sku_code, item_name, quantity, unit, price, category_code, category_name,
|
||
supplier_code, processing_method, processing_owner, sort_order, branch_code, amount)
|
||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'UNASSIGNED', $9, $10, 0, $11::varchar,
|
||
$12::numeric)
|
||
RETURNING id`,
|
||
[
|
||
resupplyOrderCode,
|
||
localSkuCode || skuCode,
|
||
line.item_name || input.itemName || localSkuCode || skuCode,
|
||
quantity,
|
||
line.unit || input.unit || null,
|
||
resupplyUnitPrice,
|
||
line.category_code,
|
||
line.category_name,
|
||
line.processing_method,
|
||
line.processing_owner,
|
||
branchCode,
|
||
resupplyTotal,
|
||
]
|
||
);
|
||
const resupplyItemId = insertedItem.rows[0]?.id || null;
|
||
/**
|
||
* 台账映射(任务 1):`(branch_code, prep_id)` 唯一 ⇒ 不新增行,改为记"补送单指向"。
|
||
* · `our_order_code` 保留原单(历史链可追溯),回写时用 `COALESCE(resupply_order_code, our_order_code)`
|
||
* · `writeback_status` 重置为 suspended ⇒ 下一轮对账会按补送单重新回写(主系统该行已被打回"重新供货")
|
||
*/
|
||
if (input.mainPrepId) {
|
||
await client.query(
|
||
`UPDATE public.main_system_order_import_items
|
||
SET resupply_order_code = $3,
|
||
resupply_order_item_id = $4,
|
||
writeback_status = 'suspended',
|
||
writeback_reason = '主系统退回:由补送单重新供货后回写',
|
||
updated_at = NOW()
|
||
WHERE branch_code = $1 AND prep_id = $2`,
|
||
[branchCode, String(input.mainPrepId), resupplyOrderCode, resupplyItemId]
|
||
);
|
||
}
|
||
await client.query(
|
||
`UPDATE after_sale_returns SET resupply_order_code = $2, updated_at = NOW() WHERE return_code = $1`,
|
||
[returnCode, resupplyOrderCode]
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 5) 原单折减(任务 3):记录该行已退回数量,并按**实际供货量**重算订单金额/重量。
|
||
* · `returned_qty` 累加(多次部分退回可叠加)
|
||
* · `orders.total_amount/total_weight` 用 `quantity - returned_qty` 重算 ⇒ 统计/结算/报表
|
||
* 自动按净供货计,**无需改任何查询**,也不会与补送单重复计
|
||
* · `stock_cover_qty`/`cover_batches` **不动**(库存回补由售后处置决定,不自动回补)
|
||
* · 全部退回时,订单只写 `deleted_at` 软取消,**不改 order_status**
|
||
*/
|
||
for (const allocation of allocations) {
|
||
// ① 逐行累加(跨行时每行只加自己分到的量)
|
||
await client.query(
|
||
`UPDATE order_items
|
||
SET returned_qty = COALESCE(returned_qty, 0) + $2
|
||
WHERE id = $1`,
|
||
[allocation.row.id, allocation.take]
|
||
);
|
||
// ② 达到该行数量才标退;首行用本次 R 码,后续行用序号后缀避免唯一索引冲突
|
||
if (allocation.markReturned) {
|
||
await client.query(
|
||
`UPDATE order_items
|
||
SET is_returned = true,
|
||
return_code = $2
|
||
WHERE id = $1 AND COALESCE(is_returned, false) = false`,
|
||
[allocation.row.id, allocation.code]
|
||
);
|
||
}
|
||
}
|
||
await client.query(
|
||
`UPDATE orders SET
|
||
total_amount = COALESCE((
|
||
SELECT ROUND(SUM(
|
||
CASE WHEN COALESCE(oi.is_returned, false) THEN 0
|
||
ELSE GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.returned_qty, 0))
|
||
END * COALESCE(oi.price, 0))::numeric, 2)
|
||
FROM order_items oi WHERE oi.order_code = orders.order_code), 0),
|
||
total_weight = COALESCE((
|
||
SELECT ROUND(SUM(
|
||
CASE WHEN COALESCE(oi.is_returned, false) THEN 0
|
||
ELSE GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.returned_qty, 0))
|
||
END)::numeric, 2)
|
||
FROM order_items oi WHERE oi.order_code = orders.order_code), 0),
|
||
updated_at = NOW()
|
||
WHERE order_code = $1`,
|
||
[ourOrderCode]
|
||
);
|
||
|
||
// ③ 重算后判定:剩余有效行数 = 0 ⇒ 软取消(只写 deleted_at,不改 order_status)
|
||
const active = await client.query<{ n: string | number }>(
|
||
`SELECT COUNT(*)::int AS n
|
||
FROM order_items
|
||
WHERE order_code = $1
|
||
AND COALESCE(is_returned, false) = false
|
||
AND COALESCE(quantity, 0) - COALESCE(returned_qty, 0) > 1e-6`,
|
||
[ourOrderCode]
|
||
);
|
||
if (Number(active.rows[0]?.n || 0) === 0) {
|
||
const cancelReason = `主系统全额退回:${mainReturnCode || returnCode}`;
|
||
const cancelled = await client.query<{ order_code: string }>(
|
||
`UPDATE orders
|
||
SET deleted_at = COALESCE(deleted_at, NOW()),
|
||
cancel_reason = $2,
|
||
updated_at = NOW()
|
||
WHERE order_code = $1 AND deleted_at IS NULL
|
||
RETURNING order_code`,
|
||
[ourOrderCode, cancelReason]
|
||
);
|
||
cancelledOrder = (cancelled.rowCount || 0) > 0;
|
||
}
|
||
// 只要本次有行被退回(标退/部分退),就在标退之后重算结算;整单取消也只调一次。
|
||
if (allocations.length > 0) {
|
||
const { recalculateStatementsAffectedByOrder } = await import('./financeReconciliationService');
|
||
await recalculateStatementsAffectedByOrder(ourOrderCode, client);
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
release();
|
||
}
|
||
|
||
// 提交后:软取消成功才清"当日占坑指针",防止下一轮导入往垃圾桶单追加(幂等,失败不阻断)。
|
||
if (cancelledOrder) {
|
||
try {
|
||
const { clearDayPointerIfPointsTo } = await import('./mirrorOrderClosureService');
|
||
await clearDayPointerIfPointsTo(branchCode, ourOrderCode);
|
||
} catch (error) {
|
||
console.warn('[main-system-return] 清当日占坑指针失败(不影响退回/取消):', (error as Error)?.message || error);
|
||
}
|
||
}
|
||
|
||
// 5) 提交后:走既有分配/库存抵扣链路(失败不阻断——补送单已建,可人工重试)
|
||
if (resupplyOrderCode) {
|
||
try {
|
||
const { reprocessOrderAllocation } = await import('./orderAllocationService');
|
||
// 签名:reprocessOrderAllocation(orderCode, customerCode?, branchCode?, externalClient?, options)
|
||
await reprocessOrderAllocation(resupplyOrderCode, null, branchCode);
|
||
} catch (error) {
|
||
console.warn('[main-system-return] 补送单自动分配失败(可人工重试):', (error as Error)?.message || error);
|
||
}
|
||
}
|
||
|
||
return { returnCode, afterSaleCode, resupplyOrderCode, duplicated: false };
|
||
}
|
||
|
||
/**
|
||
* 退回货物处置(方案 B:重新入库先进"待检不可用",质量确认合格后才转可用)。
|
||
* · action='restock':把退回量记回库存「数量」(`available_qty` **不加**)并写 `return_in` 流水;
|
||
* 需要 `batchNo`(退回货回到哪个批次)。
|
||
* · action='discard':写 `scrap` 流水记损耗,不回补库存。
|
||
* 幂等:已是终态(restocked/discarded)直接返回,不重复记账。
|
||
*/
|
||
async function applyReturnDispositionInner(input: {
|
||
branchCode: string;
|
||
returnCode: string;
|
||
action: 'restock' | 'discard';
|
||
batchNo?: string | null;
|
||
operatorId?: string | null;
|
||
}): Promise<{ returnCode: string; disposition: string; qualityStatus: string | null }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const returnCode = String(input.returnCode || '').trim();
|
||
if (!branchCode || !returnCode) {
|
||
throw Object.assign(new Error('缺少分公司/退回单号'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
const { client, release } = await acquireBranchClient(branchCode);
|
||
try {
|
||
await client.query('BEGIN');
|
||
const cur = await client.query<{
|
||
order_code: string | null;
|
||
sku_code: string | null;
|
||
quantity: string | number;
|
||
disposition: string | null;
|
||
}>(
|
||
`SELECT order_code, sku_code, quantity, disposition FROM after_sale_returns
|
||
WHERE return_code = $1 AND branch_code = $2 LIMIT 1`,
|
||
[returnCode, branchCode]
|
||
);
|
||
if (!cur.rowCount) throw Object.assign(new Error('退回记录不存在'), { status: 404, code: 'not_found' });
|
||
const row = cur.rows[0];
|
||
const qty = Number(row.quantity) || 0;
|
||
const skuCode = String(row.sku_code || '');
|
||
const orderCode = String(row.order_code || '');
|
||
if (row.disposition === 'restocked' || row.disposition === 'discarded') {
|
||
await client.query('COMMIT');
|
||
return { returnCode, disposition: String(row.disposition), qualityStatus: null };
|
||
}
|
||
|
||
if (input.action === 'discard') {
|
||
await client.query(
|
||
`INSERT INTO inventory_logs (sku_code, batch_no, operation_type, quantity, related_order_code, operator_id, remark, branch_code)
|
||
VALUES ($1, $2, 'scrap', $3, $4, $5, $6, $7)`,
|
||
[skuCode, input.batchNo || null, -Math.abs(qty), orderCode || null, input.operatorId || null, '主系统退回:丢弃', branchCode]
|
||
);
|
||
await client.query(
|
||
`UPDATE after_sale_returns SET disposition='discarded', quality_status='rejected', restocked_at=NOW(), updated_at=NOW()
|
||
WHERE return_code=$1`,
|
||
[returnCode]
|
||
);
|
||
await client.query('COMMIT');
|
||
return { returnCode, disposition: 'discarded', qualityStatus: 'rejected' };
|
||
}
|
||
|
||
// restock:先进"待检不可用"(数量加回,available_qty 不加)
|
||
const batchNo = String(input.batchNo || '').trim();
|
||
if (!batchNo) {
|
||
await client.query('ROLLBACK');
|
||
throw Object.assign(new Error('重新入库需要指定退回批次'), { status: 400, code: 'batch_required' });
|
||
}
|
||
const inv = await client.query<{ id: string }>(
|
||
`SELECT id FROM inventory WHERE batch_no = $1 AND sku_code = $2 LIMIT 1`,
|
||
[batchNo, skuCode]
|
||
);
|
||
if (inv.rowCount) {
|
||
await client.query(`UPDATE inventory SET quantity = COALESCE(quantity, 0) + $2 WHERE id = $1`, [
|
||
inv.rows[0].id,
|
||
qty,
|
||
]);
|
||
} else {
|
||
await client.query(
|
||
`INSERT INTO inventory (sku_code, batch_no, warehouse_code, quantity, available_qty, branch_code, status)
|
||
VALUES ($1, $2, 'MAIN', $3, 0, $4, 'pending_inspect')`,
|
||
[skuCode, batchNo, qty, branchCode]
|
||
);
|
||
}
|
||
await client.query(
|
||
`INSERT INTO inventory_logs (sku_code, batch_no, operation_type, quantity, related_order_code, operator_id, remark, branch_code)
|
||
VALUES ($1, $2, 'return_in', $3, $4, $5, $6, $7)`,
|
||
[skuCode, batchNo, Math.abs(qty), orderCode || null, input.operatorId || null, '主系统退回:重新入库(待检)', branchCode]
|
||
);
|
||
await client.query(
|
||
`UPDATE after_sale_returns SET disposition='restock_pending_inspect', quality_status='pending',
|
||
restock_batch_no=$2, updated_at=NOW()
|
||
WHERE return_code=$1`,
|
||
[returnCode, batchNo]
|
||
);
|
||
await client.query('COMMIT');
|
||
return { returnCode, disposition: 'restock_pending_inspect', qualityStatus: 'pending' };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
release();
|
||
}
|
||
}
|
||
|
||
/** 退回入库质量确认:合格 ⇒ 待检量转可用;不合格 ⇒ 记废弃。 */
|
||
async function confirmReturnQualityInner(input: {
|
||
branchCode: string;
|
||
returnCode: string;
|
||
qualified: boolean;
|
||
operatorId?: string | null;
|
||
}): Promise<{ returnCode: string; disposition: string; qualityStatus: string }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const returnCode = String(input.returnCode || '').trim();
|
||
const { client, release } = await acquireBranchClient(branchCode);
|
||
try {
|
||
await client.query('BEGIN');
|
||
const cur = await client.query<{
|
||
sku_code: string | null;
|
||
quantity: string | number;
|
||
restock_batch_no: string | null;
|
||
disposition: string | null;
|
||
order_code: string | null;
|
||
}>(
|
||
`SELECT sku_code, quantity, restock_batch_no, disposition, order_code
|
||
FROM after_sale_returns WHERE return_code=$1 AND branch_code=$2 LIMIT 1`,
|
||
[returnCode, branchCode]
|
||
);
|
||
if (!cur.rowCount) throw Object.assign(new Error('退回记录不存在'), { status: 404, code: 'not_found' });
|
||
const row = cur.rows[0];
|
||
if (row.disposition !== 'restock_pending_inspect') {
|
||
await client.query('ROLLBACK');
|
||
throw Object.assign(new Error('该退回单不在待检状态'), { status: 409, code: 'invalid_state' });
|
||
}
|
||
const qty = Number(row.quantity) || 0;
|
||
const skuCode = String(row.sku_code || '');
|
||
const batchNo = String(row.restock_batch_no || '');
|
||
if (input.qualified) {
|
||
await client.query(
|
||
`UPDATE inventory SET available_qty = COALESCE(available_qty, 0) + $3
|
||
WHERE batch_no = $1 AND sku_code = $2`,
|
||
[batchNo, skuCode, qty]
|
||
);
|
||
await client.query(
|
||
`UPDATE after_sale_returns SET disposition='restocked', quality_status='qualified', restocked_at=NOW(), updated_at=NOW()
|
||
WHERE return_code=$1`,
|
||
[returnCode]
|
||
);
|
||
await client.query('COMMIT');
|
||
return { returnCode, disposition: 'restocked', qualityStatus: 'qualified' };
|
||
}
|
||
await client.query(
|
||
`INSERT INTO inventory_logs (sku_code, batch_no, operation_type, quantity, related_order_code, operator_id, remark, branch_code)
|
||
VALUES ($1, $2, 'scrap', $3, $4, $5, $6, $7)`,
|
||
[skuCode, batchNo || null, -Math.abs(qty), row.order_code || null, input.operatorId || null, '退回入库质检不合格:丢弃', branchCode]
|
||
);
|
||
await client.query(
|
||
`UPDATE after_sale_returns SET disposition='discarded', quality_status='rejected', restocked_at=NOW(), updated_at=NOW()
|
||
WHERE return_code=$1`,
|
||
[returnCode]
|
||
);
|
||
await client.query('COMMIT');
|
||
return { returnCode, disposition: 'discarded', qualityStatus: 'rejected' };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK').catch(() => undefined);
|
||
throw error;
|
||
} finally {
|
||
release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 轮询兜底:扫描台账里**出现新退货码**的备货行,逐个落退回单 + 补送单。
|
||
* 主系统即使还没推 `preparations.returned`,我们也能在一个对账周期内自动跟上。
|
||
* 幂等由 `after_sale_returns(branch_code, main_return_code, sku_code)` 唯一索引保证。
|
||
*/
|
||
async function ingestReturnsFromLedgerInner(input: { branchCode: string }): Promise<{
|
||
scanned: number;
|
||
created: number;
|
||
skipped: number;
|
||
}> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!branchCode) return { scanned: 0, created: 0, skipped: 0 };
|
||
|
||
const rows = await pool.query<{
|
||
prep_id: string;
|
||
our_order_code: string | null;
|
||
our_order_item_id: string | null;
|
||
last_return_code: string;
|
||
last_prepare_qty: string | number | null;
|
||
item_name: string | null;
|
||
main_sku_code: string | null;
|
||
}>(
|
||
`SELECT li.prep_id, li.our_order_code, li.our_order_item_id, li.last_return_code,
|
||
li.last_prepare_qty, li.item_name, li.main_sku_code
|
||
FROM public.main_system_order_import_items li
|
||
WHERE li.branch_code = $1
|
||
AND li.last_return_code IS NOT NULL
|
||
AND TRIM(li.last_return_code) <> ''
|
||
AND COALESCE(li.disposition, 'imported') IN ('imported', 'completed', 'suspended')
|
||
AND li.our_order_code IS NOT NULL
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM after_sale_returns r
|
||
WHERE r.branch_code = li.branch_code
|
||
AND r.main_return_code = li.last_return_code
|
||
AND r.order_code = li.our_order_code
|
||
)
|
||
LIMIT 100`,
|
||
[branchCode]
|
||
);
|
||
|
||
let created = 0;
|
||
let skipped = 0;
|
||
for (const row of rows.rows) {
|
||
try {
|
||
// 我方订单行 → 取我方 SKU 与价格(台账里只有主系统 SKU)
|
||
const item = row.our_order_item_id
|
||
? await pool.query<{ sku_code: string | null; item_name: string | null; unit: string | null }>(
|
||
`SELECT sku_code, item_name, unit FROM order_items WHERE id = $1 LIMIT 1`,
|
||
[row.our_order_item_id]
|
||
)
|
||
: { rows: [] as Array<{ sku_code: string | null; item_name: string | null; unit: string | null }> };
|
||
const skuCode = String(item.rows[0]?.sku_code || '').trim();
|
||
if (!skuCode) {
|
||
skipped += 1;
|
||
console.warn('[main-system-return] 台账行找不到我方 SKU,跳过', { prepId: row.prep_id });
|
||
continue;
|
||
}
|
||
const qty = Number(row.last_prepare_qty) || 0;
|
||
if (!(qty > 0)) {
|
||
skipped += 1;
|
||
continue;
|
||
}
|
||
const result = await ingestMainSystemReturn({
|
||
branchCode,
|
||
mainReturnCode: String(row.last_return_code),
|
||
ourOrderCode: String(row.our_order_code),
|
||
mainPrepId: String(row.prep_id),
|
||
skuCode,
|
||
itemName: item.rows[0]?.item_name || row.item_name || null,
|
||
quantity: qty,
|
||
unit: item.rows[0]?.unit || null,
|
||
reason: '主系统退回(台账轮询识别)',
|
||
returnedAt: new Date().toISOString(),
|
||
});
|
||
if (!result.duplicated) created += 1;
|
||
} catch (error) {
|
||
skipped += 1;
|
||
console.warn('[main-system-return] 轮询落单失败', {
|
||
prepId: row.prep_id,
|
||
error: (error as Error)?.message || error,
|
||
});
|
||
}
|
||
}
|
||
return { scanned: rows.rowCount || 0, created, skipped };
|
||
}
|
||
|
||
/** 按主系统备货行 id 反查我方订单号(路由层不写 SQL,故放这里) */
|
||
async function resolveOrderCodeByPrepIdInner(input: {
|
||
branchCode: string;
|
||
prepId: string;
|
||
}): Promise<string | null> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
const prepId = String(input.prepId || '').trim();
|
||
if (!branchCode || !prepId) return null;
|
||
const { rows } = await pool.query<{ our_order_code: string | null }>(
|
||
`SELECT our_order_code FROM public.main_system_order_import_items
|
||
WHERE branch_code = $1 AND prep_id = $2 LIMIT 1`,
|
||
[branchCode, prepId]
|
||
);
|
||
return String(rows[0]?.our_order_code || '').trim() || null;
|
||
}
|
||
|
||
/** 退回单列表(售后 → 退回处置用;按处置状态筛)。 */
|
||
async function listMainSystemReturnsInner(input: {
|
||
branchCode: string;
|
||
disposition?: string | null;
|
||
limit?: number;
|
||
}): Promise<
|
||
Array<{
|
||
return_code: string;
|
||
aftersale_code: string;
|
||
order_code: string | null;
|
||
sku_code: string | null;
|
||
item_name: string | null;
|
||
quantity: number;
|
||
reason: string | null;
|
||
disposition: string;
|
||
quality_status: string | null;
|
||
resupply_order_code: string | null;
|
||
restock_batch_no: string | null;
|
||
returned_at: string | null;
|
||
}>
|
||
> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!branchCode) return [];
|
||
const limit = Math.min(Math.max(Number(input.limit) || 100, 1), 300);
|
||
const disposition = String(input.disposition || '').trim();
|
||
const params: unknown[] = [branchCode];
|
||
let filter = '';
|
||
if (disposition) {
|
||
params.push(disposition);
|
||
filter = ` AND r.disposition = $${params.length}`;
|
||
}
|
||
params.push(limit);
|
||
const { rows } = await pool.query(
|
||
`SELECT r.return_code, r.aftersale_code, r.order_code, r.sku_code,
|
||
COALESCE(oi.item_name, li.item_name, r.sku_code) AS item_name,
|
||
r.quantity, r.reason, COALESCE(r.disposition, 'pending') AS disposition,
|
||
r.quality_status, r.resupply_order_code, r.restock_batch_no,
|
||
to_char(r.returned_at, 'YYYY-MM-DD HH24:MI') AS returned_at
|
||
FROM after_sale_returns r
|
||
LEFT JOIN order_items oi ON oi.order_code = r.order_code AND oi.sku_code = r.sku_code
|
||
-- 退回行可能以主系统 SKU 落库(存量/幂等键):用台账 item_name 兜底显示
|
||
LEFT JOIN LATERAL (
|
||
SELECT li.item_name
|
||
FROM public.main_system_order_import_items li
|
||
WHERE li.branch_code = r.branch_code
|
||
AND li.our_order_code = r.order_code
|
||
AND li.main_sku_code = r.sku_code
|
||
ORDER BY li.updated_at DESC
|
||
LIMIT 1
|
||
) li ON TRUE
|
||
WHERE r.branch_code = $1${filter}
|
||
ORDER BY r.returned_at DESC NULLS LAST, r.created_at DESC
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
return rows.map((r: any) => ({
|
||
return_code: String(r.return_code),
|
||
aftersale_code: String(r.aftersale_code),
|
||
order_code: r.order_code ?? null,
|
||
sku_code: r.sku_code ?? null,
|
||
item_name: r.item_name ?? null,
|
||
quantity: Number(r.quantity) || 0,
|
||
reason: r.reason ?? null,
|
||
disposition: String(r.disposition || 'pending'),
|
||
quality_status: r.quality_status ?? null,
|
||
resupply_order_code: r.resupply_order_code ?? null,
|
||
restock_batch_no: r.restock_batch_no ?? null,
|
||
returned_at: r.returned_at ?? null,
|
||
}));
|
||
}
|
||
|
||
/* ─────────────────────────────────────────────────────────────────────────────
|
||
* 租户上下文包装(2026-10-20 修):
|
||
* 本模块直接查**租户 schema 下的表**(after_sales / after_sale_returns / orders / inventory…),
|
||
* 必须跑在 `runWithTenantDbContext` 里,否则 search_path 指向 public ⇒
|
||
* `relation "after_sale_returns" does not exist`(本地实测踩到,事件收到但落不了单)。
|
||
* ──────────────────────────────────────────────────────────────────────────── */
|
||
|
||
export async function ingestMainSystemReturn(input: IngestMainSystemReturnInput) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => ingestMainSystemReturnInner(input));
|
||
}
|
||
|
||
export async function applyReturnDisposition(input: {
|
||
branchCode: string;
|
||
returnCode: string;
|
||
action: 'restock' | 'discard';
|
||
batchNo?: string | null;
|
||
operatorId?: string | null;
|
||
}) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => applyReturnDispositionInner(input));
|
||
}
|
||
|
||
export async function confirmReturnQuality(input: {
|
||
branchCode: string;
|
||
returnCode: string;
|
||
qualified: boolean;
|
||
operatorId?: string | null;
|
||
}) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => confirmReturnQualityInner(input));
|
||
}
|
||
|
||
export async function listMainSystemReturns(input: {
|
||
branchCode: string;
|
||
disposition?: string | null;
|
||
limit?: number;
|
||
}) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => listMainSystemReturnsInner(input));
|
||
}
|
||
|
||
export async function ingestReturnsFromLedger(input: { branchCode: string }) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => ingestReturnsFromLedgerInner(input));
|
||
}
|
||
|
||
export async function resolveOrderCodeByPrepId(input: { branchCode: string; prepId: string }) {
|
||
const { runWithTenantDbContext } = await import('./tenantDbContext');
|
||
return runWithTenantDbContext(input.branchCode, () => resolveOrderCodeByPrepIdInner(input));
|
||
}
|