WMS_MAIN/app/model/store.js

428 lines
12 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, STRING, DATE, TINYINT, JSON: JSON_TYPE } = app.Sequelize;
const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5;
const DEFAULT_MAX_WAVE_QUANTITY = 500;
const DEFAULT_SUBJECT_CONFIG = Object.freeze({
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY,
min_group_order_fetch_quantity: 13,
default_express_code: 'STO',
default_platform_code: 'TB',
group_wave_prefix: 'B',
delete_order_wave_prefix: 'A',
});
const normalizeSubjectConfigText = (value, defaultValue) => {
if (value === undefined || value === null) {
return defaultValue;
}
const normalized = String(value).trim();
return normalized === '' ? defaultValue : normalized;
};
const normalizeBooleanFlag = (value, fieldName) => {
if (value === undefined || value === null || value === '') {
return undefined;
}
if ([ true, 1, '1', 'true' ].includes(value)) {
return true;
}
if ([ false, 0, '0', 'false' ].includes(value)) {
return false;
}
throw new Error(`${fieldName} 必须是布尔值`);
};
/**
* 规范化主体配置,确保默认值与字段约束一致。
*
* @param {Object|string|null|undefined} rawValue 主体配置原始值。
* @return {Object} 规范化后的主体配置对象。
*/
const normalizeSubjectConfig = rawValue => {
if (rawValue === undefined || rawValue === null || rawValue === '') {
return { ...DEFAULT_SUBJECT_CONFIG };
}
let parsed = rawValue;
if (typeof parsed === 'string') {
try {
parsed = JSON.parse(parsed);
} catch (error) {
throw new Error('subject_config 必须是合法 JSON 对象');
}
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('subject_config 必须是对象');
}
const normalized = {
...parsed,
};
const rawLimit = parsed.max_notice_webhook_count;
if (rawLimit === undefined || rawLimit === null || rawLimit === '') {
normalized.max_notice_webhook_count = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT;
} else {
const limit = Number(rawLimit);
if (!Number.isInteger(limit) || limit < 0 || limit > DEFAULT_MAX_NOTICE_WEBHOOK_COUNT) {
throw new Error(`subject_config.max_notice_webhook_count 必须是 0-${DEFAULT_MAX_NOTICE_WEBHOOK_COUNT} 的整数`);
}
normalized.max_notice_webhook_count = limit;
}
const rawMaxWaveQuantity = parsed.max_wave_quantity;
if (rawMaxWaveQuantity === undefined || rawMaxWaveQuantity === null || rawMaxWaveQuantity === '') {
normalized.max_wave_quantity = DEFAULT_MAX_WAVE_QUANTITY;
} else {
const maxWaveQuantity = Number(rawMaxWaveQuantity);
if (!Number.isInteger(maxWaveQuantity) || maxWaveQuantity <= 0) {
throw new Error('subject_config.max_wave_quantity 必须是大于 0 的整数');
}
normalized.max_wave_quantity = maxWaveQuantity;
}
const rawMinGroupOrderFetchQuantity = parsed.min_group_order_fetch_quantity;
if (rawMinGroupOrderFetchQuantity === undefined || rawMinGroupOrderFetchQuantity === null || rawMinGroupOrderFetchQuantity === '') {
normalized.min_group_order_fetch_quantity = DEFAULT_SUBJECT_CONFIG.min_group_order_fetch_quantity;
} else {
const minGroupOrderFetchQuantity = Number(rawMinGroupOrderFetchQuantity);
if (!Number.isInteger(minGroupOrderFetchQuantity) || minGroupOrderFetchQuantity <= 0) {
throw new Error('subject_config.min_group_order_fetch_quantity 必须是大于 0 的整数');
}
normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity;
}
normalized.default_express_code = normalizeSubjectConfigText(
parsed.default_express_code,
DEFAULT_SUBJECT_CONFIG.default_express_code
);
normalized.default_platform_code = normalizeSubjectConfigText(
parsed.default_platform_code,
DEFAULT_SUBJECT_CONFIG.default_platform_code
);
const rawGroupWavePrefix = parsed.group_wave_prefix;
if (rawGroupWavePrefix === undefined || rawGroupWavePrefix === null || rawGroupWavePrefix === '') {
normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix;
} else {
const groupWavePrefix = String(rawGroupWavePrefix).trim();
if (groupWavePrefix === '') {
normalized.group_wave_prefix = DEFAULT_SUBJECT_CONFIG.group_wave_prefix;
} else {
if (groupWavePrefix.length > 5) {
throw new Error('subject_config.group_wave_prefix 最多 5 个字符');
}
normalized.group_wave_prefix = groupWavePrefix;
}
}
const rawDeleteOrderWavePrefix = parsed.delete_order_wave_prefix;
if (rawDeleteOrderWavePrefix === undefined || rawDeleteOrderWavePrefix === null || rawDeleteOrderWavePrefix === '') {
normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix;
} else {
const deleteOrderWavePrefix = String(rawDeleteOrderWavePrefix).trim();
if (deleteOrderWavePrefix === '') {
normalized.delete_order_wave_prefix = DEFAULT_SUBJECT_CONFIG.delete_order_wave_prefix;
} else {
if (deleteOrderWavePrefix.length > 5) {
throw new Error('subject_config.delete_order_wave_prefix 最多 5 个字符');
}
normalized.delete_order_wave_prefix = deleteOrderWavePrefix;
}
}
if (Object.prototype.hasOwnProperty.call(parsed, 'webhook_enabled')) {
normalized.webhook_enabled = normalizeBooleanFlag(parsed.webhook_enabled, 'subject_config.webhook_enabled');
}
if (Object.prototype.hasOwnProperty.call(parsed, 'callback_strategy')) {
const strategy = String(parsed.callback_strategy || '').trim().toLowerCase();
if (strategy && ![ 'sync', 'async' ].includes(strategy)) {
throw new Error('subject_config.callback_strategy 仅支持 sync 或 async');
}
normalized.callback_strategy = strategy || 'async';
}
return normalized;
};
const Store = app.model.define('store', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '商家ID',
},
company_name: {
type: STRING(200),
allowNull: false,
unique: true,
validate: {
notEmpty: {
msg: '公司全称不能为空',
},
len: {
args: [ 1, 200 ],
msg: '公司全称长度应在1-200个字符之间',
},
},
comment: '公司全称',
},
business_license: {
type: STRING(100),
allowNull: true,
unique: true,
comment: '营业执照号',
},
legal_person: {
type: STRING(50),
allowNull: true,
comment: '法人代表',
},
contact_phone: {
type: STRING(20),
allowNull: false,
validate: {
notEmpty: {
msg: '联系电话不能为空',
},
is: {
args: /^[0-9+\-()\s]+$/,
msg: '请输入有效的联系电话',
},
},
comment: '联系电话',
},
contact_email: {
type: STRING(100),
allowNull: true,
comment: '联系邮箱',
},
contact_person: {
type: STRING(50),
allowNull: false,
validate: {
notEmpty: {
msg: '联系人不能为空',
},
len: {
args: [ 1, 50 ],
msg: '联系人姓名长度应在1-50个字符之间',
},
},
comment: '联系人',
},
address: {
type: STRING(500),
allowNull: true,
comment: '公司地址',
},
industry: {
type: STRING(100),
allowNull: true,
comment: '所属行业',
},
account_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '关联账号ID(商家管理员)',
},
status: {
type: TINYINT(4),
allowNull: false,
defaultValue: 1,
validate: {
isIn: {
args: [[ 0, 1, 2 ]],
msg: '状态值不合法,0-禁用,1-启用,2-审核中',
},
},
comment: '状态:0-禁用,1-启用,2-审核中',
},
created_by: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '创建人',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
logo_url: {
type: STRING(255),
allowNull: true,
comment: 'logo链接',
},
project: {
type: STRING(20),
allowNull: true,
comment: '应用',
},
domain: {
type: STRING(100),
allowNull: true,
comment: '绑定域名',
},
auth_end: {
type: DATE,
allowNull: true,
comment: '授权结束时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '删除时间',
},
quota_bytes: {
type: BIGINT.UNSIGNED,
allowNull: false,
defaultValue: 107374182400,
comment: '仓库文件存储配额',
},
subject_config: {
type: JSON_TYPE,
allowNull: true,
defaultValue: { ...DEFAULT_SUBJECT_CONFIG },
comment: '主体配置JSON',
get() {
return normalizeSubjectConfig(this.getDataValue('subject_config'));
},
set(value) {
this.setDataValue('subject_config', normalizeSubjectConfig(value));
},
validate: {
isValidSubjectConfig(value) {
normalizeSubjectConfig(value);
},
},
},
}, {
tableName: 'wms_store',
freezeTableName: true,
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '商家表',
indexes: [
{
name: 'uk_company_name',
fields: [ 'company_name' ],
unique: true,
},
{
name: 'uk_business_license',
fields: [ 'business_license' ],
unique: true,
},
{
name: 'idx_status',
fields: [ 'status' ],
},
{
name: 'idx_account_id',
fields: [ 'account_id' ],
},
],
});
// 关联关系 - 使用您推荐的方式
Store.associate = function() {
const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model;
// 关联创建人
Store.belongsTo(Account, {
foreignKey: 'created_by',
as: 'creator',
});
// 关联商家管理员账号
Store.belongsTo(Account, {
foreignKey: 'account_id',
as: 'adminAccount',
});
// 关联商家拥有的角色
Store.hasMany(Role, {
foreignKey: 'store_id',
as: 'roles',
});
// 关联商家拥有的账号员工关联
Store.hasMany(AccountStoreEmployee, {
foreignKey: 'store_id',
as: 'accountStoreEmployees',
});
Store.hasMany(ProhibitedType, {
foreignKey: 'warehouse_id',
as: 'prohibitedTypes',
});
Store.hasMany(NotificationWebhook, {
foreignKey: 'store_id',
as: 'notificationWebhooks',
});
};
Store.DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = DEFAULT_MAX_NOTICE_WEBHOOK_COUNT;
Store.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG;
Store.normalizeSubjectConfig = normalizeSubjectConfig;
// 实例方法:检查商家是否启用
Store.prototype.isEnabled = function() {
return this.status === 1;
};
// 实例方法:检查商家是否审核中
Store.prototype.isReviewing = function() {
return this.status === 2;
};
// 实例方法:检查是否是仓库
Store.prototype.isWarehouse = function() {
return this.project === 'warehouse';
};
// 实例方法:检查授权是否有效
Store.prototype.isAuthValid = function() {
if (!this.auth_start || !this.auth_end) {
return true; // 如果没有设置授权时间,默认有效
}
const now = new Date();
return now >= new Date(this.auth_start) && now <= new Date(this.auth_end);
};
// 实例方法:检查邮箱是否有效
Store.prototype.hasValidEmail = function() {
if (!this.contact_email) {
return false;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(this.contact_email);
};
return Store;
};