'use strict'; /** * 存量订单回填 has_sn_item(是否含序列号管理商品)。 * * 口径:订单任一明细的 stock_warehouse.is_sn_mgmt='Y' → has_sn_item='Y',否则保持 'N'。 * * 覆盖范围:基表 wms_order_delivery 与全部仓库分表,按分表后缀关联对应订单明细表: * - wms_order_delivery_{wh} → wms_order_items_{wh} * - wms_order_delivery_{wh}_history → wms_order_items_{wh}_history * - wms_order_delivery_{wh}_dispatch → wms_order_items_{wh}_dispatch * - wms_order_delivery_{wh}_outsourced → wms_order_items_{wh}(外仓明细与常用表共用) * * 幂等:先把 Y 重置为 N,再按明细回填 Y,重复执行结果一致。 */ const BASE_TABLE = 'wms_order_delivery'; const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/; /** * 列举库内全部订单分表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 分表名列表。 */ async function listOrderShards(queryInterface) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' ' + 'ORDER BY TABLE_NAME' ); return (rows || []) .map(row => String(row.tableName || row.TABLE_NAME || '')) .filter(name => SHARD_PATTERN.test(name)); } /** * 判断表是否存在。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @return {Promise} 是否存在。 */ async function tableExists(queryInterface, tableName) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName LIMIT 1', { replacements: { tableName } } ); return Boolean(rows && rows.length > 0); } /** * 判断表是否包含指定列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @param {string} tableName 表名。 * @param {string} columnName 列名。 * @return {Promise} 是否存在。 */ async function columnExists(queryInterface, tableName, columnName) { const [ rows ] = await queryInterface.sequelize.query( 'SELECT COLUMN_NAME AS columnName FROM INFORMATION_SCHEMA.COLUMNS ' + 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName AND COLUMN_NAME = :columnName LIMIT 1', { replacements: { tableName, columnName } } ); return Boolean(rows && rows.length > 0); } /** * 由订单表名推导对应订单明细表名。 * @param {string} orderTable 订单表名。 * @return {string|null} 明细表名,无法推导时返回 null。 */ function resolveItemsTable(orderTable) { if (orderTable === BASE_TABLE) { return 'wms_order_items'; } const matched = SHARD_PATTERN.exec(orderTable); if (!matched) { return null; } const warehouseId = matched[1]; const suffix = matched[2] || ''; if (suffix === 'history') { return `wms_order_items_${warehouseId}_history`; } if (suffix === 'dispatch') { return `wms_order_items_${warehouseId}_dispatch`; } return `wms_order_items_${warehouseId}`; } /** * 提取受影响行数。 * @param {*} updateResult query 返回结果。 * @return {number} 受影响行数。 */ function extractAffectedRows(updateResult) { if (Array.isArray(updateResult)) { const meta = updateResult[1]; return Number(meta && (meta.affectedRows || meta.affectedCount || meta.rowCount) || 0); } if (updateResult && typeof updateResult === 'object') { return Number(updateResult.affectedRows || updateResult.affectedCount || updateResult.rowCount || 0); } return 0; } module.exports = { /** * 执行迁移:按订单明细回填 has_sn_item。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async up(queryInterface) { const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; const results = []; for (const tableName of tables) { if (!await tableExists(queryInterface, tableName)) { results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); continue; } const itemsTable = resolveItemsTable(tableName); if (!itemsTable || !await tableExists(queryInterface, itemsTable)) { results.push({ tableName, action: 'skip', reason: `items-table-missing:${itemsTable || ''}` }); continue; } // 兼容旧版基表:wms_order_items(无 stock_id / order_id 的历史结构)无法参与回填 if (!await columnExists(queryInterface, itemsTable, 'order_id') || !await columnExists(queryInterface, itemsTable, 'stock_id')) { results.push({ tableName, action: 'skip', reason: `items-table-unsupported:${itemsTable}` }); continue; } const resetResult = await queryInterface.sequelize.query(` UPDATE \`${tableName}\` SET has_sn_item = 'N' WHERE has_sn_item = 'Y' `); const updateResult = await queryInterface.sequelize.query(` UPDATE \`${tableName}\` o INNER JOIN ( SELECT DISTINCT oi.order_id FROM \`${itemsTable}\` oi INNER JOIN wms_stock_warehouse sw ON sw.id = oi.stock_id AND sw.is_sn_mgmt = 'Y' ) t ON t.order_id = o.id SET o.has_sn_item = 'Y' `); results.push({ tableName, itemsTable, resetRows: extractAffectedRows(resetResult), affectedRows: extractAffectedRows(updateResult), }); } console.log('[20261113151000-backfill-order-has-sn-item] up results:', JSON.stringify(results)); }, /** * 回滚迁移:全部置回 'N'。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 * @return {Promise} 无返回值。 */ async down(queryInterface) { const tables = [ BASE_TABLE, ...await listOrderShards(queryInterface) ]; const results = []; for (const tableName of tables) { if (!await tableExists(queryInterface, tableName)) { results.push({ tableName, action: 'skip', reason: 'order-table-missing' }); continue; } const updateResult = await queryInterface.sequelize.query(` UPDATE \`${tableName}\` SET has_sn_item = 'N' WHERE has_sn_item = 'Y' `); results.push({ tableName, affectedRows: extractAffectedRows(updateResult) }); } console.log('[20261113151000-backfill-order-has-sn-item] down results:', JSON.stringify(results)); }, };