// 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, 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.app = app; } /** * 获取配送域车道常量。 * @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} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); } /** * 获取历史表模型 * @param {number} warehouseId 仓库ID * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); } /** * 获取配送域模型。 * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 配送域模型。 */ 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} 配送域模型。 */ async getM4Model(warehouseId) { return await this.getDispatchModel(warehouseId); } /** * 获取配送异常模型。 * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 配送域模型。 */ async getM5Model(warehouseId) { return await this.getDispatchModel(warehouseId); } /** * 根据表名直接获取模型 * @param {string} tableName 表名 * @return {Promise} 动态模型 */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; 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} 动态模型 */ 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}`; // 检查缓存 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.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} 索引配置 */ getIndexes(warehouseId, type) { return buildIndexOptions(warehouseId, type); } /** * 获取当前表通用列定义行。 * * @param {string} type 模型类型 * @return {Array} 当前表列定义行 */ getCurrentTableColumnLines(type = 'current') { return buildColumnLines(this.app, type); } /** * 获取当前表通用索引定义行。 * * @param {number} warehouseId 仓库ID * @param {string} type 模型类型 * @return {Array} 当前表索引定义行 */ getCurrentTableIndexLines(warehouseId, type = 'current') { return buildIndexLines(warehouseId, type); } /** * 获取配送域物理表名。 * @param {number|string} warehouseId 仓库ID。 * @return {Promise} 配送域物理表名。 */ async getDispatchTableName(warehouseId) { const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId); return `wms_order_delivery_dispatch_${warehouseIdStr}`; } /** * 获取配送域表列定义行。 * @return {Array} 配送域表列定义行。 */ getDispatchTableColumnLines() { return buildColumnLines(this.app, 'dispatch'); } /** * 获取配送域表索引定义行。 * @param {string} warehouseIdStr 仓库ID字符串。 * @return {Array} 配送域表索引定义行。 */ getDispatchTableIndexLines(warehouseIdStr) { return buildIndexLines(warehouseIdStr, 'dispatch'); } /** * 获取配送域索引配置。 * @param {string} warehouseIdStr 仓库ID字符串。 * @return {Array} 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} */ 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} 是否存在 */ 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} 是否需要同步。 */ 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} */ 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 || {})); for (const columnName of Object.keys(expectedAttributes)) { if (!columnNames.has(columnName)) { continue; } const expectedAttribute = expectedAttributes[columnName]; const quotedTableName = quoteIdentifier(tableName); const quotedColumnName = quoteIdentifier(columnName); if (expectedAttribute.allowNull === false) { const [ nullRows ] = await sequelize.query( `SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NULL LIMIT 1` ); if (Array.isArray(nullRows) && nullRows.length > 0) { throw buildManagedTableConstraintError(tableName, columnName, 'NOT_NULL'); } } const numericConstraint = parseNumericConstraint(expectedAttribute); if (!numericConstraint) { continue; } const [ rangeRows ] = await sequelize.query( `SELECT 1 AS violationFound FROM ${quotedTableName} WHERE ${quotedColumnName} IS NOT NULL AND (${quotedColumnName} < :minValue OR ${quotedColumnName} > :maxValue) LIMIT 1`, { replacements: { minValue: numericConstraint.min, maxValue: numericConstraint.max, }, } ); if (Array.isArray(rangeRows) && rangeRows.length > 0) { 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} 是否执行了同步。 */ 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 this.assertManagedTableDataConstraints(tableName, modelType); } await dynamicModel.sync({ alter: true }); return true; } /** * 扫描并同步订单工厂管理的目标表。 * @return {Promise} */ async ensureManagedTableSchemas() { const tableNames = await this.listManagedTableNames(); for (const tableName of tableNames) { const parsed = parseManagedTableName(tableName); if (!parsed) { continue; } await this.ensureManagedTableSchema(tableName, parsed.type, parsed.warehouseId); } } /** * 获取当前库中已存在的订单工厂目标表。 * @return {Promise>} 目标表名列表。 */ 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} */ 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' ], 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(); clearShardWarehouseValidationCache(this.app); this.app.logger.info('模型缓存已清理'); } /** * 获取所有缓存的模型 */ getCachedModels() { return Array.from(this.modelCache.entries()); } } return new OrderDeliveryFactory(); };