302 lines
9.3 KiB
JavaScript
302 lines
9.3 KiB
JavaScript
// order_items_factory.js
|
||
'use strict';
|
||
|
||
module.exports = app => {
|
||
const { Sequelize, model } = app;
|
||
|
||
class OrderItemsFactory {
|
||
constructor() {
|
||
this.modelCache = new Map();
|
||
this.app = app;
|
||
this.creatingTables = new Map(); // 防止并发创建表
|
||
}
|
||
|
||
/**
|
||
* 获取当前表模型
|
||
* @param warehouseId
|
||
*/
|
||
async getCurrentModel(warehouseId) {
|
||
return await this.getOrCreateModel(warehouseId, 'current');
|
||
}
|
||
|
||
/**
|
||
* 获取历史表模型
|
||
* @param warehouseId
|
||
*/
|
||
async getHistoryModel(warehouseId) {
|
||
return await this.getOrCreateModel(warehouseId, 'history');
|
||
}
|
||
|
||
/**
|
||
* 获取或创建模型
|
||
* @param warehouseId
|
||
* @param type
|
||
*/
|
||
async getOrCreateModel(warehouseId, type = 'current') {
|
||
const cacheKey = `${warehouseId}_${type}`;
|
||
|
||
// 检查缓存
|
||
if (this.modelCache.has(cacheKey)) {
|
||
return this.modelCache.get(cacheKey);
|
||
}
|
||
|
||
const tableName = this.generateTableName(warehouseId, type);
|
||
|
||
try {
|
||
// 防止并发创建表
|
||
if (this.creatingTables.has(cacheKey)) {
|
||
await this.creatingTables.get(cacheKey);
|
||
return this.modelCache.get(cacheKey);
|
||
}
|
||
|
||
const createPromise = this.createModelWithRetry(warehouseId, type, tableName, cacheKey);
|
||
this.creatingTables.set(cacheKey, createPromise);
|
||
|
||
const dynamicModel = await createPromise;
|
||
this.creatingTables.delete(cacheKey);
|
||
|
||
return dynamicModel;
|
||
} catch (error) {
|
||
this.creatingTables.delete(cacheKey);
|
||
this.app.logger.error(`获取订单商品模型失败 ${tableName}:`, error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 带重试的模型创建
|
||
* @param warehouseId
|
||
* @param type
|
||
* @param tableName
|
||
* @param cacheKey
|
||
* @param retryCount
|
||
*/
|
||
async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) {
|
||
for (let i = 0; i < retryCount; i++) {
|
||
try {
|
||
// 检查表是否存在
|
||
const tableExists = await this.checkTableExists(tableName);
|
||
if (!tableExists) {
|
||
await this.createPhysicalTable(warehouseId, type);
|
||
}
|
||
|
||
// 创建模型实例
|
||
const mainModel = this.app.model.OrderItems;
|
||
const attributes = { ...mainModel.rawAttributes };
|
||
|
||
// 移除主键的autoIncrement属性,避免动态表冲突
|
||
if (attributes.id) {
|
||
delete attributes.id.autoIncrement;
|
||
}
|
||
|
||
const DynamicModel = this.app.model.define(tableName, attributes, {
|
||
tableName,
|
||
timestamps: true,
|
||
underscored: true,
|
||
paranoid: false,
|
||
indexes: this.generateIndexes(warehouseId),
|
||
comment: type === 'history'
|
||
? `仓库${warehouseId}订单商品历史表`
|
||
: `仓库${warehouseId}订单商品常用表`,
|
||
});
|
||
|
||
// 复制关联关系
|
||
this.copyAssociations(mainModel, DynamicModel);
|
||
|
||
// 缓存模型
|
||
this.modelCache.set(cacheKey, DynamicModel);
|
||
this.app.logger.info(`创建订单商品动态模型成功: ${tableName}`);
|
||
|
||
return DynamicModel;
|
||
} catch (error) {
|
||
if (i === retryCount - 1) {
|
||
throw error;
|
||
}
|
||
this.app.logger.warn(`创建模型失败,第${i + 1}次重试:`, error.message);
|
||
await this.sleep(500); // 等待500ms后重试
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 复制关联关系
|
||
* @param sourceModel
|
||
* @param targetModel
|
||
*/
|
||
copyAssociations(sourceModel, targetModel) {
|
||
if (sourceModel.associations) {
|
||
Object.keys(sourceModel.associations).forEach(key => {
|
||
const association = sourceModel.associations[key];
|
||
const options = { ...association.options };
|
||
|
||
// 避免动态表的外键约束问题
|
||
options.constraints = false;
|
||
|
||
if (association.associationType === 'BelongsTo') {
|
||
targetModel.belongsTo(
|
||
association.target,
|
||
{
|
||
...options,
|
||
foreignKey: association.foreignKey,
|
||
as: association.as,
|
||
}
|
||
);
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成索引配置
|
||
* @param warehouseId
|
||
*/
|
||
generateIndexes(warehouseId) {
|
||
return [
|
||
{
|
||
name: `idx_${warehouseId}_order_id`,
|
||
fields: [ 'order_id' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_item_id`,
|
||
fields: [ 'item_id' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_item_code`,
|
||
fields: [ 'item_code' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_source_order_code`,
|
||
fields: [ 'source_order_code' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_stock_id`,
|
||
fields: [ 'stock_id' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_owner_code`,
|
||
fields: [ 'owner_code' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_order_item`,
|
||
fields: [ 'order_id', 'item_id' ],
|
||
},
|
||
{
|
||
name: `idx_${warehouseId}_created_at`,
|
||
fields: [ 'created_at' ],
|
||
},
|
||
];
|
||
}
|
||
|
||
/**
|
||
* 检查表是否存在
|
||
* @param tableName
|
||
*/
|
||
async checkTableExists(tableName) {
|
||
try {
|
||
const [ results ] = await this.app.model.query(
|
||
`SELECT 1 FROM information_schema.tables
|
||
WHERE table_schema = DATABASE()
|
||
AND table_name = :tableName`,
|
||
{
|
||
replacements: { tableName },
|
||
type: Sequelize.QueryTypes.SELECT,
|
||
}
|
||
);
|
||
return !!results;
|
||
} catch (error) {
|
||
this.app.logger.error('检查表是否存在失败:', error);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 创建物理表
|
||
* @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' ?
|
||
',`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : '';
|
||
|
||
const createTableSQL = `
|
||
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
||
\`id\` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||
\`order_id\` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID',
|
||
\`actual_price\` decimal(18,2) NOT NULL DEFAULT '0.00' COMMENT '实际价格',
|
||
\`retail_price\` decimal(18,2) DEFAULT NULL COMMENT '零售价格',
|
||
\`ext_code\` varchar(50) DEFAULT NULL COMMENT '外部编码',
|
||
\`inventory_type\` varchar(50) DEFAULT NULL COMMENT '库存类型',
|
||
\`item_code\` varchar(50) DEFAULT NULL COMMENT '商品编码',
|
||
\`item_id\` bigint(20) DEFAULT NULL COMMENT '商品ID',
|
||
\`item_name\` varchar(200) DEFAULT NULL COMMENT '商品名称',
|
||
\`order_line_no\` varchar(50) DEFAULT NULL COMMENT '订单行号',
|
||
\`owner_code\` varchar(50) DEFAULT NULL COMMENT '货主编码',
|
||
\`plan_qty\` int(11) DEFAULT NULL COMMENT '计划数量',
|
||
\`source_order_code\` varchar(50) DEFAULT NULL COMMENT '源订单编码',
|
||
\`sub_source_order_code\` varchar(50) DEFAULT NULL COMMENT '子源订单编码',
|
||
\`extend_props\` json DEFAULT NULL COMMENT '扩展属性(JSON格式)',
|
||
\`stock_id\` bigint(20) DEFAULT NULL COMMENT '库存ID',
|
||
\`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||
\`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
|
||
${historyFields},
|
||
PRIMARY KEY (\`id\`),
|
||
KEY \`idx_${warehouseId}_order_id\` (\`order_id\`),
|
||
KEY \`idx_${warehouseId}_item_id\` (\`item_id\`),
|
||
KEY \`idx_${warehouseId}_item_code\` (\`item_code\`),
|
||
KEY \`idx_${warehouseId}_source_order_code\` (\`source_order_code\`),
|
||
KEY \`idx_${warehouseId}_stock_id\` (\`stock_id\`),
|
||
KEY \`idx_${warehouseId}_owner_code\` (\`owner_code\`),
|
||
KEY \`idx_${warehouseId}_order_item\` (\`order_id\`, \`item_id\`),
|
||
KEY \`idx_${warehouseId}_created_at\` (\`created_at\`)
|
||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${tableComment}';
|
||
`;
|
||
|
||
await this.app.model.query(createTableSQL);
|
||
this.app.logger.info(`创建订单商品物理表成功: ${tableName}`);
|
||
}
|
||
|
||
/**
|
||
* 生成表名
|
||
* @param warehouseId
|
||
* @param type
|
||
*/
|
||
generateTableName(warehouseId, type) {
|
||
const suffix = type === 'history' ? '_history' : '';
|
||
return `wms_order_items_${warehouseId}${suffix}`;
|
||
}
|
||
|
||
/**
|
||
* 清除缓存
|
||
* @param warehouseId
|
||
* @param type
|
||
*/
|
||
clearCache(warehouseId, type) {
|
||
const cacheKey = `${warehouseId}_${type}`;
|
||
this.modelCache.delete(cacheKey);
|
||
}
|
||
|
||
/**
|
||
* 清除所有缓存
|
||
*/
|
||
clearAllCache() {
|
||
this.modelCache.clear();
|
||
}
|
||
|
||
/**
|
||
* 休眠函数
|
||
* @param ms
|
||
*/
|
||
sleep(ms) {
|
||
return new Promise(resolve => setTimeout(resolve, ms));
|
||
}
|
||
}
|
||
|
||
return new OrderItemsFactory();
|
||
};
|