WMS_MAIN/app/model/store_warehouse.js
liufumingren 14a5f13ad5 feat(db): wms_store_warehouse 新增 initiator_subject_id,wms_picking 新增 stock_id 及联合索引
- wms_store_warehouse: 新增 initiator_subject_id 记录发起方主体ID

- wms_picking: 新增 stock_id 字段 + idx_wms_picking_warehouse_stock 联合索引 + 历史数据回填

- Model 层同步更新关联定义
2026-07-09 03:36:03 +08:00

818 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
module.exports = app => {
const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize;
const POLICY_CONFIG_FIELDS = Object.freeze([
Object.freeze({
key: 'auto_allocate_bin',
name: '自动分配库位',
type: 'flag',
default: 0,
required: false,
description: '收货上架时是否自动推荐库位',
}),
Object.freeze({
key: 'auto_allocate_express',
name: '是否自动分配快递',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否自动分配快递',
}),
Object.freeze({
key: 'auto_allocate_storage',
name: '是否自动分配储位',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否自动分配储位',
}),
Object.freeze({
key: 'allow_receiving_quick_putaway',
name: '收货单快捷入库',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否允许使用收货单快捷入库',
}),
Object.freeze({
key: 'allow_mix_batch',
name: '允许混批',
type: 'flag',
default: 0,
required: false,
description: '是否允许不同批次混合存放',
}),
Object.freeze({
key: 'allow_temp_storage',
name: '允许临时存放',
type: 'flag',
default: 0,
required: false,
description: '是否允许进入临时存放区',
}),
Object.freeze({
key: 'storage_separation',
name: '是否存储分离',
type: 'flag',
default: 1,
required: false,
description: '控制该货主在当前仓库下是否按独立存储策略管理库存',
}),
Object.freeze({
key: 'allow_oversell',
name: '允许超卖',
type: 'flag',
default: 0,
required: false,
description: '是否允许该货主在当前仓库下锁定超过可用库存',
}),
Object.freeze({
key: 'express_quota',
name: '快递号额度',
type: 'integer',
default: 0,
required: false,
description: '允许在快递余额之外额外分配的快递号数量',
min: 0,
max: 1000000,
}),
Object.freeze({
key: 'need_order_approval',
name: '推送订单需审批',
type: 'flag',
default: 1,
required: false,
description: '控制货主推送订单创建后是否必须进入审批流程',
}),
Object.freeze({
key: 'auto_sync_back',
name: '自动同步回传',
type: 'flag',
default: 1,
required: false,
description: '快递号分配成功后是否自动同步订单信息到外部系统(奇门/API/手动)',
}),
Object.freeze({
key: 'enable_external_express_code',
name: '启用外部快递编码',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否允许使用外部快递编码,为否的时候默认使用下方的默认快递',
}),
Object.freeze({
key: 'default_express_code',
name: '默认快递',
type: 'list',
default: 'STO',
required: false,
description: '货主在当前仓下默认使用的快递编码',
}),
Object.freeze({
key: 'default_platform_code',
name: '默认平台',
type: 'list',
default: 'TB',
required: false,
description: '货主在当前仓下默认使用的平台编码',
}),
Object.freeze({
key: 'sender_name',
name: '发件人姓名',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的默认发件人姓名',
maxLength: 50,
}),
Object.freeze({
key: 'sender_tel',
name: '发件人电话',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的默认发件人联系电话',
maxLength: 20,
}),
Object.freeze({
key: 'province_name',
name: '省份',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的发件省份',
maxLength: 50,
}),
Object.freeze({
key: 'city_name',
name: '城市',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的发件城市',
maxLength: 50,
}),
Object.freeze({
key: 'district_name',
name: '区/县',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的发件区/县',
maxLength: 50,
}),
Object.freeze({
key: 'town_name',
name: '镇/街道',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的发件镇/街道',
maxLength: 50,
}),
Object.freeze({
key: 'address',
name: '详细地址',
type: 'string',
default: '',
required: false,
description: '货主在当前仓下面单的发件详细地址',
maxLength: 200,
}),
Object.freeze({
key: 'waybill_custom_display_type',
name: '面单自定义显示类型',
type: 'enum',
default: '1',
required: false,
description: '控制面单自定义区商品信息展示内容',
options: [
Object.freeze({ value: '1', label: '隐藏' }),
Object.freeze({ value: '2', label: '商品名称和数量' }),
Object.freeze({ value: '3', label: '拣货库位和条码和数量' }),
Object.freeze({ value: '4', label: '拣货库位和条码后5位和数量' }),
Object.freeze({ value: '5', label: '拣货库位商品名称条码和数量' }),
],
}),
Object.freeze({
key: 'cutoff_order_enabled',
name: '启用截单',
type: 'flag',
default: 1,
required: false,
description: '启用后,当天订单创建时间超过截单时间,不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'cutoff_order_time',
name: '截单时间',
type: 'string',
default: '18:00',
required: false,
maxLength: 5,
min: '12:00',
max: '23:59',
description: '截单时间,格式 HH:mm,如 16:00',
}),
]);
const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => {
result[field.key] = field;
return result;
}, {}));
const clonePolicyConfigOptions = options => {
if (!Array.isArray(options)) {
return undefined;
}
return options.map(option => {
if (!option || typeof option !== 'object') {
return option;
}
return { ...option };
});
};
const getPolicyConfigOptionValue = option => {
if (option && typeof option === 'object') {
if (option.value !== undefined && option.value !== null) {
return String(option.value);
}
if (option.code !== undefined && option.code !== null) {
return String(option.code);
}
if (option.key !== undefined && option.key !== null) {
return String(option.key);
}
}
return String(option);
};
const clonePolicyConfigField = field => ({
key: field.key,
name: field.name,
type: field.type,
default: field.default,
required: field.required,
description: field.description,
...(Array.isArray(field.options) ? { options: clonePolicyConfigOptions(field.options) } : {}),
...(field.min !== undefined ? { min: field.min } : {}),
...(field.max !== undefined ? { max: field.max } : {}),
...(field.precision !== undefined ? { precision: field.precision } : {}),
...(field.step !== undefined ? { step: field.step } : {}),
...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}),
});
const normalizePolicyConfigOptionValue = option => {
if (!option || typeof option !== 'object') {
return String(option);
}
if (option.value !== undefined && option.value !== null) {
return String(option.value);
}
if (option.code !== undefined && option.code !== null) {
return String(option.code);
}
if (option.key !== undefined && option.key !== null) {
return String(option.key);
}
return '';
};
const parsePolicyConfig = (value, fieldName = 'policy_config') => {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch (error) {
throw new Error(`${fieldName} 不是合法JSON`);
}
}
return value;
};
const normalizePolicyConfig = (value, options = {}) => {
const {
fieldName = 'policy_config',
allowEmpty = false,
sanitizeOnly = false,
} = options;
if (value === undefined || value === null || value === '') {
if (allowEmpty) {
return null;
}
throw new Error(`${fieldName} 参数不能为空`);
}
const parsed = parsePolicyConfig(value, fieldName);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`${fieldName} 必须为对象`);
}
const supportedKeys = Object.keys(POLICY_CONFIG_FIELD_MAP);
const unsupportedKeys = Object.keys(parsed).filter(key => !POLICY_CONFIG_FIELD_MAP[key]);
if (unsupportedKeys.length && !sanitizeOnly) {
throw new Error(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${supportedKeys.join(', ')}`);
}
const normalized = {};
for (const field of POLICY_CONFIG_FIELDS) {
if (!Object.prototype.hasOwnProperty.call(parsed, field.key)) {
continue;
}
const rawValue = parsed[field.key];
if (rawValue === undefined || rawValue === null || rawValue === '') {
if (field.type === 'string') {
normalized[field.key] = '';
}
continue;
}
try {
if (field.type === 'enum') {
const valueText = String(rawValue).trim();
const allowedValues = Array.isArray(field.options)
? field.options.map(getPolicyConfigOptionValue)
: [];
if (!allowedValues.includes(valueText)) {
throw new Error(`${fieldName}.${field.key} 参数不合法`);
}
normalized[field.key] = valueText;
continue;
}
if (field.type === 'list') {
const valueText = String(rawValue).trim();
if (valueText) {
normalized[field.key] = valueText;
}
continue;
}
if (field.type === 'flag') {
if (rawValue === true || rawValue === 1 || rawValue === '1') {
normalized[field.key] = 1;
continue;
}
if (rawValue === false || rawValue === 0 || rawValue === '0') {
normalized[field.key] = 0;
continue;
}
throw new Error(`${fieldName}.${field.key} 参数不合法`);
}
if (field.type === 'integer') {
const num = Number(rawValue);
if (!Number.isFinite(num) || num < field.min || num > field.max) {
throw new Error(`${fieldName}.${field.key} 参数不合法`);
}
normalized[field.key] = Math.floor(num);
continue;
}
if (field.type === 'number') {
const num = Number(rawValue);
if (!Number.isFinite(num) || num < field.min || num > field.max) {
throw new Error(`${fieldName}.${field.key} 参数不合法`);
}
const precision = Number.isInteger(field.precision) ? field.precision : 2;
const factor = 10 ** precision;
normalized[field.key] = Math.round(num * factor) / factor;
continue;
}
if (field.type === 'string') {
const text = String(rawValue).trim();
if (text.length > field.maxLength) {
throw new Error(`${fieldName}.${field.key} 长度不能超过 ${field.maxLength}`);
}
// 时间类型字符串范围校验
if (field.min !== undefined && field.max !== undefined && text !== '' && (text < field.min || text > field.max)) {
normalized[field.key] = field.default !== undefined ? String(field.default) : '';
} else {
normalized[field.key] = text;
}
}
} catch (error) {
if (!sanitizeOnly) {
throw error;
}
}
}
return Object.keys(normalized).length ? normalized : null;
};
const StoreWarehouse = app.model.define('store_warehouse', {
id: {
type: BIGINT(20),
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '授权ID',
},
store_id: {
type: BIGINT(20),
allowNull: false,
comment: '商家ID',
references: {
model: 'store',
key: 'id',
},
},
warehouse_id: {
type: BIGINT(20),
allowNull: false,
comment: '仓库ID',
references: {
model: 'store',
key: 'id',
},
},
auth_status: {
type: TINYINT(4),
allowNull: false,
defaultValue: 1,
validate: {
isIn: [[ 1, 2, 3, 4, 5 ]], // 1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期
},
comment: '授权状态:1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期',
},
apply_reason: {
type: TEXT,
allowNull: true,
comment: '申请理由',
},
review_comment: {
type: TEXT,
allowNull: true,
comment: '审核意见',
},
apply_time: {
type: DATE,
allowNull: false,
comment: '申请时间',
},
print_quantity: {
type: INTEGER(11),
allowNull: false,
comment: '面单余额',
},
print_quantity_locked: {
type: INTEGER(11),
allowNull: false,
comment: '面单锁定余额',
},
review_time: {
type: DATE,
allowNull: true,
comment: '审核时间',
},
auth_start: {
type: DATE,
allowNull: true,
comment: '授权开始日期',
},
auth_end: {
type: DATE,
allowNull: true,
comment: '授权结束日期',
},
actual_end: {
type: DATE,
allowNull: true,
comment: '实际结束时间',
},
applied_by: {
type: BIGINT(20),
allowNull: false,
comment: '申请人',
},
reviewed_by: {
type: BIGINT(20),
allowNull: true,
comment: '审核人',
},
ended_by: {
type: BIGINT(20),
allowNull: true,
comment: '解除人',
},
initiator_subject_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '发起方主体ID(wms_store.id)',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
store_remask: {
type: STRING(50),
allowNull: true,
validate: {
len: [ 0, 50 ],
},
comment: '商家备注',
},
warehouse_remask: {
type: STRING(50),
allowNull: true,
validate: {
len: [ 0, 50 ],
},
comment: '仓库备注',
},
policy_config: {
type: JSON_TYPE,
allowNull: true,
defaultValue: null,
comment: '货主在仓库下的固定策略配置(JSON)',
get() {
return normalizePolicyConfig(this.getDataValue('policy_config'), {
fieldName: 'policy_config',
allowEmpty: true,
sanitizeOnly: true,
});
},
set(value) {
this.setDataValue('policy_config', normalizePolicyConfig(value, {
fieldName: 'policy_config',
allowEmpty: true,
}));
},
},
warehouse_use_status: {
type: INTEGER(1),
allowNull: false,
defaultValue: 1,
comment: '仓库侧使用状态:0-不可用,1-可用',
},
store_use_status: {
type: INTEGER(1),
allowNull: false,
defaultValue: 1,
comment: '货主侧使用状态:0-不可用,1-可用',
},
}, {
tableName: 'wms_store_warehouse',
freezeTableName: true,
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
comment: '商家仓库授权关系表',
indexes: [
{
name: 'uk_store_warehouse',
unique: true,
fields: [ 'store_id', 'warehouse_id' ],
},
{
name: 'idx_store_id',
fields: [ 'store_id' ],
},
{
name: 'idx_warehouse_id',
fields: [ 'warehouse_id' ],
},
{
name: 'idx_auth_status',
fields: [ 'auth_status' ],
},
{
name: 'idx_apply_time',
fields: [ 'apply_time' ],
},
{
name: 'idx_auth_period',
fields: [ 'auth_start', 'auth_end' ],
},
{
name: 'idx_applied_by',
fields: [ 'applied_by' ],
},
{
name: 'idx_reviewed_by',
fields: [ 'reviewed_by' ],
},
{
name: 'idx_auth_end',
fields: [ 'auth_end' ],
},
{
name: 'idx_status_apply_time',
fields: [ 'auth_status', 'apply_time' ],
},
],
});
// 定义关联关系
StoreWarehouse.associate = function() {
const { Store, Account, StockWarehouse, Receiving, StoreWarehousePrintQuantityLog } = app.model;
// 授权关系属于商家
StoreWarehouse.belongsTo(Store, {
foreignKey: 'store_id',
targetKey: 'id',
as: 'store',
});
// 授权关系属于仓库
StoreWarehouse.belongsTo(Store, {
foreignKey: 'warehouse_id',
targetKey: 'id',
as: 'warehouse',
});
// 申请人
StoreWarehouse.belongsTo(Account, {
foreignKey: 'applied_by',
targetKey: 'id',
as: 'applicant',
});
// 审核人
StoreWarehouse.belongsTo(Account, {
foreignKey: 'reviewed_by',
targetKey: 'id',
as: 'reviewer',
});
// store_id 在业务上需要与 warehouse_id 联合约束,模型层不声明单列外键约束。
StoreWarehouse.hasMany(StockWarehouse, {
foreignKey: 'store_id',
targetKey: 'store_id',
as: 'store_stock',
constraints: false,
});
// 解除人
StoreWarehouse.belongsTo(Account, {
foreignKey: 'ended_by',
targetKey: 'id',
as: 'end_user',
});
// receiving 同样依赖 store_id + warehouse_id 的复合语义。
StoreWarehouse.hasMany(Receiving, {
foreignKey: 'store_id',
as: 'receiving',
constraints: false,
});
StoreWarehouse.hasMany(StoreWarehousePrintQuantityLog, {
foreignKey: 'contract_id',
sourceKey: 'id',
as: 'print_quantity_logs',
constraints: false,
});
};
StoreWarehouse.getPolicyConfigFieldList = function() {
return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField);
};
StoreWarehouse.getPolicyConfigFieldListWithOptions = async function() {
const fieldList = this.getPolicyConfigFieldList();
const [ expressRows, platformRows ] = await Promise.all([
app.model.Express && typeof app.model.Express.findAll === 'function'
? app.model.Express.findAll({
attributes: [ 'code', 'name' ],
order: [[ 'code', 'ASC' ]],
})
: Promise.resolve([]),
app.model.Platform && typeof app.model.Platform.findAll === 'function'
? app.model.Platform.findAll({
attributes: [ 'code', 'name' ],
order: [[ 'code', 'ASC' ]],
})
: Promise.resolve([]),
]);
const optionMap = {
default_express_code: expressRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
default_platform_code: platformRows.map(item => ({
value: normalizePolicyConfigOptionValue(item),
label: String(item.name || item.code || ''),
})),
};
return fieldList.map(field => {
const options = optionMap[field.key];
if (!options) {
return field;
}
return {
...field,
options,
};
});
};
StoreWarehouse.normalizePolicyConfig = function(value, options = {}) {
return normalizePolicyConfig(value, options);
};
// 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
StoreWarehouse.buildScopedWhere = function(options = {}) {
const {
warehouseId,
storeId,
warehouseUseStatus = 1,
} = options;
const where = {
warehouse_use_status: warehouseUseStatus,
};
if (warehouseId !== undefined && warehouseId !== null) {
where.warehouse_id = warehouseId;
}
if (storeId !== undefined && storeId !== null) {
where.store_id = storeId;
}
return where;
};
// 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
StoreWarehouse.buildStoreStockInclude = function(options = {}) {
const {
warehouseId,
storeId,
required = false,
warehouseUseStatus = 1,
attributes = [ 'store_id', 'store_remask' ],
} = options;
return {
model: this,
as: 'store_stock',
attributes,
where: this.buildScopedWhere({
warehouseId,
storeId,
warehouseUseStatus,
}),
required,
};
};
// 实例方法 - 检查授权是否有效
StoreWarehouse.prototype.isAuthValid = function() {
if (this.auth_status !== 2) return false; // 只有已通过状态才有效
if (!this.auth_start || !this.auth_end) return false;
const now = new Date();
const start = new Date(this.auth_start);
const end = new Date(this.auth_end);
return now >= start && now <= end;
};
// 实例方法 - 检查授权是否即将过期(30天内)
StoreWarehouse.prototype.isExpiringSoon = function() {
if (this.auth_status !== 2 || !this.auth_end) return false;
const now = new Date();
const end = new Date(this.auth_end);
const daysUntilExpire = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
return daysUntilExpire <= 30 && daysUntilExpire > 0;
};
// 实例方法 - 获取授权剩余天数
StoreWarehouse.prototype.getRemainingDays = function() {
if (!this.isAuthValid()) return 0;
const now = new Date();
const end = new Date(this.auth_end);
const diffTime = end - now;
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
};
return StoreWarehouse;
};