diff --git a/server/src/services/mainSystemReturnService.ts b/server/src/services/mainSystemReturnService.ts new file mode 100644 index 0000000..64f2347 --- /dev/null +++ b/server/src/services/mainSystemReturnService.ts @@ -0,0 +1,210 @@ +/** + * 主系统「商品退回」→ 售后记录 + **立即生成补送单**(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 { 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; +} + +const newCode = (prefix: string) => + `${prefix}${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; + +/** 主系统退回 → 售后记录 + 补送单(幂等;单事务建单,分配在提交后 best-effort 触发) */ +export async function ingestMainSystemReturn( + input: IngestMainSystemReturnInput +): Promise { + 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 = await pool.connect(); + let resupplyOrderCode: string | null = null; + let returnCode = ''; + let afterSaleCode = ''; + let duplicated = false; + try { + await client.query('BEGIN'); + + // 1) 幂等:同一 (branch, main_return_code, sku) 只落一条 + 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, skuCode] + ); + 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, + }; + } + + // 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) + VALUES ($1, $2, (SELECT customer_code FROM orders WHERE order_code = $2 LIMIT 1), + 'main_system_return', $3, $4, $5, 10) + RETURNING id`, + [afterSaleCode, ourOrderCode, skuCode, quantity, input.reason || null] + ); + 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, + skuCode, + quantity, + input.reason || null, + branchCode, + mainReturnCode, + input.returnedAt ? new Date(input.returnedAt) : new Date(), + ] + ); + + // 4) **立即生成补送单**(普通订单;只含退回行与数量) + const src = await client.query<{ + 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; + }>( + `SELECT 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 + FROM order_items oi + JOIN orders o ON o.order_code = oi.order_code + WHERE oi.order_code = $1 AND oi.sku_code = $2 AND COALESCE(oi.is_returned, false) = false + ORDER BY oi.created_at DESC + LIMIT 1`, + [ourOrderCode, skuCode] + ); + const line = src.rows[0]; + if (line) { + resupplyOrderCode = newCode('ORD_RS_'); + const price = Number(line.price) || 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, + Number((price * quantity).toFixed(2)), + quantity, + `主系统退回补送(原单 ${ourOrderCode},退回单 ${returnCode})`, + input.operatorId || null, + branchCode, + line.delivery_date, + ourOrderCode, + ] + ); + await client.query( + `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) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'UNASSIGNED', $9, $10, 0)`, + [ + resupplyOrderCode, + skuCode, + line.item_name || input.itemName || skuCode, + quantity, + line.unit || input.unit || null, + price, + line.category_code, + line.category_name, + line.processing_method, + line.processing_owner, + ] + ); + await client.query( + `UPDATE after_sale_returns SET resupply_order_code = $2, updated_at = NOW() WHERE return_code = $1`, + [returnCode, resupplyOrderCode] + ); + } + + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } + + // 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 }; +}