'use strict'; /** * wms_wave_batch.wave_no 唯一化。 * * 背景:并发创建波次时「查当日最大序号+1」存在竞态,可能产生 wave_no 相同的多行 * (不同 wave_id、不同订单组),导致两组订单共用一个波次号。 * * 本迁移: * 1. 修复存量重复波次号:同一 wave_no 保留最早(wave_id 最小)一行, * 其余行按「前缀+日期+下一个空闲序号」重新编号,并同步引用方数据 * (订单表四个车道、拣货任务波次关联表、打印记录、打包任务)的 wave_no; * 2. 移除冗余的非唯一索引 idx_wave_no(若存在); * 3. 新增唯一索引 uniq_wave_no(若已人工添加则跳过,保证幂等)。 */ const TABLE_NAME = 'wms_wave_batch'; /** * 归一化索引字段名(Sequelize 各版本返回 string 或 { attribute } 对象)。 * * @param {Array} fields 索引字段列表。 * @return {Array} 字段名字符串列表。 */ function normalizeIndexFields(fields) { return (Array.isArray(fields) ? fields : []) .map(field => String( typeof field === 'string' ? field : (field && (field.attribute || field.name || '')) ).trim()) .filter(Boolean); } /** * 判断索引列表是否包含指定名称的非唯一/唯一 wave_no 索引。 * * @param {Array} indexes showIndex 结果。 * @param {string} indexName 索引名称。 * @param {boolean} unique 是否唯一索引。 * @return {boolean} 是否存在。 */ function hasWaveNoIndex(indexes, indexName, unique) { return (Array.isArray(indexes) ? indexes : []).some(index => { if (!index || index.name !== indexName) { return false; } const fields = normalizeIndexFields(index.fields); return fields.length === 1 && fields[0] === 'wave_no' && Boolean(index.unique) === unique; }); } /** * 查询存量重复的波次号。 * * @param {Object} queryInterface Sequelize 查询接口。 * @return {Promise>} 重复波次号列表。 */ async function fetchDuplicateWaveNos(queryInterface) { return await queryInterface.sequelize.query( `SELECT wave_no, COUNT(*) AS cnt FROM ${TABLE_NAME} GROUP BY wave_no HAVING COUNT(*) > 1 ORDER BY wave_no ASC`, { type: queryInterface.sequelize.QueryTypes.SELECT } ); } /** * 计算「前缀+日期」片段下下一个空闲波次号。 * * @param {Object} queryInterface Sequelize 查询接口。 * @param {string} prefixDate 波次号前缀+日期片段(如 B20260822)。 * @return {Promise} 下一个空闲波次号。 */ async function buildNextFreeWaveNo(queryInterface, prefixDate) { const startPos = String(prefixDate).length + 1; const rows = await queryInterface.sequelize.query( `SELECT IFNULL(MAX(CAST(SUBSTRING(wave_no, :startPos) AS UNSIGNED)), 0) + 1 AS seq FROM ${TABLE_NAME} WHERE wave_no LIKE :pattern`, { replacements: { startPos, pattern: `${prefixDate}%` }, type: queryInterface.sequelize.QueryTypes.SELECT, } ); const seq = Number(rows && rows[0] && rows[0].seq || 1); return `${prefixDate}${String(seq).padStart(5, '0')}`; } /** * 判断波次号是否已存在。 * * @param {Object} queryInterface Sequelize 查询接口。 * @param {string} waveNo 波次号。 * @return {Promise} 是否已存在。 */ async function waveNoExists(queryInterface, waveNo) { const rows = await queryInterface.sequelize.query( `SELECT wave_id FROM ${TABLE_NAME} WHERE wave_no = :waveNo LIMIT 1`, { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } ); return Array.isArray(rows) && rows.length > 0; } /** * 更新指定表内该波次的 wave_no(表不存在时跳过)。 * * @param {Object} queryInterface Sequelize 查询接口。 * @param {string} tableName 表名。 * @param {number} warehouseId 仓库ID。 * @param {number} waveId 波次ID。 * @param {string} waveNo 新波次号。 * @return {Promise} 无返回值。 */ async function updateTableWaveNo(queryInterface, tableName, warehouseId, waveId, waveNo) { const checkRows = await queryInterface.sequelize.query( `SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :tableName`, { replacements: { tableName }, type: queryInterface.sequelize.QueryTypes.SELECT } ); if (!Array.isArray(checkRows) || checkRows.length === 0) { return; } await queryInterface.sequelize.query( `UPDATE \`${tableName}\` SET wave_no = :waveNo WHERE warehouse_id = :warehouseId AND wave_id = :waveId AND wave_no <> :waveNo`, { replacements: { waveNo, warehouseId, waveId } } ); } /** * 同步某波次被重编号后所有引用方表中的 wave_no。 * * @param {Object} queryInterface Sequelize 查询接口。 * @param {number} warehouseId 仓库ID。 * @param {number} waveId 波次ID。 * @param {string} waveNo 新波次号。 * @return {Promise} 无返回值。 */ async function syncWaveNoReferences(queryInterface, warehouseId, waveId, waveNo) { if (Number.isInteger(warehouseId) && warehouseId > 0) { await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}`, warehouseId, waveId, waveNo); await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_history`, warehouseId, waveId, waveNo); await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_dispatch`, warehouseId, waveId, waveNo); await updateTableWaveNo(queryInterface, `wms_order_delivery_${warehouseId}_outsourced`, warehouseId, waveId, waveNo); } await updateTableWaveNo(queryInterface, 'wms_wave_pick_task_wave', warehouseId, waveId, waveNo); await updateTableWaveNo(queryInterface, 'wms_print_record', warehouseId, waveId, waveNo); await updateTableWaveNo(queryInterface, 'wms_pack_task', warehouseId, waveId, waveNo); } module.exports = { async up(queryInterface) { // 1. 修复存量重复波次号:同一 wave_no 保留最早一行,其余重新编号 const duplicateRows = await fetchDuplicateWaveNos(queryInterface); for (const dup of (Array.isArray(duplicateRows) ? duplicateRows : [])) { const waveNo = String(dup && dup.wave_no || '').trim(); if (!waveNo) { continue; } const rows = await queryInterface.sequelize.query( `SELECT wave_id, warehouse_id FROM ${TABLE_NAME} WHERE wave_no = :waveNo ORDER BY wave_id ASC`, { replacements: { waveNo }, type: queryInterface.sequelize.QueryTypes.SELECT } ); if (!Array.isArray(rows) || rows.length <= 1) { continue; } const prefixDate = waveNo.replace(/\d+$/, ''); if (!prefixDate) { throw new Error(`波次号 ${waveNo} 无字母前缀,无法自动重编号,请人工处理`); } // 保留最早(wave_id 最小)的一行,其余行重新编号 for (let index = 1; index < rows.length; index += 1) { const row = rows[index]; const waveId = Number(row && row.wave_id || 0); const warehouseId = Number(row && row.warehouse_id || 0); if (!Number.isInteger(waveId) || waveId <= 0) { continue; } let nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); let guard = 0; while (guard < 100 && await waveNoExists(queryInterface, nextWaveNo)) { nextWaveNo = await buildNextFreeWaveNo(queryInterface, prefixDate); guard += 1; } if (guard >= 100) { throw new Error(`波次号 ${waveNo} 重新编号失败:无法找到空闲编号`); } await queryInterface.sequelize.query( `UPDATE ${TABLE_NAME} SET wave_no = :nextWaveNo, update_time = NOW() WHERE wave_id = :waveId`, { replacements: { nextWaveNo, waveId } } ); // 同步引用方数据 await syncWaveNoReferences(queryInterface, warehouseId, waveId, nextWaveNo); } } // 2. 二次校验:修复后不应再有重复波次号 const residualRows = await fetchDuplicateWaveNos(queryInterface); if ((Array.isArray(residualRows) ? residualRows : []).length > 0) { const residual = residualRows.map(row => String(row && row.wave_no || '').trim()).filter(Boolean); throw new Error(`wms_wave_batch 修复后仍存在重复波次号: ${residual.join(', ')}`); } // 3. 读取索引现状 const indexes = await queryInterface.showIndex(TABLE_NAME); // 4. 移除冗余非唯一索引(若存在) if (hasWaveNoIndex(indexes, 'idx_wave_no', false)) { await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_no'); } // 5. 新增唯一索引(若已人工添加则跳过,保证幂等) if (!hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { unique: true, name: 'uniq_wave_no', }); } }, async down(queryInterface) { const indexes = await queryInterface.showIndex(TABLE_NAME); // 回滚:移除唯一索引 if (hasWaveNoIndex(indexes, 'uniq_wave_no', true)) { await queryInterface.removeIndex(TABLE_NAME, 'uniq_wave_no'); } // 回滚:恢复非唯一索引(若不存在) if (!hasWaveNoIndex(indexes, 'idx_wave_no', false)) { await queryInterface.addIndex(TABLE_NAME, [ 'wave_no' ], { unique: false, name: 'idx_wave_no', }); } }, };