WMS_MAIN/app/model/order_delivery_table_schema.js
2026-04-17 19:21:57 +08:00

522 lines
13 KiB
JavaScript

'use strict';
const MANAGED_TYPES = Object.freeze({
CURRENT: 'current',
HISTORY: 'history',
DISPATCH: 'dispatch',
OUTSOURCED: 'outsourced',
});
const TABLE_PATTERNS = Object.freeze([
{
type: MANAGED_TYPES.DISPATCH,
pattern: /^wms_order_delivery_dispatch_(\d+)$/,
},
{
type: MANAGED_TYPES.HISTORY,
pattern: /^wms_order_delivery_(\d+)_history$/,
},
{
type: MANAGED_TYPES.OUTSOURCED,
pattern: /^wms_order_delivery_(\d+)_outsourced$/,
},
{
type: MANAGED_TYPES.CURRENT,
pattern: /^wms_order_delivery_(\d+)$/,
},
]);
/**
* 规范化订单工厂管理的模型类型。
* @param {string} type 模型类型。
* @return {string} 规范化后的模型类型。
*/
function normalizeManagedType(type) {
return Object.values(MANAGED_TYPES).includes(type) ? type : MANAGED_TYPES.CURRENT;
}
/**
* 判断是否为配送域类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为配送域类型。
*/
function isDispatchType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.DISPATCH;
}
/**
* 判断是否为历史类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为历史类型。
*/
function isHistoryType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.HISTORY;
}
/**
* 判断是否为 outsourced 类型。
* @param {string} type 模型类型。
* @return {boolean} 是否为 outsourced 类型。
*/
function isOutsourcedType(type) {
return normalizeManagedType(type) === MANAGED_TYPES.OUTSOURCED;
}
/**
* 克隆模型属性定义,避免直接修改基础模型对象。
* @param {Object} attributes 原始属性定义。
* @return {Object} 克隆后的属性定义。
*/
function cloneAttributes(attributes) {
return Object.entries(attributes).reduce((result, [ name, attribute ]) => {
result[name] = { ...attribute };
return result;
}, {});
}
/**
* 规范化索引字段定义。
* @param {string|Object} field 字段定义。
* @return {{ attribute: string, length?: number }} 规范化后的字段定义。
*/
function normalizeIndexField(field) {
if (typeof field === 'string') {
return { attribute: field };
}
if (!field || typeof field !== 'object') {
return { attribute: String(field) };
}
const attribute = field.attribute || field.name || field.field || field.columnName || field.column_name;
const normalizedField = {
attribute: attribute ? String(attribute) : '',
};
if (Object.prototype.hasOwnProperty.call(field, 'length') && field.length !== undefined && field.length !== null) {
normalizedField.length = Number(field.length);
}
return normalizedField;
}
/**
* 规范化索引定义。
* @param {Object} index 索引定义。
* @return {{ name: string, unique: boolean, fields: Array<Object> }} 规范化后的索引定义。
*/
function normalizeIndexDefinition(index) {
return {
name: index.name || index.Key_name || index.key_name || '',
unique: Boolean(index.unique || index.Unique || (typeof index.nonUnique === 'number' ? index.nonUnique === 0 : false)),
fields: Array.isArray(index.fields) ? index.fields.map(normalizeIndexField) : [],
};
}
/**
* 规范化 Sequelize 数值类型的 SQL 定义。
* @param {Object} attribute Sequelize 属性定义。
* @return {{ type: string, unsigned: boolean, min: string, max: string, precision?: number, scale?: number }|null} 数值约束信息。
*/
function parseNumericConstraint(attribute) {
let typeSql = '';
if (attribute && attribute.type && typeof attribute.type.toSql === 'function') {
try {
typeSql = attribute.type.toSql();
} catch (error) {
return null;
}
} else {
typeSql = String(attribute && attribute.type || '');
}
const normalizedTypeSql = String(typeSql || '')
.trim()
.replace(/\s+/g, ' ')
.toUpperCase();
if (!normalizedTypeSql) {
return null;
}
const integerMatch = normalizedTypeSql.match(/^(TINYINT|SMALLINT|MEDIUMINT|INT|INTEGER|BIGINT)\s*(?:\(\s*\d+\s*\))?(?:\s+UNSIGNED)?$/i);
if (integerMatch) {
const integerBits = {
TINYINT: 8,
SMALLINT: 16,
MEDIUMINT: 24,
INT: 32,
INTEGER: 32,
BIGINT: 64,
}[integerMatch[1].toUpperCase()];
const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql);
const bigBits = BigInt(integerBits);
const max = unsigned
? (2n ** bigBits) - 1n
: (2n ** (bigBits - 1n)) - 1n;
const min = unsigned
? 0n
: -(2n ** (bigBits - 1n));
return {
type: integerMatch[1].toUpperCase(),
unsigned,
min: min.toString(),
max: max.toString(),
};
}
const decimalMatch = normalizedTypeSql.match(/^(DECIMAL|NUMERIC)\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)(?:\s+UNSIGNED)?$/i);
if (decimalMatch) {
const precision = Number(decimalMatch[2]);
const scale = Number(decimalMatch[3]);
const unsigned = /\bUNSIGNED\b/i.test(normalizedTypeSql);
const integerDigits = precision - scale;
if (!Number.isInteger(precision) || !Number.isInteger(scale) || precision <= 0 || scale < 0 || integerDigits <= 0) {
return null;
}
const integerPart = '9'.repeat(integerDigits);
const decimalPart = scale > 0 ? `.${'9'.repeat(scale)}` : '';
return {
type: decimalMatch[1].toUpperCase(),
unsigned,
precision,
scale,
min: `-${integerPart}${decimalPart}`,
max: `${integerPart}${decimalPart}`,
};
}
return null;
}
/**
* 生成默认值 SQL 片段。
* @param {*} defaultValue 默认值。
* @return {string} SQL 片段。
*/
function formatDefaultValue(defaultValue) {
if (defaultValue === null) {
return 'NULL';
}
if (defaultValue === undefined) {
return '';
}
if (defaultValue && typeof defaultValue.toSql === 'function') {
return defaultValue.toSql();
}
if (typeof defaultValue === 'string') {
const escaped = defaultValue.replace(/'/g, "''");
return `'${escaped}'`;
}
if (typeof defaultValue === 'number' || typeof defaultValue === 'bigint') {
return String(defaultValue);
}
if (typeof defaultValue === 'boolean') {
return defaultValue ? '1' : '0';
}
return `'${String(defaultValue).replace(/'/g, "''")}'`;
}
/**
* 将 Sequelize 属性定义转换为 DDL 列片段。
* @param {string} columnName 列名。
* @param {Object} attribute Sequelize 属性定义。
* @return {string} DDL 列片段。
*/
function buildColumnLine(columnName, attribute) {
const parts = [ `\`${columnName}\``, attribute.type && typeof attribute.type.toSql === 'function'
? attribute.type.toSql()
: String(attribute.type || ''),
];
if (attribute.allowNull === false) {
parts.push('NOT NULL');
}
if (attribute.autoIncrement) {
parts.push('AUTO_INCREMENT');
}
if (Object.prototype.hasOwnProperty.call(attribute, 'defaultValue')) {
const defaultSql = formatDefaultValue(attribute.defaultValue);
if (defaultSql) {
parts.push(`DEFAULT ${defaultSql}`);
}
}
if (attribute.comment) {
parts.push(`COMMENT '${String(attribute.comment).replace(/'/g, "''")}'`);
}
return parts.join(' ');
}
/**
* 构建模型属性定义。
* @param {Object} app Egg 应用实例。
* @param {string} type 模型类型。
* @return {Object} 属性定义。
*/
function buildTableAttributes(app, type) {
const modelType = normalizeManagedType(type);
const attributes = cloneAttributes(app.model.OrderDelivery.rawAttributes);
if (isDispatchType(modelType)) {
const { ENUM } = app.Sequelize;
attributes.dispatch_lane = {
type: ENUM('m4', 'm5'),
field: 'dispatch_lane',
allowNull: false,
defaultValue: 'm4',
comment: '配送工作台子域(M4正常/M5异常)',
};
}
if (isHistoryType(modelType)) {
attributes.archive_time = {
type: app.Sequelize.DATE,
field: 'archive_time',
allowNull: true,
defaultValue: null,
comment: '归档时间',
};
}
return attributes;
}
/**
* 构建表名。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表名。
*/
function buildTableName(warehouseId, type) {
const modelType = normalizeManagedType(type);
if (isDispatchType(modelType)) {
return `wms_order_delivery_dispatch_${warehouseId}`;
}
if (isOutsourcedType(modelType)) {
return `wms_order_delivery_${warehouseId}_outsourced`;
}
const suffix = isHistoryType(modelType) ? '_history' : '';
return `wms_order_delivery_${warehouseId}${suffix}`;
}
/**
* 构建表注释。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {string} 表注释。
*/
function buildTableComment(warehouseId, type) {
const modelType = normalizeManagedType(type);
if (isDispatchType(modelType)) {
return `仓库${warehouseId}发货单配送域(M4/M5)影子表`;
}
if (isHistoryType(modelType)) {
return `仓库${warehouseId}发货单历史表`;
}
if (isOutsourcedType(modelType)) {
return `仓库${warehouseId}发货单外仓表`;
}
return `仓库${warehouseId}发货单常用表`;
}
/**
* 构建模型选项。
* @param {Object} app Egg 应用实例。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Object} Sequelize 模型选项。
*/
function buildTableOptions(app, warehouseId, type) {
const modelType = normalizeManagedType(type);
const options = {
tableName: buildTableName(warehouseId, modelType),
timestamps: false,
comment: buildTableComment(warehouseId, modelType),
indexes: buildIndexOptions(warehouseId, modelType),
};
if (isHistoryType(modelType)) {
options.fields = Object.keys(buildTableAttributes(app, modelType));
}
return options;
}
/**
* 构建索引选项。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Array<Object>} 索引选项。
*/
function buildIndexOptions(warehouseId, type) {
const modelType = normalizeManagedType(type);
const prefix = `${warehouseId}_${modelType}`;
if (isDispatchType(modelType)) {
const baseIndexes = buildIndexOptions(warehouseId, MANAGED_TYPES.CURRENT);
const dispatchLaneIndex = {
name: `idx_dispatch_${warehouseId}_dispatch_lane`,
fields: [ 'dispatch_lane', 'status' ],
};
return [
baseIndexes[0],
baseIndexes[1],
baseIndexes[2],
dispatchLaneIndex,
...baseIndexes.slice(3),
];
}
const indexes = [
{
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: [{ attribute: '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',
],
},
];
if (isHistoryType(modelType)) {
indexes.push({
name: `idx_${warehouseId}_history_archive_time`,
fields: [ 'archive_time' ],
});
}
return indexes;
}
/**
* 将索引选项转换为 DDL 片段。
* @param {Object} index 索引定义。
* @return {string} DDL 索引片段。
*/
function buildIndexLine(index) {
const fieldParts = index.fields.map(field => {
const normalizedField = normalizeIndexField(field);
const length = Object.prototype.hasOwnProperty.call(normalizedField, 'length')
? `(${normalizedField.length})`
: '';
return `\`${normalizedField.attribute}\`${length}`;
});
const prefix = index.unique ? 'UNIQUE KEY' : 'KEY';
return `${prefix} \`${index.name}\` (${fieldParts.join(',')})`;
}
/**
* 构建表列定义行。
* @param {Object} app Egg 应用实例。
* @param {string} type 模型类型。
* @return {Array<string>} 列定义行。
*/
function buildColumnLines(app, type) {
return Object.entries(buildTableAttributes(app, type)).map(([ columnName, attribute ]) => buildColumnLine(columnName, attribute));
}
/**
* 构建表索引定义行。
* @param {number|string} warehouseId 仓库ID。
* @param {string} type 模型类型。
* @return {Array<string>} 索引定义行。
*/
function buildIndexLines(warehouseId, type) {
return buildIndexOptions(warehouseId, type).map(buildIndexLine);
}
/**
* 解析订单工厂管理的表名。
* @param {string} tableName 表名。
* @return {{ type: string, warehouseId: string }|null} 解析结果。
*/
function parseManagedTableName(tableName) {
for (const item of TABLE_PATTERNS) {
const match = item.pattern.exec(tableName);
if (match) {
return {
type: item.type,
warehouseId: match[1],
};
}
}
return null;
}
module.exports = {
MANAGED_TYPES,
normalizeManagedType,
isDispatchType,
isHistoryType,
isOutsourcedType,
normalizeIndexField,
normalizeIndexDefinition,
parseNumericConstraint,
buildTableAttributes,
buildTableName,
buildTableComment,
buildTableOptions,
buildIndexOptions,
buildColumnLines,
buildIndexLines,
parseManagedTableName,
};