// app/model/wms_order_delivery_factory.js 'use strict'; module.exports = app => { const { Sequelize, model } = app; class OrderDeliveryFactory { constructor() { this.modelCache = new Map(); this.app = app; } /** * 获取当前表模型 * @param warehouseId */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); } /** * 获取历史表模型 * @param warehouseId */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); } /** * 根据表名直接获取模型 * @param tableName */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } try { const tableExists = await this.checkTableExists(tableName); if (!tableExists) { throw new Error(`表 ${tableName} 不存在`); } const baseAttributes = this.app.model.OrderDelivery.rawAttributes; const DynamicModel = this.app.model.define(tableName, baseAttributes, { tableName, timestamps: false, comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表', }); this.modelCache.set(cacheKey, DynamicModel); return DynamicModel; } catch (error) { this.app.logger.error(`获取模型失败 ${tableName}:`, error); throw error; } } /** * 获取或创建模型 * @param warehouseId * @param type */ async getOrCreateModel(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); const cacheKey = `${warehouseId}_${type}`; // 检查缓存 if (this.modelCache.has(cacheKey)) { return this.modelCache.get(cacheKey); } try { // 检查表是否存在,不存在则创建 const tableExists = await this.checkTableExists(tableName); if (!tableExists) { await this.createPhysicalTable(warehouseId, type); } // 创建模型实例 const baseAttributes = this.app.model.OrderDelivery.rawAttributes; const modelOptions = this.getModelOptions(tableName, warehouseId, type); const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions); // 设置关联关系 this.setupAssociations(DynamicModel, warehouseId, type); // 缓存模型 this.modelCache.set(cacheKey, DynamicModel); this.app.logger.info(`创建动态模型成功: ${tableName}`); return DynamicModel; } catch (error) { this.app.logger.error(`创建动态模型失败 ${tableName}:`, error); throw error; } } /** * 获取模型配置选项 * @param tableName * @param warehouseId * @param type */ getModelOptions(tableName, warehouseId, type) { const options = { tableName, timestamps: false, comment: type === 'history' ? `仓库${warehouseId}发货单历史表` : `仓库${warehouseId}发货单常用表`, indexes: this.getIndexes(warehouseId, type), }; // 历史表添加归档时间字段 if (type === 'history') { options.fields = Object.keys(this.app.model.OrderDelivery.rawAttributes); options.fields.push('archive_time'); } return options; } /** * 获取索引配置 * @param warehouseId * @param type */ getIndexes(warehouseId, type) { const prefix = `${warehouseId}_${type}`; return [ { name: `idx_${prefix}_store_id`, fields: [ 'store_id' ], }, { name: `idx_${prefix}_warehouse_id`, fields: [ 'warehouse_id' ], }, { name: `idx_${prefix}_delivery_code`, unique: true, fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ], }, { name: `idx_${prefix}_items`, fields: [ 'items' ], length: 50, }, { name: `idx_${prefix}_items_hash`, fields: [ 'items_hash' ], }, { name: `idx_${prefix}_hash_crc`, fields: [ 'items_hash', 'items_crc', 'warehouse_id' ], }, { name: `idx_${prefix}_wave`, fields: [ 'status', 'wave_id' ], }, { name: `idx_${prefix}_statuses`, fields: [ 'status', 'post_status', 'pick_status', 'pack_status', 'outbound_status', ], }, ]; } /** * 设置关联关系 * @param DynamicModel * @param warehouseId * @param type */ async setupAssociations(DynamicModel, warehouseId, type) { try { // 如果存在商品模型工厂,建立关联 if (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 tableName */ 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 warehouseId * @param type */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); const tableComment = type === 'history' ? `仓库${warehouseId}发货单历史表` : `仓库${warehouseId}发货单常用表`; // 添加历史表特有的字段 const historyFields = type === 'history' ? ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; // 状态机枚举值 const statusEnums = this.getStatusEnumValues(); const createTableSQL = ` CREATE TABLE \`${tableName}\` ( \`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, \`delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '发货单号', \`pre_delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '预发货单号', \`pre_delivery_order_id\` varchar(50) DEFAULT NULL COMMENT '预发货单ID', \`order_type\` varchar(50) DEFAULT NULL COMMENT '订单类型', \`warehouse_code\` varchar(50) DEFAULT NULL COMMENT '仓库编码', \`order_flag\` varchar(200) DEFAULT NULL COMMENT '订单标记', \`source_platform_code\` varchar(50) DEFAULT NULL COMMENT '来源平台编码', \`source_platform_name\` varchar(200) DEFAULT NULL COMMENT '来源平台名称', \`create_at\` datetime DEFAULT NULL COMMENT '创建时间', \`delete_at\` datetime DEFAULT NULL COMMENT '删除时间', \`updated_at\` datetime DEFAULT NULL COMMENT '更新时间', \`place_order_time\` datetime DEFAULT NULL COMMENT '店铺创建订单时间', \`pay_time\` datetime DEFAULT NULL COMMENT '支付时间', \`pay_no\` varchar(50) DEFAULT NULL COMMENT '支付单号', \`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码', \`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人', \`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间', \`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间', \`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称', \`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称', \`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称', \`total_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单总金额', \`item_amount\` decimal(18,2) DEFAULT NULL COMMENT '商品总金额', \`discount_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单折扣金额', \`freight\` decimal(18,2) DEFAULT NULL COMMENT '快递费用', \`ar_amount\` decimal(18,2) DEFAULT NULL COMMENT '应收金额', \`got_amount\` decimal(18,2) DEFAULT NULL COMMENT '已收金额', \`service_fee\` decimal(18,2) DEFAULT NULL COMMENT 'COD服务费', \`logistics_code\` varchar(50) DEFAULT NULL COMMENT '物流公司编码', \`logistics_name\` varchar(200) DEFAULT NULL COMMENT '物流公司名称', \`express_code\` varchar(50) DEFAULT NULL COMMENT '面单号前置', \`logistics_area_code\` varchar(50) DEFAULT NULL COMMENT '快递区域编码, 大头笔信息', \`delivery_type\` varchar(255) DEFAULT NULL COMMENT '发货服务类型', \`is_urgency\` enum('Y','N') DEFAULT 'N' COMMENT '是否紧急', \`invoice_flag\` enum('Y','N') DEFAULT 'N' COMMENT '是否需要发票', \`status\` enum('pedding','created','cancel','error') DEFAULT 'created' COMMENT '状态', \`name\` text COMMENT '收件人姓名', \`zip_code\` varchar(50) DEFAULT NULL COMMENT '收件人邮编', \`tel\` text COMMENT '收件人电话', \`mobile\` text COMMENT '收件人移动电话', \`email\` text COMMENT '收件人邮箱', \`country_code\` varchar(255) DEFAULT NULL COMMENT '国家编码', \`province\` varchar(255) DEFAULT NULL COMMENT '省份', \`city\` varchar(255) DEFAULT NULL COMMENT '城市', \`area\` varchar(255) DEFAULT NULL COMMENT '区', \`town\` varchar(255) DEFAULT NULL COMMENT '镇', \`detail_address\` varchar(255) DEFAULT NULL COMMENT '详细地址', \`id_type\` varchar(255) DEFAULT NULL COMMENT '证件类型', \`id_number\` int(11) DEFAULT NULL COMMENT '证件号码', \`oaid\` text COMMENT 'OAID', \`sync_status\` enum('padding','fin','error') DEFAULT 'padding' COMMENT '同步状态', \`store_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '货主id', \`warehouse_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '仓库id', \`from_key\` int(11) DEFAULT NULL COMMENT '来源键', \`items\` text COMMENT '商品结构字符串', \`items_count\` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品种类数', \`items_total\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品总数', \`items_weight\` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总重量', \`items_hash\` char(32) NOT NULL DEFAULT '' COMMENT '哈希值', \`items_crc\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '校验码', \`wave_id\` bigint(20) NOT NULL DEFAULT '0' COMMENT '波次ID,0表示未分配', \`post_status\` enum('padding','fin','timeout','error','none') DEFAULT 'none' COMMENT '分配快递号状态机', \`storage_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '分配储位状态机', \`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机', \`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机', \`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机', \`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机', \`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机', \`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机', \`lock_status\` enum('none','warehouse','store') DEFAULT NULL COMMENT '锁定状态机', \`intercept_status\` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL COMMENT '拦截状态机' ${historyFields}, PRIMARY KEY (\`id\`), UNIQUE KEY \`idx_${warehouseId}_${type}_delivery_code\` (\`delivery_order_code\`,\`store_id\`,\`warehouse_id\`), KEY \`idx_${warehouseId}_${type}_store_id\` (\`store_id\`), KEY \`idx_${warehouseId}_${type}_warehouse_id\` (\`warehouse_id\`), KEY \`idx_${warehouseId}_${type}_items\` (\`items\`(50)), KEY \`idx_${warehouseId}_${type}_items_hash\` (\`items_hash\`), KEY \`idx_${warehouseId}_${type}_hash_crc\` (\`items_hash\`,\`items_crc\`,\`warehouse_id\`), KEY \`idx_${warehouseId}_${type}_wave\` (\`status\`,\`wave_id\`), KEY \`idx_${warehouseId}_${type}_statuses\` (\`status\`,\`post_status\`,\`pick_status\`,\`pack_status\`,\`outbound_status\`) ${type === 'history' ? `,KEY \`idx_${warehouseId}_history_archive_time\` (\`archive_time\`)` : ''} ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='${tableComment}'; `; await this.app.model.query(createTableSQL); 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' ], print_status: [ 'none', 'padding', 'fin', 'error' ], claim_status: [ 'none', 'padding', 'fin', 'error' ], outbound_status: [ 'none', 'padding', 'fin', '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 warehouseId * @param type */ generateTableName(warehouseId, type) { const suffix = type === 'history' ? '_history' : ''; return `wms_order_delivery_${warehouseId}${suffix}`; } /** * 清理模型缓存 */ clearCache() { this.modelCache.clear(); this.app.logger.info('模型缓存已清理'); } /** * 获取所有缓存的模型 */ getCachedModels() { return Array.from(this.modelCache.entries()); } } return new OrderDeliveryFactory(); };