856 lines
28 KiB
JavaScript
856 lines
28 KiB
JavaScript
// 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,
|
|
parseManagedTableName,
|
|
} = 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.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) {
|
|
const expectedColumn = expectedAttributes[columnName];
|
|
const actualColumn = tables[columnName] || {};
|
|
const expectedType = expectedColumn.type && typeof expectedColumn.type.toSql === 'function'
|
|
? expectedColumn.type.toSql().toLowerCase()
|
|
: String(expectedColumn.type || '').toLowerCase();
|
|
const actualType = String(actualColumn.type || actualColumn.Type || '').toLowerCase();
|
|
const expectedAllowNull = expectedColumn.allowNull !== false;
|
|
const actualAllowNull = actualColumn.allowNull !== false;
|
|
const expectedDefault = Object.prototype.hasOwnProperty.call(expectedColumn, 'defaultValue')
|
|
? expectedColumn.defaultValue
|
|
: undefined;
|
|
const actualDefault = Object.prototype.hasOwnProperty.call(actualColumn, 'defaultValue')
|
|
? actualColumn.defaultValue
|
|
: undefined;
|
|
|
|
if (expectedType && actualType && expectedType !== actualType) {
|
|
return true;
|
|
}
|
|
|
|
if (expectedAllowNull !== actualAllowNull) {
|
|
return true;
|
|
}
|
|
|
|
const normalizedExpectedDefault = expectedDefault == null ? null : String(expectedDefault);
|
|
const normalizedActualDefault = actualDefault == null ? null : String(actualDefault);
|
|
if (normalizedExpectedDefault !== normalizedActualDefault) {
|
|
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}]`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 确保单个目标表与模型结构一致。
|
|
* @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 (!needsSync) {
|
|
return false;
|
|
}
|
|
|
|
if (!tableExists) {
|
|
await dynamicModel.sync({ force: false });
|
|
return true;
|
|
}
|
|
|
|
await this.assertManagedTableDataConstraints(tableName, modelType);
|
|
await this.alterManagedTableSchema(tableName, modelType, warehouseId, dynamicModel);
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 将现有表的列结构与期望模型对齐,所有变更合并为单条 ALTER TABLE 语句。
|
|
* @param {string} tableName 表名。
|
|
* @param {string} type 模型类型。
|
|
* @param {number|string} warehouseId 仓库ID。
|
|
* @param {Object} dynamicModel 已构建的动态模型(用于索引同步)。
|
|
* @return {Promise<void>}
|
|
*/
|
|
async alterManagedTableSchema(tableName, type, warehouseId, dynamicModel) {
|
|
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 变更列
|
|
for (const columnName of expectedColumnNames) {
|
|
const columnDef = buildColumnLine(columnName, expectedAttributes[columnName]);
|
|
if (!actualColumnNames.has(columnName)) {
|
|
clauses.push(`ADD COLUMN ${columnDef}`);
|
|
} else {
|
|
clauses.push(`CHANGE ${quoteIdentifier(columnName)} ${columnDef}`);
|
|
}
|
|
}
|
|
|
|
// DROP 多余列(现有表有但期望模型没有的列)
|
|
const expectedColumnSet = new Set(expectedColumnNames);
|
|
for (const columnName of actualColumnNames) {
|
|
if (!expectedColumnSet.has(columnName)) {
|
|
clauses.push(`DROP COLUMN ${quoteIdentifier(columnName)}`);
|
|
}
|
|
}
|
|
|
|
if (clauses.length > 0) {
|
|
await sequelize.query(`ALTER TABLE ${quotedTableName} ${clauses.join(', ')}`);
|
|
}
|
|
|
|
// 索引同步仍委托 Sequelize sync({ alter: true }) 处理(仅触发索引差异)
|
|
await dynamicModel.sync({ alter: true });
|
|
}
|
|
|
|
/**
|
|
* 获取当前库中已存在的订单工厂目标表。
|
|
* @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);
|
|
|
|
await dynamicModel.sync({ alter: true });
|
|
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();
|
|
};
|