WMS_MAIN/database/migrations/20261115180000-refactor-wms-order-b2b.js
liufumingren 0a6e82e00a feat(order): B2B 订单作业链路(列表/转换/取消/波次排除/作业明细表重构)
- 新增 order.pendingOrder2b.list / order.deliveryOrder2b.list:复用待处理与配送列表条件,
  强制 is_b2b='Y'(fixedWhere 以 AND 追加,请求 where 无法覆盖),并带出 wms_order_b2b
  作业明细字段(total_box_count/pickup_plate_number/prep_remark/prep_duration_seconds/
  prep_at/is_picked_up/picked_up_at/created_at),无明细行时输出空值占位
- B2B 列表 where 支持按作业明细字段筛选:先按 warehouse_id + order_id 查副表取 order_id,
  再以 id IN (...) 回填;该筛选仅这两个接口开放,不影响普通订单列表
- 其余订单列表(order/reviewOrder/pendingOrder/outboundOrder/expectionOrder/entrustOrder/
  deliveryOrder/deliveryExpectionOrder/archiveOrder 及 waveStrategyFallbackOrderList)
  统一追加 (is_b2b IS NULL OR is_b2b = 'N'),B2B 订单不再混入普通列表
- order.convertToB2b 收紧准入:status!=cancel、step in [1,2,3]、未拣货、未复核、未锁定、
  未拦截、未 B2B(打印状态不限制);已在波次中的订单转换后在同一事务内从波次摘除
  (含库内抓取订单),波次存在进行中拣货任务则跳过
- order.cancelB2b 放开打印限制,作业明细由软删除改为物理删除
- 波次抓取全链路排除 B2B:补上自动加团 appendOrderToWave / countCandidateGroupOrders
  两处遗漏;抽出 detachOrdersFromWavesInTransaction 供 batchRemoveOrders 与转 B2B 复用
- wms_order_delivery 分表新增 is_b2b 列表索引(current/dispatch,等值列前置 + 排序列),
  由订单工厂结构漂移同步自动补建
- 迁移 20261115180000-refactor-wms-order-b2b:新增 prep_at;移除 is_print/updated_at/
  deleted_at/delivery_order_code/store_id;唯一键改 uk_warehouse_order(warehouse_id, order_id);
  迁移前清理历史软删除行与重复行(开发库与生产库均已执行)
- operation_log 兜底用 changeSummary 写入 message,修复转/取消 B2B 日志操作说明为空
- 同步 methods/system.json 与变更记录 0.3.351~0.3.360

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 01:30:08 +08:00

203 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* wms_order_b2b 精简重构。
*
* 变更内容:
* 1. 新增 prep_at(备货完成时间)。
* 2. 移除 is_print / updated_at / deleted_at / delivery_order_code / store_id:
* - is_print 随 B2B 面单打印能力下线而废弃;打印限制改由订单主表 print_status 决定(且已放开)。
* - updated_at / deleted_at 移除后作业明细不再软删除。
* - delivery_order_code / store_id 为快照冗余字段,关联读统一走 warehouse_id + order_id。
* 3. 唯一键 uk_order_id 改为 uk_warehouse_order(warehouse_id, order_id):
* 分表 id 按仓库各自发号,跨仓可能重叠,只按 order_id 唯一会误伤。
* 4. 取消 B2B 由软删除改为物理删除:迁移时先清掉历史软删除行,避免移除 deleted_at 后"复活"。
*
* 幂等:所有列/索引变更前都做存在性判断,重复执行安全。
* ⚠ 数据不可逆:删除的列与历史软删除行不会保留。
*/
const TABLE_NAME = 'wms_order_b2b';
/** 需要移除的列 */
const DROP_COLUMNS = [ 'is_print', 'updated_at', 'deleted_at', 'delivery_order_code', 'store_id' ];
/** 需要移除的索引 */
const DROP_INDEXES = [ 'uk_order_id', 'idx_warehouse_id', 'idx_store_id', 'idx_delivery_order_code', 'idx_is_print', 'idx_deleted_at' ];
/**
* 判断索引是否存在。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} indexName 索引名。
* @return {Promise<boolean>} 是否存在。
*/
async function indexExists(queryInterface, indexName) {
const indexes = await queryInterface.showIndex(TABLE_NAME);
return (Array.isArray(indexes) ? indexes : []).some(index => {
const name = String(index && (index.name || index.Key_name || index.key_name) || '');
return name.toLowerCase() === String(indexName).toLowerCase();
});
}
/**
* 安全删除索引(不存在则跳过)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} indexName 索引名。
* @param {Array<Object>} log 执行日志。
* @return {Promise<void>} 无返回值。
*/
async function dropIndexIfExists(queryInterface, indexName, log) {
if (!(await indexExists(queryInterface, indexName))) {
log.push({ action: 'skip-drop-index', indexName, reason: 'not-exists' });
return;
}
await queryInterface.removeIndex(TABLE_NAME, indexName);
log.push({ action: 'drop-index', indexName });
}
/**
* 安全删除列(不存在则跳过)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {string} columnName 列名。
* @param {Object} columns describeTable 结果。
* @param {Array<Object>} log 执行日志。
* @return {Promise<void>} 无返回值。
*/
async function dropColumnIfExists(queryInterface, columnName, columns, log) {
if (!Object.prototype.hasOwnProperty.call(columns, columnName)) {
log.push({ action: 'skip-drop-column', columnName, reason: 'not-exists' });
return;
}
await queryInterface.removeColumn(TABLE_NAME, columnName);
log.push({ action: 'drop-column', columnName });
}
module.exports = {
/**
* 执行迁移。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Object} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async up(queryInterface, Sequelize) {
const { DATE } = Sequelize;
const log = [];
const query = queryInterface.sequelize;
let columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns || Object.keys(columns).length === 0) {
throw new Error(`表 ${TABLE_NAME} 不存在,无法执行重构迁移`);
}
// 1. 历史软删除行清理(deleted_at 即将被移除,不清掉会变成"有效行")
if (Object.prototype.hasOwnProperty.call(columns, 'deleted_at')) {
const [ deletedRows ] = await query.query(`DELETE FROM ${TABLE_NAME} WHERE deleted_at IS NOT NULL`);
log.push({ action: 'delete-soft-deleted-rows', affected: Number(deletedRows && deletedRows.affectedRows || 0) });
}
// 2. 同仓同单重复行清理(保留 id 最大的一行),为新唯一键让路
if (Object.prototype.hasOwnProperty.call(columns, 'warehouse_id')
&& Object.prototype.hasOwnProperty.call(columns, 'order_id')) {
const [ dedupeRows ] = await query.query(`
DELETE t FROM ${TABLE_NAME} t
INNER JOIN ${TABLE_NAME} keep
ON keep.warehouse_id = t.warehouse_id
AND keep.order_id = t.order_id
AND keep.id > t.id
`);
log.push({ action: 'delete-duplicate-rows', affected: Number(dedupeRows && dedupeRows.affectedRows || 0) });
}
// 3. 新增 prep_at
if (!Object.prototype.hasOwnProperty.call(columns, 'prep_at')) {
await queryInterface.addColumn(TABLE_NAME, 'prep_at', {
type: DATE,
allowNull: true,
comment: '备货完成时间',
});
log.push({ action: 'add-column', columnName: 'prep_at' });
} else {
log.push({ action: 'skip-add-column', columnName: 'prep_at', reason: 'exists' });
}
// 4. 删除废弃索引(含旧唯一键与冗余 warehouse_id 索引)
for (const indexName of DROP_INDEXES) {
await dropIndexIfExists(queryInterface, indexName, log);
}
// 5. 建立新的复合唯一键
if (!(await indexExists(queryInterface, 'uk_warehouse_order'))) {
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'order_id' ], {
name: 'uk_warehouse_order',
unique: true,
});
log.push({ action: 'add-index', indexName: 'uk_warehouse_order' });
} else {
log.push({ action: 'skip-add-index', indexName: 'uk_warehouse_order', reason: 'exists' });
}
// 6. 删除废弃列
columns = await queryInterface.describeTable(TABLE_NAME);
for (const columnName of DROP_COLUMNS) {
await dropColumnIfExists(queryInterface, columnName, columns, log);
}
console.log('[20261115180000-refactor-wms-order-b2b] up results:', JSON.stringify(log));
},
/**
* 回滚迁移:恢复被移除的列与索引(历史数据不可恢复)。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {Object} Sequelize Sequelize 类型集合。
* @return {Promise<void>} 无返回值。
*/
async down(queryInterface, Sequelize) {
const { DATE, ENUM, STRING, BIGINT } = Sequelize;
const log = [];
let columns = await queryInterface.describeTable(TABLE_NAME);
await dropIndexIfExists(queryInterface, 'uk_warehouse_order', log);
const restoreColumns = [
[ 'store_id', { type: BIGINT(20).UNSIGNED, allowNull: true, comment: '货主ID' }],
[ 'delivery_order_code', { type: STRING(50), allowNull: true, comment: '发货单号快照' }],
[ 'is_print', { type: ENUM('Y', 'N'), allowNull: false, defaultValue: 'N', comment: '是否打印:Y=已打印 N=未打印' }],
[ 'updated_at', { type: DATE, allowNull: true, comment: '更新时间' }],
[ 'deleted_at', { type: DATE, allowNull: true, comment: '软删除时间' }],
];
for (const [ columnName, definition ] of restoreColumns) {
if (Object.prototype.hasOwnProperty.call(columns, columnName)) {
log.push({ action: 'skip-add-column', columnName, reason: 'exists' });
continue;
}
await queryInterface.addColumn(TABLE_NAME, columnName, definition);
log.push({ action: 'add-column', columnName });
}
const restoreIndexes = [
[ 'uk_order_id', [ 'order_id' ], true ],
[ 'idx_warehouse_id', [ 'warehouse_id' ], false ],
[ 'idx_store_id', [ 'store_id' ], false ],
[ 'idx_delivery_order_code', [ 'delivery_order_code' ], false ],
[ 'idx_is_print', [ 'is_print' ], false ],
[ 'idx_deleted_at', [ 'deleted_at' ], false ],
];
for (const [ indexName, fields, unique ] of restoreIndexes) {
if (await indexExists(queryInterface, indexName)) {
log.push({ action: 'skip-add-index', indexName, reason: 'exists' });
continue;
}
await queryInterface.addIndex(TABLE_NAME, fields, { name: indexName, unique });
log.push({ action: 'add-index', indexName });
}
columns = await queryInterface.describeTable(TABLE_NAME);
await dropColumnIfExists(queryInterface, 'prep_at', columns, log);
console.log('[20261115180000-refactor-wms-order-b2b] down results:', JSON.stringify(log));
},
};