From e6d3f1ba8dc4f652190f8dbdb43f20099bfe541d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 3 Nov 2026 04:36:14 +0800 Subject: [PATCH] =?UTF-8?q?fix(external-print):=20=E6=9D=A5=E6=BA=90?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=8F=B7=E6=94=B9=E7=94=A8=E5=BA=97=E7=AE=A1?= =?UTF-8?q?=E5=AE=B6=E7=B3=BB=E7=BB=9F=E7=BC=96=E5=8F=B7=EF=BC=88LogicOrde?= =?UTF-8?q?rId=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题:外部打单平台订单的来源订单号 / 去重键取的是 PlatformOrderId(平台单号), 但平台单号并不唯一(同一平台单可拆成多条逻辑单),唯一标识是店管家的「系统编号」LogicOrderId。 例如 订单编号 261023-105376715090914 的系统编号是 695351624597601813。 - normalizeOrder:external_order_id / order_no 改用 LogicOrderId(缺失时回落平台单号), 平台单号以 platform_order_no 单独带出 - 订单表 extend_props 增加 platform_order_no,便于按店管家「订单编号」对账 - 订单详情抽屉新增「平台订单号」一行(有值才显示) - 新增 scripts/migrate-logic-order-id.js(npm run orders:migrate-logic-id): 把历史订单的来源订单号从平台单号迁移到系统编号,同时改写 orders / order_index / 各状态表 / order_status_items / 配送单,并补写 extend_props.platform_order_no;默认 dry-run - 修正 orders.external_order_id、order_index.parent_order_no、orderFields 的字段注释 已执行迁移 20 条(备份见会话 files/backup-before-logic-order-id-migration.json), 迁移后重新拉单 created=0 / updated=14,确认不会产生重复订单。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/lib/orderFields.js | 2 +- backend/app/lib/printPlatform/dgj.js | 11 +- backend/app/model/order.js | 2 +- backend/app/model/orderIndex.js | 2 +- backend/app/service/externalPrintOrder.js | 2 + backend/package.json | 1 + backend/scripts/migrate-logic-order-id.js | 136 ++++++++++++++++++++++ frontend/src/views/Order/StatusPanel.vue | 10 ++ 8 files changed, 161 insertions(+), 5 deletions(-) create mode 100644 backend/scripts/migrate-logic-order-id.js diff --git a/backend/app/lib/orderFields.js b/backend/app/lib/orderFields.js index b35d8b6..5e29eb4 100644 --- a/backend/app/lib/orderFields.js +++ b/backend/app/lib/orderFields.js @@ -31,7 +31,7 @@ function coreColumns(Sequelize, status) { const { BIGINT, STRING, JSON: JsonType } = Sequelize; return { order_no: { type: STRING(50), allowNull: false, comment: '订单号(老 order_no / delivery_order_code)' }, - parent_order_no: { type: STRING(50), comment: '来源订单号(上游/平台订单号)' }, + parent_order_no: { type: STRING(50), comment: '来源订单号(外部平台唯一单号;店管家为系统编号 LogicOrderId)' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' }, shop_id: { type: BIGINT.UNSIGNED, comment: '店铺ID' }, product_info: { type: JsonType, comment: '商品明细快照(JSON 数组;结构化明细见 order_status_items)' }, diff --git a/backend/app/lib/printPlatform/dgj.js b/backend/app/lib/printPlatform/dgj.js index b5030da..adb9d57 100644 --- a/backend/app/lib/printPlatform/dgj.js +++ b/backend/app/lib/printPlatform/dgj.js @@ -1087,13 +1087,20 @@ class DgjService extends PrintPlatformService { normalizeOrder(row) { const data = row || {}; const subOrders = Array.isArray(data.SubOrders) ? data.SubOrders : []; + // 店管家「系统编号」LogicOrderId 全局唯一,作为来源订单号与去重键; + // 「订单编号」PlatformOrderId 是平台单号,可能存在重复(如同一平台单被拆成多条逻辑单),不能作为唯一标识 + const logicOrderId = String(data.LogicOrderId || '').trim(); + const platformOrderId = String(data.PlatformOrderId || '').trim(); + const externalOrderId = logicOrderId || platformOrderId; return { - external_order_id: String(data.PlatformOrderId || data.LogicOrderId || ''), + external_order_id: externalOrderId, + // 平台单号保留下来展示/查询用(与外部环境对账时需要) + platform_order_no: platformOrderId || null, external_shop_id: data.ShopId == null ? '' : String(data.ShopId), external_shop_name: truncate(data.ShopName || data.AgentShopName || data.SelfShopName, 128), platform_type: truncate(data.PlatformType, 32), platform_status: truncate(data.ErpState || data.Status, 32), - order_no: String(data.PlatformOrderId || data.LogicOrderId || ''), + order_no: externalOrderId, total_amount: toNumber(data.TotalAmount), pay_amount: toNumber(data.SumTotalAmount || data.TotalAmount), // 店管家对收件人脱敏(明文仅打印组件可取):这里保留可用的省市区与脱敏明细地址 diff --git a/backend/app/model/order.js b/backend/app/model/order.js index 1a23884..70cdb66 100644 --- a/backend/app/model/order.js +++ b/backend/app/model/order.js @@ -15,7 +15,7 @@ module.exports = app => { principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, shop_id: { type: BIGINT.UNSIGNED, comment: '所属店铺ID,为空表示未关联店铺' }, external_print_account_id: { type: BIGINT.UNSIGNED, comment: '来源外部打单账号ID' }, - external_order_id: { type: STRING(64), comment: '平台订单号(店管家 PlatformOrderId)' }, + external_order_id: { type: STRING(64), comment: '平台订单唯一标识(店管家为系统编号 LogicOrderId,平台单号见 external_data)' }, platform_type: { type: STRING(32), comment: '平台类型:TouTiao/Taobao/Pinduoduo 等' }, platform_status: { type: STRING(32), comment: '平台侧订单状态' }, external_shop_id: { type: STRING(64), comment: '平台侧店铺ID(店管家 ShopId)' }, diff --git a/backend/app/model/orderIndex.js b/backend/app/model/orderIndex.js index 8803ba7..adab2d3 100644 --- a/backend/app/model/orderIndex.js +++ b/backend/app/model/orderIndex.js @@ -17,7 +17,7 @@ module.exports = app => { const OrderIndex = app.model.define(ORDER_INDEX_TABLE, { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键(订单全局唯一 ID)' }, order_no: { type: STRING(50), allowNull: false, comment: '订单号' }, - parent_order_no: { type: STRING(50), comment: '来源订单号(上游/平台订单号)' }, + parent_order_no: { type: STRING(50), comment: '来源订单号(外部平台唯一单号;店管家为系统编号 LogicOrderId)' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' }, current_table: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前所在表:pending/exception/outsourcing/delivery/history' }, current_status: { type: STRING(16), allowNull: false, defaultValue: 'pending', comment: '当前状态:pending 待审核 / exception 异常 / outsourcing 委外中 / delivery 配送 / history 历史' }, diff --git a/backend/app/service/externalPrintOrder.js b/backend/app/service/externalPrintOrder.js index 1750e0f..820e38b 100644 --- a/backend/app/service/externalPrintOrder.js +++ b/backend/app/service/externalPrintOrder.js @@ -375,6 +375,8 @@ class ExternalPrintOrderService extends Service { platform: account.platform.code, platform_shop_id: item.external_shop_id || null, platform_shop_name: item.external_shop_name || null, + // 平台单号(店管家「订单编号」)与来源订单号(「系统编号」)分开保存,便于对账 + platform_order_no: item.platform_order_no || null, receiver_masked: !!receiver.masked, }, }; diff --git a/backend/package.json b/backend/package.json index 7e2333f..f458991 100644 --- a/backend/package.json +++ b/backend/package.json @@ -20,6 +20,7 @@ "order-items:rebuild": "node scripts/rebuild-order-items.js", "order-index:repair": "node scripts/repair-order-index.js", "orders:cleanup-shipped": "node scripts/cleanup-shipped-pending-orders.js", + "orders:migrate-logic-id": "node scripts/migrate-logic-order-id.js", "deploy": "npm run deploy:prod", "deploy:prod": "npm --prefix ../tools run deploy --", "deploy:backend": "npm --prefix ../tools run deploy:backend --", diff --git a/backend/scripts/migrate-logic-order-id.js b/backend/scripts/migrate-logic-order-id.js new file mode 100644 index 0000000..5b027c7 --- /dev/null +++ b/backend/scripts/migrate-logic-order-id.js @@ -0,0 +1,136 @@ +'use strict'; + +/** + * 外部打单平台订单:把「来源订单号」从平台单号(PlatformOrderId)迁移到店管家系统编号(LogicOrderId)。 + * + * 背景:平台单号可能重复(同一平台单会拆成多条逻辑单),只有系统编号全局唯一, + * 拉单已改为用 LogicOrderId 作为 external_order_id / 来源订单号 / 去重键; + * 历史数据需要同步改写,否则下次拉单会当成新订单重复入库。 + * + * 改写范围(按 external_order_id 精确匹配,不影响手工单): + * - orders.order_no / external_order_id + * - order_index.order_no / parent_order_no + * - 各状态表的 order_no / parent_order_no / source_order_codes + * - order_status_items.source_order_code + * - order_deliveries / order_delivery_items 的来源单号 + * - extend_props.platform_order_no 补写平台单号,便于与店管家页面按「订单编号」对账 + * + * 用法: + * node scripts/migrate-logic-order-id.js # 只打印待迁移清单(dry-run) + * node scripts/migrate-logic-order-id.js --apply # 执行迁移 + */ +const mm = require('egg-mock'); +const { ORDER_STATUS } = require('../app/lib/orderStatus'); + +/** 需要改写的状态表 */ +const STATUS_TABLES = Object.values(ORDER_STATUS) + .filter(status => status !== ORDER_STATUS.HISTORY || true) + .map(status => `order_status_${status}`); + +(async () => { + const apply = process.argv.includes('--apply'); + const app = mm.app(); + await app.ready(); + const ctx = app.mockContext(); + + const orders = await ctx.model.Order.findAll({ + attributes: [ 'id', 'order_no', 'principal_id', 'external_order_id', 'external_data' ], + raw: true, + }); + + const plans = []; + for (const order of orders) { + const oldId = String(order.external_order_id || '').trim(); + if (!oldId) continue; + const raw = typeof order.external_data === 'string' ? safeJson(order.external_data) : (order.external_data || {}); + const logicId = String(raw.LogicOrderId || '').trim(); + if (!logicId || logicId === oldId) continue; + const prefix = String(order.order_no || '').includes('-') + ? String(order.order_no).slice(0, String(order.order_no).indexOf('-')) + : 'dgj'; + plans.push({ + id: Number(order.id), + principalId: Number(order.principal_id), + oldId, + logicId, + oldNo: String(order.order_no), + newNo: `${prefix}-${logicId}`, + }); + } + + for (const plan of plans) { + console.log(`${plan.oldNo} → ${plan.newNo}(来源订单号 ${plan.oldId} → ${plan.logicId})`); + } + console.log(`待迁移订单 ${plans.length} 条`); + + if (!plans.length || !apply) { + if (plans.length) console.log('[dry-run] 未写库,确认后加 --apply 执行'); + await app.close(); + process.exit(0); + } + + const transaction = await ctx.model.transaction(); + try { + for (const plan of plans) { + await ctx.model.query( + 'UPDATE `orders` SET order_no = ?, external_order_id = ? WHERE id = ?', + { replacements: [ plan.newNo, plan.logicId, plan.id ], transaction } + ); + + await ctx.model.query( + 'UPDATE `order_index` SET order_no = ?, parent_order_no = ? WHERE principal_id = ? AND (order_no = ? OR parent_order_no = ?)', + { replacements: [ plan.newNo, plan.logicId, plan.principalId, plan.oldNo, plan.oldId ], transaction } + ); + + for (const table of STATUS_TABLES) { + await ctx.model.query( + `UPDATE \`${table}\` + SET order_no = ?, parent_order_no = ?, + source_order_codes = REPLACE(source_order_codes, ?, ?), + extend_props = JSON_SET(COALESCE(extend_props, JSON_OBJECT()), '$.platform_order_no', ?) + WHERE principal_id = ? AND (order_no = ? OR parent_order_no = ?)`, + { replacements: [ plan.newNo, plan.logicId, plan.oldId, plan.logicId, plan.oldId, plan.principalId, plan.oldNo, plan.oldId ], transaction } + ); + } + + await ctx.model.query( + 'UPDATE `order_status_items` SET source_order_code = ? WHERE source_order_code = ? AND principal_id = ?', + { replacements: [ plan.logicId, plan.oldId, plan.principalId ], transaction } + ); + await ctx.model.query( + 'UPDATE `order_deliveries` SET source_order_codes = REPLACE(source_order_codes, ?, ?) WHERE source_order_codes LIKE ?', + { replacements: [ plan.oldId, plan.logicId, `%${plan.oldId}%` ], transaction } + ); + await ctx.model.query( + 'UPDATE `order_delivery_items` SET source_order_code = ? WHERE source_order_code = ?', + { replacements: [ plan.logicId, plan.oldId ], transaction } + ); + } + await transaction.commit(); + console.log(`已迁移 ${plans.length} 条订单的来源订单号为店管家系统编号`); + } catch (err) { + await transaction.rollback(); + console.error(`迁移失败,已回滚:${err.message}`); + await app.close(); + process.exit(1); + } + + await app.close(); + process.exit(0); +})().catch(err => { + console.error(err); + process.exit(1); +}); + +/** + * 宽松解析 JSON:脏数据解析失败时返回空对象(该行跳过迁移) + * @param {string} text JSON 文本 + * @return {Object} 解析结果 + */ +function safeJson(text) { + try { + return JSON.parse(text) || {}; + } catch { + return {}; + } +} diff --git a/frontend/src/views/Order/StatusPanel.vue b/frontend/src/views/Order/StatusPanel.vue index 5085e80..3680b13 100644 --- a/frontend/src/views/Order/StatusPanel.vue +++ b/frontend/src/views/Order/StatusPanel.vue @@ -547,6 +547,13 @@ function fmtNum(value: unknown): string { return Number.isFinite(num) ? String(Number(num.toFixed(2))) : String(value) } +/** 外部打单平台订单的平台单号(店管家「订单编号」,来源订单号用的是其「系统编号」) */ +function platformOrderNoOf(row: Record | null): string { + const props = row && (row.extend_props as Record | null) + const value = props && props.platform_order_no + return typeof value === 'string' ? value : '' +} + /** 行金额 = 数量 × 单价 */ function lineAmount(line: OrderItemLine): string { const qty = Number(line.plan_qty || 0) @@ -777,6 +784,9 @@ onMounted(async () => { {{ detailRow.order_no }} {{ detailRow.parent_order_no || '-' }} + + {{ platformOrderNoOf(detailRow) }} + {{ detailRow.status_label || ORDER_STAGE_META[detailRow.status]?.label }}