524 lines
16 KiB
JavaScript
524 lines
16 KiB
JavaScript
// order_items_factory.js
|
|
'use strict';
|
|
|
|
const {
|
|
ensureShardWarehouseId,
|
|
clearShardWarehouseValidationCache,
|
|
} = require('../lib/warehouse_shard_guard');
|
|
|
|
/**
|
|
* 克隆模型属性定义。
|
|
* @param {Object} attributes 属性定义。
|
|
* @return {Object} 克隆后的属性定义。
|
|
*/
|
|
function cloneAttributes(attributes) {
|
|
return Object.entries(attributes || {}).reduce((result, [ key, value ]) => {
|
|
result[key] = { ...value };
|
|
return result;
|
|
}, {});
|
|
}
|
|
|
|
/**
|
|
* 规范化索引定义。
|
|
* @param {Object} index 索引定义。
|
|
* @return {Object} 规范化后的索引定义。
|
|
*/
|
|
function normalizeIndexDefinition(index) {
|
|
let unique = false;
|
|
|
|
if (index && Object.prototype.hasOwnProperty.call(index, 'unique')) {
|
|
unique = Boolean(index.unique);
|
|
} else if (index && Object.prototype.hasOwnProperty.call(index, 'Unique')) {
|
|
unique = Boolean(index.Unique);
|
|
} else if (index && Object.prototype.hasOwnProperty.call(index, 'nonUnique')) {
|
|
unique = Number(index.nonUnique) === 0;
|
|
}
|
|
|
|
return {
|
|
name: index && (index.name || index.Key_name || index.key_name || index.index_name) || '',
|
|
unique,
|
|
fields: Array.isArray(index && index.fields)
|
|
? index.fields.map(field => {
|
|
if (typeof field === 'string') {
|
|
return {
|
|
attribute: field,
|
|
};
|
|
}
|
|
|
|
return {
|
|
attribute: field.attribute || field.name || field.field || field.columnName || '',
|
|
length: field.length,
|
|
};
|
|
})
|
|
: [],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 判断两个索引定义是否存在结构差异。
|
|
* @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;
|
|
}
|
|
|
|
if (normalizedExpected.unique !== normalizedActual.unique) {
|
|
return true;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
module.exports = app => {
|
|
const { Sequelize } = app;
|
|
|
|
class OrderItemsFactory {
|
|
constructor() {
|
|
this.modelCache = new Map();
|
|
this.app = app;
|
|
this.creatingTables = new Map(); // 防止并发创建表
|
|
}
|
|
|
|
/**
|
|
* 获取当前表模型
|
|
* @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} warehouseId 仓库ID
|
|
* @return {Promise<Object>} 配送表模型
|
|
*/
|
|
async getDispatchModel(warehouseId) {
|
|
return await this.getOrCreateModel(warehouseId, 'dispatch');
|
|
}
|
|
|
|
/**
|
|
* 获取或创建模型
|
|
* @param {number} warehouseId 仓库ID
|
|
* @param {string} type 模型类型
|
|
* @return {Promise<Object>} 动态模型
|
|
*/
|
|
async getOrCreateModel(warehouseId, type = 'current') {
|
|
const warehouseIdStr = await ensureShardWarehouseId(this.app, warehouseId);
|
|
const cacheKey = `${warehouseIdStr}_${type}`;
|
|
|
|
// 检查缓存
|
|
if (this.modelCache.has(cacheKey)) {
|
|
return this.modelCache.get(cacheKey);
|
|
}
|
|
|
|
const tableName = this.generateTableName(warehouseIdStr, type);
|
|
|
|
try {
|
|
// 防止并发创建表
|
|
if (this.creatingTables.has(cacheKey)) {
|
|
await this.creatingTables.get(cacheKey);
|
|
return this.modelCache.get(cacheKey);
|
|
}
|
|
|
|
const createPromise = this.createModelWithRetry(warehouseIdStr, 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 {number} warehouseId 仓库ID
|
|
* @param {string} type 模型类型
|
|
* @param {string} tableName 表名
|
|
* @param {string} cacheKey 缓存键
|
|
* @param {number} retryCount 重试次数
|
|
* @return {Promise<Object>} 动态模型
|
|
*/
|
|
async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) {
|
|
for (let i = 0; i < retryCount; i++) {
|
|
try {
|
|
const DynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
|
|
|
|
// await this.ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel);
|
|
|
|
// 复制关联关系
|
|
this.copyAssociations(this.app.model.OrderItems, 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 {Object} sourceModel 源模型
|
|
* @param {Object} 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 {number|string} warehouseId 仓库ID。
|
|
* @param {string} type 模型类型。
|
|
* @param {string} tableName 表名。
|
|
* @return {Object} 动态模型。
|
|
*/
|
|
buildDynamicModel(warehouseId, type, tableName) {
|
|
const attributes = this.getTableAttributes(type);
|
|
const modelComment = type === 'history'
|
|
? `仓库${warehouseId}订单商品历史表`
|
|
: type === 'dispatch'
|
|
? `仓库${warehouseId}订单商品配送表`
|
|
: `仓库${warehouseId}订单商品常用表`;
|
|
|
|
return this.app.model.define(tableName, attributes, {
|
|
tableName,
|
|
timestamps: true,
|
|
underscored: true,
|
|
paranoid: false,
|
|
indexes: this.generateIndexes(warehouseId),
|
|
comment: modelComment,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 获取订单商品模型属性定义。
|
|
* @param {string} type 模型类型。
|
|
* @return {Object} 属性定义。
|
|
*/
|
|
getTableAttributes(type) {
|
|
const mainModel = this.app.model.OrderItems;
|
|
const attributes = cloneAttributes(mainModel && mainModel.rawAttributes);
|
|
|
|
if (attributes.id) {
|
|
delete attributes.id.autoIncrement;
|
|
}
|
|
|
|
if (type === 'history' && !attributes.archive_time) {
|
|
attributes.archive_time = {
|
|
type: this.app.Sequelize.DATE,
|
|
allowNull: true,
|
|
defaultValue: this.app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
|
comment: '归档时间',
|
|
};
|
|
}
|
|
|
|
return attributes;
|
|
}
|
|
|
|
/**
|
|
* 生成索引配置
|
|
* @param {number} warehouseId 仓库ID
|
|
*/
|
|
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 {string} 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 Array.isArray(results)
|
|
? results.length > 0
|
|
: Boolean(results);
|
|
} catch (error) {
|
|
this.app.logger.error('检查表是否存在失败:', error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 判断目标表是否需要进行结构同步。
|
|
* @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.generateIndexes(warehouseId);
|
|
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 模型类型。
|
|
* @param {number|string} warehouseId 仓库ID。
|
|
* @param {Object} [DynamicModel] 已构建的动态模型。
|
|
* @return {Promise<boolean>} 是否执行了同步。
|
|
*/
|
|
async ensureManagedTableSchema(tableName, type, warehouseId, DynamicModel = null) {
|
|
const dynamicModel = DynamicModel || this.buildDynamicModel(warehouseId, type, tableName);
|
|
const tableExists = await this.checkTableExists(tableName);
|
|
const needsSync = tableExists
|
|
? await this.needsTableSchemaSync(tableName, type, warehouseId, tableExists)
|
|
: true;
|
|
|
|
if (!needsSync) {
|
|
return false;
|
|
}
|
|
|
|
await dynamicModel.sync({ alter: true });
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* 创建物理表。
|
|
* @param {number} warehouseId 仓库ID
|
|
* @param {string} type 模型类型
|
|
*/
|
|
async createPhysicalTable(warehouseId, type = 'current') {
|
|
const tableName = this.generateTableName(warehouseId, type);
|
|
const dynamicModel = this.buildDynamicModel(warehouseId, type, tableName);
|
|
|
|
await dynamicModel.sync({ alter: true });
|
|
this.app.logger.info(`创建/同步订单商品物理表成功: ${tableName}`);
|
|
}
|
|
|
|
/**
|
|
* 生成表名
|
|
* @param {number} warehouseId 仓库ID
|
|
* @param {string} type 模型类型
|
|
*/
|
|
generateTableName(warehouseId, type) {
|
|
const suffix = type === 'history'
|
|
? '_history'
|
|
: type === 'dispatch'
|
|
? '_dispatch'
|
|
: '';
|
|
return `wms_order_items_${warehouseId}${suffix}`;
|
|
}
|
|
|
|
/**
|
|
* 清除缓存
|
|
* @param {number} warehouseId 仓库ID
|
|
* @param {string} type 模型类型
|
|
*/
|
|
clearCache(warehouseId, type) {
|
|
const cacheKey = `${warehouseId}_${type}`;
|
|
this.modelCache.delete(cacheKey);
|
|
this.creatingTables.delete(cacheKey);
|
|
clearShardWarehouseValidationCache(this.app);
|
|
}
|
|
|
|
/**
|
|
* 清除所有缓存
|
|
*/
|
|
clearAllCache() {
|
|
this.modelCache.clear();
|
|
this.creatingTables.clear();
|
|
clearShardWarehouseValidationCache(this.app);
|
|
}
|
|
|
|
/**
|
|
* 休眠函数
|
|
* @param {number} ms 毫秒数
|
|
*/
|
|
sleep(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
}
|
|
|
|
return new OrderItemsFactory();
|
|
};
|