WMS_MAIN/app/model/order_delivery_factory.js

1239 lines
44 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.

// app/model/wms_order_delivery_factory.js
'use strict';
const {
ensureShardWarehouseId,
clearShardWarehouseValidationCache,
} = require('../lib/warehouse_shard_guard');
const {
normalizeManagedType,
isOutsourcedType,
normalizeIndexDefinition,
parseNumericConstraint,
buildTableAttributes,
buildTableName: buildManagedTableName,
buildTableComment,
buildTableOptions,
buildIndexOptions,
buildColumnLine,
buildColumnLines,
buildIndexLines,
isColumnDefinitionDifferent,
parseManagedTableName,
AUTO_INCREMENT_SAFE_MARGIN,
} = require('./order_delivery_table_schema');
const LANES = Object.freeze({
M4: 'm4',
M5: 'm5',
});
/**
* 判断两个索引定义是否存在结构差异。
* @param {Object} expectedIndex 预期索引定义。
* @param {Object} actualIndex 实际索引定义。
* @return {boolean} 是否存在结构差异。
*/
function isIndexDefinitionDifferent(expectedIndex, actualIndex) {
const normalizedExpected = normalizeIndexDefinition(expectedIndex);
const normalizedActual = normalizeIndexDefinition(actualIndex);
if (!normalizedActual.name) {
return true;
}
const actualUniqueDefined = Object.prototype.hasOwnProperty.call(actualIndex || {}, 'unique')
|| Object.prototype.hasOwnProperty.call(actualIndex || {}, 'Unique')
|| Object.prototype.hasOwnProperty.call(actualIndex || {}, 'nonUnique');
if (actualUniqueDefined && normalizedExpected.unique !== normalizedActual.unique) {
return true;
}
if (!Array.isArray(actualIndex && actualIndex.fields) || !actualIndex.fields.length) {
return false;
}
if (normalizedExpected.fields.length !== normalizedActual.fields.length) {
return true;
}
for (let index = 0; index < normalizedExpected.fields.length; index += 1) {
const expectedField = normalizedExpected.fields[index];
const actualField = normalizedActual.fields[index];
if (!expectedField.attribute || !actualField.attribute) {
return true;
}
if (expectedField.attribute !== actualField.attribute) {
return true;
}
if (Object.prototype.hasOwnProperty.call(expectedField, 'length') && expectedField.length !== actualField.length) {
return true;
}
}
return false;
}
/**
* 转义 SQL 标识符。
* @param {string} identifier 标识符。
* @return {string} 转义后的标识符。
*/
function quoteIdentifier(identifier) {
return `\`${String(identifier).replace(/`/g, '``')}\``;
}
/**
* 构造表数据约束违规错误。
* @param {string} tableName 表名。
* @param {string} columnName 列名。
* @param {string} violationType 违规类型。
* @param {string} [detail] 违规详情。
* @return {Error} 错误对象。
*/
function buildManagedTableConstraintError(tableName, columnName, violationType, detail = '') {
const suffix = detail ? `, detail=${detail}` : '';
const error = new Error(`数据不满足约束: table=${tableName}, column=${columnName}, violation=${violationType}${suffix}`);
error.code = 'ORDER_DELIVERY_TABLE_CONSTRAINT_VIOLATION';
error.tableName = tableName;
error.columnName = columnName;
error.violationType = violationType;
return error;
}
module.exports = app => {
class OrderDeliveryFactory {
constructor() {
this.modelCache = new Map();
this.inflightInitCache = new Map();
this.locationTableReady = new Map();
this.app = app;
}
/**
* 复用并发中的模型初始化,避免重复执行建模与结构自检。
* @param {string} lockKey 并发锁键。
* @param {Function} initializer 初始化函数。
* @return {Promise<Object>} 模型实例。
*/
async runModelInitializer(lockKey, initializer) {
if (this.inflightInitCache.has(lockKey)) {
return await this.inflightInitCache.get(lockKey);
}
const initPromise = (async () => {
try {
return await initializer();
} finally {
this.inflightInitCache.delete(lockKey);
}
})();
this.inflightInitCache.set(lockKey, initPromise);
return await initPromise;
}
/**
* 获取配送域车道常量。
* @return {Object} 车道常量。
*/
get LANES() {
return LANES;
}
/**
* 判断是否为配送域模型。
* @param {string} type 模型类型。
* @return {boolean} 是否为配送域模型。
*/
isDispatchType(type) {
return type === 'dispatch';
}
/**
* 解析模型类型。
* @param {string} type 模型类型。
* @return {string} 解析后的模型类型。
*/
resolveModelType(type) {
return normalizeManagedType(type);
}
isOutsourcedModel(type) {
return isOutsourcedType(type);
}
/**
* 获取当前表模型
* @param {number} warehouseId 仓库ID
* @return {Promise<Object>} 当前表模型
*/
async getCurrentModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'current');
}
/**
* 获取历史表模型
* @param {number} warehouseId 仓库ID
* @return {Promise<Object>} 历史表模型
*/
async getHistoryModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'history');
}
/**
* 获取配送域模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getDispatchModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'dispatch');
}
async getOutsourcedModel(warehouseId) {
return await this.getOrCreateModel(warehouseId, 'outsourced');
}
/**
* 获取配送正常模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getM4Model(warehouseId) {
return await this.getDispatchModel(warehouseId);
}
/**
* 获取配送异常模型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<Object>} 配送域模型。
*/
async getM5Model(warehouseId) {
return await this.getDispatchModel(warehouseId);
}
/**
* 根据表名直接获取模型
* @param {string} tableName 表名
* @return {Promise<Object>} 动态模型
*/
async getModelByTableName(tableName) {
const cacheKey = `table_${tableName}`;
const lockKey = `init_table_${tableName}`;
if (this.modelCache.has(cacheKey)) {
return this.modelCache.get(cacheKey);
}
return await this.runModelInitializer(lockKey, async () => {
if (this.modelCache.has(cacheKey)) {
return this.modelCache.get(cacheKey);
}
try {
const parsed = parseManagedTableName(tableName);
if (!parsed) {
throw new Error(`表 ${tableName} 不是订单工厂管理表`);
}
const tableExists = await this.checkTableExists(tableName);
if (!tableExists) {
throw new Error(`表 ${tableName} 不存在`);
}
const DynamicModel = this.buildManagedModel(parsed.warehouseId, parsed.type, tableName);
await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId, DynamicModel);
this.modelCache.set(cacheKey, DynamicModel);
return DynamicModel;
} catch (error) {
this.app.logger.error(`获取模型失败 ${tableName}:`, error);
throw error;
}
});
}
/**
* 获取或创建模型
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<Object>} 动态模型
*/
async getOrCreateModel(warehouseId, type) {
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
const modelType = this.resolveModelType(type);
const tableName = this.generateTableName(warehouseIdStr, modelType);
const cacheKey = `${warehouseIdStr}_${modelType}`;
const tableCacheKey = `table_${tableName}`;
// 与 getModelByTableName 统一使用“物理表名锁”,避免不同入口并发重复初始化同一张表
const lockKey = `init_table_${tableName}`;
// 检查缓存
if (this.modelCache.has(cacheKey)) {
return this.modelCache.get(cacheKey);
}
return await this.runModelInitializer(lockKey, async () => {
if (this.modelCache.has(cacheKey)) {
return this.modelCache.get(cacheKey);
}
try {
const DynamicModel = this.buildManagedModel(warehouseIdStr, modelType, tableName);
await this.ensureManagedTableSchema(tableName, modelType, warehouseIdStr, DynamicModel);
// 设置关联关系
this.setupAssociations(DynamicModel, warehouseIdStr, modelType);
// 缓存模型(按业务键和表名键双写,避免跨入口重复初始化)
this.modelCache.set(cacheKey, DynamicModel);
this.modelCache.set(tableCacheKey, DynamicModel);
this.app.logger.info(`创建动态模型成功: ${tableName}`);
return DynamicModel;
} catch (error) {
this.app.logger.error(`创建动态模型失败 ${tableName}:`, error);
throw error;
}
});
}
/**
* 获取模型配置选项
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Object} Sequelize 模型配置
*/
getModelOptions(warehouseId, type) {
return buildTableOptions(this.app, warehouseId, type);
}
/**
* 构建动态模型。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @param {string} tableName 表名。
* @return {Object} 动态模型。
*/
buildManagedModel(warehouseId, type, tableName) {
const modelType = this.resolveModelType(type);
const attributes = this.getTableAttributes(modelType);
const modelOptions = this.getModelOptions(warehouseId, modelType);
return this.app.model.define(tableName, attributes, modelOptions);
}
/**
* 获取订单工厂管理的属性定义。
* @param {string} type 模型类型。
* @return {Object} 属性定义。
*/
getTableAttributes(type) {
return buildTableAttributes(this.app, type);
}
/**
* 获取索引配置
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Array<Object>} 索引配置
*/
getIndexes(warehouseId, type) {
return buildIndexOptions(warehouseId, type);
}
/**
* 获取当前表通用列定义行。
*
* @param {string} type 模型类型
* @return {Array<string>} 当前表列定义行
*/
getCurrentTableColumnLines(type = 'current') {
return buildColumnLines(this.app, type);
}
/**
* 获取当前表通用索引定义行。
*
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Array<string>} 当前表索引定义行
*/
getCurrentTableIndexLines(warehouseId, type = 'current') {
return buildIndexLines(warehouseId, type);
}
/**
* 获取配送域物理表名。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<string>} 配送域物理表名。
*/
async getDispatchTableName(warehouseId) {
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
return `wms_order_delivery_${warehouseIdStr}_dispatch`;
}
/**
* 获取配送域表列定义行。
* @return {Array<string>} 配送域表列定义行。
*/
getDispatchTableColumnLines() {
return buildColumnLines(this.app, 'dispatch');
}
/**
* 获取配送域表索引定义行。
* @param {string} warehouseIdStr 仓库ID字符串。
* @return {Array<string>} 配送域表索引定义行。
*/
getDispatchTableIndexLines(warehouseIdStr) {
return buildIndexLines(warehouseIdStr, 'dispatch');
}
/**
* 获取配送域索引配置。
* @param {string} warehouseIdStr 仓库ID字符串。
* @return {Array<Object>} Sequelize 索引配置。
*/
getDispatchTableIndexOptions(warehouseIdStr) {
return buildIndexOptions(warehouseIdStr, 'dispatch');
}
/**
* 获取配送域属性定义。
* @return {Object} 配送域属性定义。
*/
getDispatchAttributes() {
return this.getTableAttributes('dispatch');
}
buildDispatchAttributes() {
return this.getDispatchAttributes();
}
/**
* 设置关联关系
* @param {Object} DynamicModel 动态模型
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<void>}
*/
async setupAssociations(DynamicModel, warehouseId, type) {
try {
// 配送域不挂商品明细关联,其余模式保持原行为。
if (!this.isDispatchType(type) && this.app.model.OrderItemsFactory) {
const ItemsModel = await this.app.model.OrderItemsFactory.getOrCreateModel(warehouseId, type);
// 发货单 -> 商品 (1:N)
DynamicModel.hasMany(ItemsModel, {
foreignKey: 'order_id',
sourceKey: 'id',
as: 'orderItems',
constraints: false,
});
// 商品 -> 发货单 (N:1)
ItemsModel.belongsTo(DynamicModel, {
foreignKey: 'order_id',
targetKey: 'id',
as: 'delivery',
constraints: false,
});
}
// 关联店铺表
if (this.app.model.Store) {
DynamicModel.belongsTo(this.app.model.Store, {
foreignKey: 'store_id',
targetKey: 'id',
as: 'store',
constraints: false,
});
DynamicModel.belongsTo(this.app.model.Store, {
foreignKey: 'warehouse_id',
targetKey: 'id',
as: 'warehouse',
constraints: false,
});
}
} catch (error) {
this.app.logger.warn('设置关联关系失败:', error.message);
}
}
/**
* 检查表是否存在
* @param {string} tableName 表名
* @return {Promise<boolean>} 是否存在
*/
async checkTableExists(tableName) {
const sequelize = this.app.model;
const queryInterface = sequelize.getQueryInterface();
try {
const tables = await queryInterface.showAllTables();
return tables.includes(tableName);
} catch (error) {
// 备用方案:使用原始查询
const checkSQL = `
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
`;
const [ results ] = await sequelize.query(checkSQL, {
replacements: [ tableName ],
});
return results.length > 0;
}
}
/**
* 判断目标表是否需要进行结构同步。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {boolean|null} [tableExists=null] 是否已确认表存在。
* @return {Promise<boolean>} 是否需要同步。
*/
async needsTableSchemaSync(tableName, type, warehouseId, tableExists = null) {
const queryInterface = this.app.model.getQueryInterface();
const managedTableExists = typeof tableExists === 'boolean'
? tableExists
: await this.checkTableExists(tableName);
if (!managedTableExists) {
return true;
}
const [ tables, indexes ] = await Promise.all([
queryInterface.describeTable(tableName),
typeof queryInterface.showIndex === 'function'
? queryInterface.showIndex(tableName)
: Promise.resolve([]),
]);
const expectedAttributes = this.getTableAttributes(type);
const expectedAttributeNames = Object.keys(expectedAttributes);
const actualAttributeNames = Object.keys(tables || {});
if (expectedAttributeNames.length !== actualAttributeNames.length) {
return true;
}
const actualColumnNames = new Set(actualAttributeNames);
for (const columnName of expectedAttributeNames) {
if (!actualColumnNames.has(columnName)) {
return true;
}
}
for (const columnName of expectedAttributeNames) {
if (isColumnDefinitionDifferent(columnName, expectedAttributes[columnName], tables[columnName])) {
return true;
}
}
const expectedIndexes = this.getIndexes(warehouseId, type);
const actualIndexes = Array.isArray(indexes) ? indexes : [];
for (const expectedIndex of expectedIndexes) {
const actualIndex = actualIndexes.find(index => (index.Key_name || index.name) === expectedIndex.name);
if (!actualIndex) {
return true;
}
if (isIndexDefinitionDifferent(expectedIndex, actualIndex)) {
return true;
}
}
return false;
}
/**
* 在结构同步前预检现有数据是否满足非空和数值范围约束。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @return {Promise<void>}
*/
async assertManagedTableDataConstraints(tableName, type) {
const queryInterface = this.app.model.getQueryInterface();
const sequelize = this.app.model;
const tableColumns = await queryInterface.describeTable(tableName);
const expectedAttributes = this.getTableAttributes(type);
const columnNames = new Set(Object.keys(tableColumns || {}));
const quotedTableName = quoteIdentifier(tableName);
// 收集需要检查的列
const notNullColumns = [];
const numericColumns = [];
for (const columnName of Object.keys(expectedAttributes)) {
if (!columnNames.has(columnName)) {
continue;
}
const expectedAttribute = expectedAttributes[columnName];
if (expectedAttribute.allowNull === false) {
notNullColumns.push(columnName);
}
const numericConstraint = parseNumericConstraint(expectedAttribute);
if (numericConstraint) {
numericColumns.push({ columnName, numericConstraint });
}
}
// 一条 SQL 检查所有 NOT NULL 约束
if (notNullColumns.length > 0) {
const conditions = notNullColumns
.map(col => `${quoteIdentifier(col)} IS NULL`)
.join(' OR ');
const selectCols = notNullColumns
.map(col => `MAX(CASE WHEN ${quoteIdentifier(col)} IS NULL THEN 1 ELSE 0 END) AS ${quoteIdentifier(col)}`)
.join(', ');
const [ nullRows ] = await sequelize.query(
`SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1`
);
if (Array.isArray(nullRows) && nullRows.length > 0) {
const row = nullRows[0];
for (const columnName of notNullColumns) {
if (row[columnName] === 1) {
throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL');
}
}
}
}
// 一条 SQL 检查所有数值范围约束
if (numericColumns.length > 0) {
const selectCols = numericColumns
.map(({ columnName, numericConstraint }) => {
const qCol = quoteIdentifier(columnName);
return `MAX(CASE WHEN ${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}) THEN 1 ELSE 0 END) AS ${quoteIdentifier(columnName)}`;
})
.join(', ');
const conditions = numericColumns
.map(({ columnName, numericConstraint }) => {
const qCol = quoteIdentifier(columnName);
return `(${qCol} IS NOT NULL AND (${qCol} < ${numericConstraint.min} OR ${qCol} > ${numericConstraint.max}))`;
})
.join(' OR ');
const [ rangeRows ] = await sequelize.query(
`SELECT ${selectCols} FROM ${quotedTableName} WHERE ${conditions} LIMIT 1`
);
if (Array.isArray(rangeRows) && rangeRows.length > 0) {
const row = rangeRows[0];
for (const { columnName, numericConstraint } of numericColumns) {
if (row[columnName] === 1) {
throw buildManagedTableConstraintError(
tableName,
columnName,
'NUMERIC_RANGE',
`expected=[${numericConstraint.min}, ${numericConstraint.max}]`
);
}
}
}
}
}
/**
* 获取同仓库共享 id 序列的全部分表的 MAX(id) 基线。
*
* 多表共用 id 契约:订单迁移到配送表时显式复制源 id,因此新分配的
* id 必须大于所有分表已占用的 id。
*
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<number>} 最大 id,无任何分表时返回 0。
*/
async getSharedIdBaseline(warehouseId) {
const tables = [
buildManagedTableName(warehouseId, 'current'),
buildManagedTableName(warehouseId, 'dispatch'),
buildManagedTableName(warehouseId, 'history'),
buildManagedTableName(warehouseId, 'outsourced'),
];
let existingTableSet = null;
try {
existingTableSet = new Set(await this.app.model.getQueryInterface().showAllTables());
} catch (error) {
existingTableSet = null;
}
let baseline = 0;
for (const relatedTable of tables) {
const exists = existingTableSet
? existingTableSet.has(relatedTable)
: await this.checkTableExists(relatedTable);
if (!exists) {
continue;
}
const [ rows ] = await this.app.model.query(
`SELECT COALESCE(MAX(id), 0) AS maxId FROM ${quoteIdentifier(relatedTable)}`
);
const maxId = Number(rows && rows[0] && rows[0].maxId || 0);
if (Number.isFinite(maxId) && maxId > baseline) {
baseline = maxId;
}
}
return baseline;
}
/**
* 核对并修复表自增水位,确保 AUTO_INCREMENT 大于同仓库共享 id 序列
* 的全部分表(current/dispatch/history/outsourced)的 MAX(id)。
*
* 多表共用 id 契约:订单迁移到配送表时显式复制源 id。因此 current 表的
* 自增序列必须全局单调——新分配的 id 不能与任何分表已占用的 id 重叠。
* 若高 id 订单已迁走(current 表 MAX(id) 变小),表重建会把水位重置为
* current.MAX(id)+1,与配送表已占用的 id 重叠,后续迁移显式插入会撞主键。
* 所以水位基准必须取所有分表的最大 MAX(id)。
*
* @param {string} tableName 表名。
* @return {Promise<void>}
*/
async ensureAutoIncrementWatermark(tableName) {
const parsed = parseManagedTableName(tableName);
if (!parsed) {
return;
}
const baseline = await this.getSharedIdBaseline(parsed.warehouseId);
if (!Number.isFinite(baseline) || baseline <= 0) {
return;
}
const autoIncrement = await this.getTableAutoIncrement(tableName);
if (autoIncrement === null || autoIncrement > baseline) {
return;
}
// 修复目标加安全余量:防止读取 MAX(id) 与 SET 之间的并发插入抢先占号,
// 导致修复后水位再次低于已分配 id(MySQL 不会把计数器降到当前已分配值以下,
// 余量仅作为并发窗口的缓冲)
const safeTarget = baseline + AUTO_INCREMENT_SAFE_MARGIN;
await this.app.model.query(`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`);
this.app.logger.warn(
`订单工厂表 ${tableName} 自增水位低于共享 id 序列最大 id(auto=${autoIncrement}, max=${baseline}),已修复为 ${safeTarget}`
);
}
/**
* 确保单个目标表与模型结构一致。
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [DynamicModel] 已构建的动态模型。
* @return {Promise<boolean>} 是否执行了同步。
*/
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
const modelType = this.resolveModelType(type);
const dynamicModel = DynamicModel || this.buildManagedModel(warehouseId, modelType, tableName);
const tableExists = await this.checkTableExists(tableName);
const needsSync = tableExists
? await this.needsTableSchemaSync(tableName, modelType, warehouseId, tableExists)
: true;
if (!tableExists) {
await dynamicModel.sync({ force: false });
return true;
}
if (needsSync) {
await this.assertManagedTableDataConstraints(tableName, modelType);
await this.alterManagedTableSchema(tableName, modelType, warehouseId);
}
// 无论是否同步结构,都核对自增水位(表重建/迁移/手工修复都可能破坏水位)
await this.ensureAutoIncrementWatermark(tableName);
return needsSync;
}
/**
* 读取表的当前 AUTO_INCREMENT 水位。
* @param {string} tableName 表名。
* @return {Promise<number|null>} 自增水位,非自增表返回 null。
*/
async getTableAutoIncrement(tableName) {
const [ rows ] = await this.app.model.query(
'SELECT AUTO_INCREMENT AS autoIncrement FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?',
{ replacements: [ tableName ] }
);
const rawValue = rows && rows[0] && rows[0].autoIncrement;
const value = Number(rawValue);
return Number.isFinite(value) ? value : null;
}
/**
* 获取仓库订单 id 序列表名。
*
* 每仓库一张序列表:id 自增发号,location 记录订单数据当前所在表位。
*
* @param {number|string} warehouseId 仓库ID。
* @return {string} 序列表名。
*/
getLocationSequenceTableName(warehouseId) {
return `wms_order_id_location_${warehouseId}`;
}
/**
* 确保仓库订单 id 序列表存在,并将其自增水位抬升到同仓库所有
* 订单分表 MAX(id) 之上(避开存量订单 id)。
*
* 注意:本方法可能执行 DDL(隐式提交),必须在事务外调用。
*
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<void>}
*/
async ensureLocationSequenceTable(warehouseId) {
const tableName = this.getLocationSequenceTableName(warehouseId);
// 进程内已初始化过则跳过:避免每次建单都重复 showAllTables + 分表 MAX 核对
if (this.locationTableReady.get(warehouseId)) {
return;
}
// 并发去重:同一仓库并发的 ensure 共享同一个初始化 Promise,
// 保证「建表 + 抬水位」只执行一次,其余调用等待完成后直接返回。
return await this.runModelInitializer(`init_seq_${warehouseId}`, async () => {
if (this.locationTableReady.get(warehouseId)) {
return;
}
// 先算基线再建表:建表语句直接携带正确水位。
// 消除「先建表(水位=1)再 ALTER」之间的发号窗口——否则窗口内
// 并发建单/多 worker 发号会拿到 1,与存量订单 id 冲突。
const baseline = await this.getSharedIdBaseline(warehouseId);
const safeTarget = baseline > 0 ? baseline + AUTO_INCREMENT_SAFE_MARGIN : 0;
const exists = await this.checkTableExists(tableName);
if (!exists) {
const autoIncrementClause = safeTarget > 0 ? ` AUTO_INCREMENT = ${safeTarget}` : '';
try {
await this.app.model.query(
`CREATE TABLE ${quoteIdentifier(tableName)} (
\`id\` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
\`location\` VARCHAR(20) NOT NULL DEFAULT 'current',
PRIMARY KEY (\`id\`)
) ENGINE=InnoDB${autoIncrementClause} DEFAULT CHARSET=utf8mb4 COMMENT='仓库订单全局id序列与位置索引(极简,不迁移)'`
);
this.app.logger.info(`创建订单 id 序列表成功: ${tableName}${safeTarget > 0 ? `, 初始水位=${safeTarget}` : ''}`);
} catch (createError) {
const errorCode = createError
&& ((createError.original && createError.original.code)
|| (createError.parent && createError.parent.code)
|| createError.code);
if (errorCode !== 'ER_TABLE_EXISTS') {
throw createError;
}
// 并发窗口:其他 worker 已建表,转入下方已存在核对分支
this.app.logger.warn(`订单 id 序列表 ${tableName} 已被并发创建,转入水位核对`);
}
}
// 表已存在(或刚被并发创建):核对并抬升水位
if (safeTarget > 0) {
const autoIncrement = await this.getTableAutoIncrement(tableName);
// ai 为 null(MariaDB 新建表/计数器未初始化)同样视为需要抬升
if (autoIncrement === null || autoIncrement <= baseline) {
await this.app.model.query(
`ALTER TABLE ${quoteIdentifier(tableName)} AUTO_INCREMENT = ${safeTarget}`
);
this.app.logger.warn(
`订单 id 序列表 ${tableName} 水位抬升至 ${safeTarget}(分表最大 id=${baseline},原水位=${autoIncrement ?? 'null'})`
);
}
}
this.locationTableReady.set(warehouseId, true);
});
}
/**
* 启动初检:为当前库中已存在的订单分表仓库确保序列表存在且水位正确。
*
* 仅做「建表 + 水位抬升」,不迁移任何数据——存量订单的位置指针回填由
* `script/backfill-order-id-location.cjs` 脚本负责。单个仓库失败仅告警,
* 不影响其他仓库与服务启动。
*
* @return {Promise<number>} 完成初检的仓库数。
*/
async ensureAllLocationSequenceTables() {
const managedTableNames = await this.listManagedTableNames();
const warehouseIds = Array.from(new Set(
managedTableNames
.map(tableName => {
const parsed = parseManagedTableName(tableName);
return parsed ? parsed.warehouseId : null;
})
.filter(Boolean)
));
let checkedCount = 0;
for (const warehouseId of warehouseIds) {
try {
await this.ensureLocationSequenceTable(warehouseId);
checkedCount += 1;
} catch (error) {
this.app.logger.warn(`[启动初检] 仓库 ${warehouseId} 序列表初始化失败: ${error.message}`);
}
}
if (warehouseIds.length > 0) {
this.app.logger.info(`[启动初检] 订单 id 序列表初检完成: ${checkedCount}/${warehouseIds.length} 个仓库`);
}
return checkedCount;
}
/**
* 从仓库序列表分配全局订单 id(在调用方事务内执行,随事务回滚)。
*
* 调用方必须在事务外先调用 ensureLocationSequenceTable 完成建表。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @param {string} [location='current'] 初始位置(current/dispatch/history/outsourced)。
* @return {Promise<number>} 新分配的订单 id。
*/
async allocateOrderId(warehouseId, transaction = null, location = 'current') {
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
// 不允许在事务内隐式 DDL,交给调用方在事务外初始化
throw new Error(`订单 id 序列表 ${tableName} 不存在,请先调用 ensureLocationSequenceTable`);
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const queryResult = await this.app.model.query(
`INSERT INTO ${quoteIdentifier(tableName)} (\`location\`) VALUES (?)`,
{ replacements: [ location ], ...options }
);
// sequelize.query 对 INSERT 的返回形态随驱动不同,兼容解析:
// - mysql2: [ insertId, affectedRows ](首个元素是数字)
// - 其他包装: [{ insertId, affectedRows }, ...]
const raw = Array.isArray(queryResult) ? queryResult[0] : queryResult;
let insertId = 0;
if (typeof raw === 'number') {
insertId = raw;
} else if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
insertId = Number(raw.insertId || 0);
} else if (Array.isArray(raw) && raw.length > 0 && typeof raw[0] === 'number') {
insertId = Number(raw[0]);
}
if (!Number.isFinite(insertId) || insertId <= 0) {
throw new Error('订单 id 分配失败');
}
return insertId;
}
/**
* 更新订单在序列表中的位置指针(迁移时调用)。
*
* 存量订单(序列表无记录)以显式 id 补录;显式插入值大于当前水位时
* MySQL 会自动推进序列表自增,保证后续发号不与存量 id 冲突。
*
* @param {number|string} orderId 订单ID。
* @param {number|string} warehouseId 仓库ID。
* @param {string} location 新位置。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<void>}
*/
async updateOrderLocation(orderId, warehouseId, location, transaction = null) {
const tableName = this.getLocationSequenceTableName(warehouseId);
const options = transaction ? { transaction } : {};
await this.app.model.query(
`INSERT INTO ${quoteIdentifier(tableName)} (\`id\`, \`location\`) VALUES (?, ?) ON DUPLICATE KEY UPDATE \`location\` = VALUES(\`location\`)`,
{ replacements: [ Number(orderId), location ], ...options }
);
}
/**
* 查询单个订单当前所在表位。
*
* @param {number|string} orderId 订单ID。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<string|null>} 位置(current/dispatch/history/outsourced),
* 无记录返回 null(存量订单未回填)。
*/
async getOrderLocation(orderId, warehouseId, transaction = null) {
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
return null;
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const [ rows ] = await this.app.model.query(
`SELECT \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` = ? LIMIT 1`,
{ replacements: [ Number(orderId) ], ...options }
);
return rows && rows[0] ? String(rows[0].location) : null;
}
/**
* 批量查询订单当前所在表位。
*
* @param {Array<number|string>} orderIds 订单ID列表。
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<Map<number, string>>} orderId → location;
* 无记录的订单不在 Map 中(存量订单未回填)。
*/
async getOrderLocations(orderIds, warehouseId, transaction = null) {
const result = new Map();
const normalizedIds = Array.from(new Set(
(Array.isArray(orderIds) ? orderIds : [ orderIds ])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0)
));
if (normalizedIds.length === 0) {
return result;
}
const tableName = this.getLocationSequenceTableName(warehouseId);
if (!this.locationTableReady.get(warehouseId)) {
const exists = await this.checkTableExists(tableName);
if (!exists) {
return result;
}
this.locationTableReady.set(warehouseId, true);
}
const options = transaction ? { transaction } : {};
const placeholders = normalizedIds.map(() => '?').join(',');
const [ rows ] = await this.app.model.query(
`SELECT \`id\`, \`location\` FROM ${quoteIdentifier(tableName)} WHERE \`id\` IN (${placeholders})`,
{ replacements: normalizedIds, ...options }
);
for (const row of rows || []) {
result.set(Number(row.id), String(row.location));
}
return result;
}
/**
* 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。
*
* 自增保护:对自增主键 id 列不做 CHANGE——对 AUTO_INCREMENT 列重新声明
* 列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为
* MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史
* 低值,与配送表已复制的 id 重叠,导致后续迁移主键冲突。
*
* @param {string} tableName 表名。
* @param {string} type 模型类型。
* @param {number|string} warehouseId 仓库ID。
* @return {Promise<void>}
*/
async alterManagedTableSchema(tableName, type, warehouseId) {
const queryInterface = this.app.model.getQueryInterface();
const sequelize = this.app.model;
const actualColumns = await queryInterface.describeTable(tableName);
const expectedAttributes = this.getTableAttributes(type);
const quotedTableName = quoteIdentifier(tableName);
const actualColumnNames = new Set(Object.keys(actualColumns || {}));
const expectedColumnNames = Object.keys(expectedAttributes);
const clauses = [];
// ADD 新增列 / CHANGE 差异列;id 主键列永不参与 CHANGE——对 AUTO_INCREMENT
// 列重新声明列定义可能触发表重建(ALGORITHM=COPY),重建后 AUTO_INCREMENT 被重置为
// MAX(id)+1。待处理表的高 id 订单已迁移删除,重置会使自增水位回退到历史低值,
// 与配送表已复制的 id 重叠,导致后续迁移主键冲突。
for (const columnName of expectedColumnNames) {
const expectedAttribute = expectedAttributes[columnName];
if (columnName === 'id') {
continue;
}
const columnDef = buildColumnLine(columnName, expectedAttribute);
if (!actualColumnNames.has(columnName)) {
clauses.push(`ADD COLUMN ${columnDef}`);
} else if (isColumnDefinitionDifferent(columnName, expectedAttribute, actualColumns[columnName])) {
clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`);
}
}
// DROP 多余列(现有表有但期望模型没有的列;id 必在期望模型中,不会被 DROP)
const expectedColumnSet = new Set(expectedColumnNames);
for (const columnName of actualColumnNames) {
if (!expectedColumnSet.has(columnName)) {
clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`);
}
}
const previousAutoIncrement = await this.getTableAutoIncrement(tableName);
if (clauses.length > 0) {
await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`);
}
// 若 ALTER 触发表重建并把自增水位重置到历史低值,恢复原水位
const currentAutoIncrement = await this.getTableAutoIncrement(tableName);
if (previousAutoIncrement !== null
&& currentAutoIncrement !== null
&& currentAutoIncrement < previousAutoIncrement) {
await sequelize.query(`ALTER TABLE ${quotedTableName} AUTO_INCREMENT = ${previousAutoIncrement}`);
this.app.logger.warn(
`订单工厂表 ${tableName} 自增水位被 ALTER 重置(${previousAutoIncrement} → ${currentAutoIncrement}),已恢复为 ${previousAutoIncrement}`
);
}
// 索引同步不再使用 sync({ alter: true }):历史事故表明它会重建表并重置自增水位,
// 且无法可靠检测 AUTO_INCREMENT 属性差异。改为仅补齐缺失索引,不重建、不删除已有索引。
const existingIndexNames = new Set((await queryInterface.showIndex(tableName))
.map(index => index.Key_name || index.name || '')
.filter(Boolean));
for (const indexDef of this.getIndexes(warehouseId, type)) {
if (existingIndexNames.has(indexDef.name)) {
continue;
}
await queryInterface.addIndex(tableName, indexDef.fields, {
name: indexDef.name,
unique: Boolean(indexDef.unique),
});
}
}
/**
* 获取当前库中已存在的订单工厂目标表。
* @return {Promise<Array<string>>} 目标表名列表。
*/
async listManagedTableNames() {
const [ rows ] = await this.app.model.query(`
SELECT TABLE_NAME AS tableName
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME LIKE 'wms_order_delivery_%'
`);
return rows
.map(item => item.tableName)
.filter(tableName => parseManagedTableName(tableName));
}
/**
* 创建物理表
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {Promise<void>}
*/
async createPhysicalTable(warehouseId, type) {
const modelType = this.resolveModelType(type);
const tableName = this.generateTableName(warehouseId, modelType);
const dynamicModel = this.buildManagedModel(warehouseId, modelType, tableName);
// 统一走差异检测 + 自增水位保护的同步路径,不再使用 sync({ alter: true })
await this.ensureManagedTableSchema(tableName, modelType, warehouseId, dynamicModel);
this.app.logger.info(`创建/同步物理表成功: ${tableName}`);
}
/**
* 获取状态枚举值
*/
getStatusEnumValues() {
return {
status: [ 'created', 'cancel', 'error' ],
sync_status: [ 'padding', 'fin', 'error' ],
post_status: [ 'padding', 'fin', 'timeout', 'error', 'none' ],
storage_status: [ 'padding', 'fin', 'error', 'none' ],
pick_status: [ 'padding', 'fin', 'error', 'none' ],
pack_status: [ 'none', 'padding', 'fin', 'error' ],
inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ],
step: [ 0, 1 ],
print_status: [ 'none', 'padding', 'fin', 'error' ],
print_lock_status: [ 'none', 'warehouse' ],
claim_status: [ 'none', 'padding', 'fin', 'error' ],
outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
lock_status: [ 'none', 'warehouse', 'store' ],
intercept_status: [
'none', 'requesting', 'requested', 'intercepting',
'intercepted_in_transit', 'intercepted_at_warehouse',
'returning', 'returned', 'delivered_by_mistake',
'timeout', 'cancelled', 'failed', 'exception',
],
};
}
/**
* 生成表名
* @param {number} warehouseId 仓库ID
* @param {string} type 模型类型
* @return {string} 表名
*/
generateTableName(warehouseId, type) {
const modelType = this.resolveModelType(type);
return buildManagedTableName(warehouseId, modelType);
}
/**
* 获取订单工厂管理表的注释。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表注释。
*/
getTableComment(warehouseId, type) {
return buildTableComment(warehouseId, type);
}
/**
* 清理模型缓存
*/
clearCache() {
this.modelCache.clear();
this.inflightInitCache.clear();
clearShardWarehouseValidationCache(this.app);
this.app.logger.info('模型缓存已清理');
}
/**
* 获取所有缓存的模型
*/
getCachedModels() {
return Array.from(this.modelCache.entries());
}
}
return new OrderDeliveryFactory();
};