'use strict'; /** * 订单序列号(SN)关联表 order_sn_codes * * 背景:WMS 回传发货确认(deliveryorder.confirm)时,明细行可能带 `snList`(序列号列表)。 * OMS 原先把确认报文整体存进订单的 `wms_push_result.confirm`(JSON,无法按 SN 反查), * 现改为**另存关联表**:一行一个 SN,带行号 / 商品 / 包裹 / 运单号,供订单查询按 SN 反查订单。 * * 归属口径: * - `order_id` = order_index.id(订单全局唯一 ID;订单在状态表之间流转时不变,因此转表不用搬 SN) * - `principal_id` 冗余主体,查询按「主体 + SN」走索引 * - 一条 SN 可能在同一订单里重复回传(WMS 重推),由唯一键 `uk_osc_order_sn` 兜底去重 * * 幂等:showAllTables 判断表是否存在。 */ module.exports = { async up(queryInterface, Sequelize) { const tables = await queryInterface.showAllTables(); const exists = tables .map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME))) .includes('order_sn_codes'); if (exists) return; const { BIGINT, STRING, DATE } = Sequelize; await queryInterface.createTable('order_sn_codes', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID(主体隔离)' }, order_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '订单ID(order_index.id,全局唯一;流转状态表不变)' }, order_no: { type: STRING(50), allowNull: true, comment: '订单号(冗余,便于排查 / 导出)' }, order_line_no: { type: STRING(20), allowNull: true, comment: '回传明细行号(orderLineNo)' }, item_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '商品ID(itemId)' }, item_code: { type: STRING(100), allowNull: true, comment: '商品编码(itemCode)' }, item_name: { type: STRING(255), allowNull: true, comment: '商品名称(itemName)' }, package_code: { type: STRING(50), allowNull: true, comment: '包裹号(packages.package.packageCode)' }, express_code: { type: STRING(50), allowNull: true, comment: '运单号(packages.package.expressCode)' }, warehouse_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '仓库ID(app_key 定位到的仓库)' }, sn_code: { type: STRING(255), allowNull: false, comment: '序列号(SN 原值,去空白;反查订单用)' }, source: { type: STRING(20), allowNull: false, defaultValue: 'wms', comment: '来源:wms=仓库回传(预留手工补录)' }, created_at: { type: DATE, allowNull: true, comment: '创建时间' }, updated_at: { type: DATE, allowNull: true, comment: '更新时间' }, }, { comment: '订单序列号(SN)关联表(WMS 发货确认回传的 snList)', charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', }); // 反查订单:principal_id + sn_code(订单列表按 SN 多值精确匹配) await queryInterface.addIndex('order_sn_codes', [ 'principal_id', 'sn_code' ], { name: 'idx_osc_principal_sn', }); await queryInterface.addIndex('order_sn_codes', [ 'order_id' ], { name: 'idx_osc_order', }); // 同一订单重复回传同一 SN 时由唯一键兜底去重(代码层已先过滤,这里防并发) await queryInterface.addIndex('order_sn_codes', [ 'principal_id', 'order_id', 'sn_code' ], { name: 'uk_osc_order_sn', unique: true, }); }, async down(queryInterface) { const tables = await queryInterface.showAllTables(); const exists = tables .map(t => (typeof t === 'string' ? t : (t.tableName || t.TABLE_NAME))) .includes('order_sn_codes'); if (exists) await queryInterface.dropTable('order_sn_codes'); }, };