'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 INVENTORY_WARNING_RULE_COLOR_MAP = Object.freeze({ 1: '#ff4d4f', 2: '#ff7a45', 3: '#faad14', 4: '#fadb14', 5: '#95de64', 6: '#52c41a', }); const DEFAULT_INVENTORY_WARNING_RULES = Object.freeze([ Object.freeze({ name: '01级', key: INVENTORY_WARNING_RULE_COLOR_MAP[1], expire_days: 0, tip_text: '立即报废' }), Object.freeze({ name: '02级', key: INVENTORY_WARNING_RULE_COLOR_MAP[2], expire_days: 30, tip_text: '优先处理' }), Object.freeze({ name: '03级', key: INVENTORY_WARNING_RULE_COLOR_MAP[3], expire_days: 90, tip_text: '尽快处理' }), Object.freeze({ name: '04级', key: INVENTORY_WARNING_RULE_COLOR_MAP[4], expire_days: 180, tip_text: '建议处理' }), Object.freeze({ name: '05级', key: INVENTORY_WARNING_RULE_COLOR_MAP[5], expire_days: 365, tip_text: '库存关注' }), Object.freeze({ name: '06级', key: INVENTORY_WARNING_RULE_COLOR_MAP[6], expire_days: 999999, tip_text: '常规监控' }), ]); /** * 获取库存预警默认规则(深拷贝)。 * * @return {Array} 默认库存预警规则。 */ const getDefaultInventoryWarningRules = () => DEFAULT_INVENTORY_WARNING_RULES.map(rule => ({ ...rule })); const DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME = '06:00'; const DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME = '22:00'; // 自动出库开关:独立字段,默认关闭 const DEFAULT_AUTO_OUTBOUND_ENABLED = false; // 自动出库规则:数组,默认空数组(空数组 = 不出库任何订单);每项规则独立判断,任一命中即出库 const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze([]); /** * 获取自动出库规则默认值(新数组,避免共享冻结数组引用)。 * * @return {Array} 默认自动出库规则数组。 */ const getDefaultAutoOutboundRules = () => []; const DEFAULT_CUTOFF_ORDER_TIME = '18:00'; const CUTOFF_ORDER_TIME_MIN = '00:00'; const CUTOFF_ORDER_TIME_MAX = '23:59'; const DEFAULT_ALLOCATE_START_TIME = '08:00'; const ALLOCATE_START_TIME_MIN = '00:00'; const ALLOCATE_START_TIME_MAX = '23:59'; // 自然日开始时间(业务日分界点):今日统计窗口 = [该时间点, 次日该时间点) const DEFAULT_DAY_START_TIME = '06:00'; const DAY_START_TIME_MIN = '00:00'; const DAY_START_TIME_MAX = '23:59'; // 收货未入库提醒:默认关闭,开启后每天按 notice_time 扫描超时未入库的收货单 const DEFAULT_PENDING_RECEIVING_NOTICE_TIME = '08:30'; const DEFAULT_PENDING_RECEIVING_MIN_HOURS = 24; const DEFAULT_PENDING_RECEIVING_MAX_HOURS = 48; const PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH = 500; const DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; const DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; const DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE = Object.freeze({ enabled: false, notice_time: DEFAULT_PENDING_RECEIVING_NOTICE_TIME, min_hours: DEFAULT_PENDING_RECEIVING_MIN_HOURS, max_hours: DEFAULT_PENDING_RECEIVING_MAX_HOURS, notice_template: DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, store_notice_template: DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, }); // 站内信推送失败自动重发:默认关闭(未配置的仓库不重发,需在仓库设置中显式开启); // 开启后仅重发「失败时间在 window_minutes 内」的消息(超窗口不再补发) const DEFAULT_INBOX_PUSH_RETRY = Object.freeze({ enabled: false, window_minutes: 30, }); const INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN = 1; const INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX = 1440; 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, auto_allocate_express_exclude_remarks: [], default_express_code: 'STO', default_platform_code: 'TB', sender_name: '', sender_tel: '', province_name: '', city_name: '', district_name: '', town_name: '', address: '', receiver_address: '', group_wave_prefix: 'B', delete_order_wave_prefix: 'A', default_location_id: null, single_order_pack_max_minutes: 3, group_order_pack_max_minutes: 40, big_group_pack_coefficient: 3, single_weigh_require_pack: false, stock_warning_enabled: false, stock_warning_quantity: 0, stock_static_hours: 168, return_unpack_max_record_minutes: 5, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_enabled: DEFAULT_AUTO_OUTBOUND_ENABLED, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, cutoff_order_enabled: 1, cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME, allocate_start_time: DEFAULT_ALLOCATE_START_TIME, day_start_time: DEFAULT_DAY_START_TIME, receiving_pending_inbound_notice: DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE, inbox_push_retry: DEFAULT_INBOX_PUSH_RETRY, }); 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 {Array|null|undefined|string} rawRules 原始库存预警规则。 * @return {Array} 规范化后的库存预警规则数组。 */ const normalizeInventoryWarningRules = rawRules => { if (rawRules === undefined || rawRules === null || rawRules === '') { return getDefaultInventoryWarningRules(); } if (!Array.isArray(rawRules)) { throw new Error('subject_config.inventory_warning_rules 必须是数组'); } return rawRules.map((rule, index) => { const basePath = `subject_config.inventory_warning_rules[${index}]`; if (!rule || typeof rule !== 'object' || Array.isArray(rule)) { throw new Error(`${basePath} 必须是对象`); } const name = String(rule.name === undefined || rule.name === null ? '' : rule.name).trim(); if (!name) { throw new Error(`${basePath}.name 不能为空`); } const key = String(rule.key === undefined || rule.key === null ? '' : rule.key).trim(); if (!key) { throw new Error(`${basePath}.key 不能为空`); } const rawExpireDays = rule.expire_days; if (rawExpireDays === undefined || rawExpireDays === null || rawExpireDays === '') { throw new Error(`${basePath}.expire_days 必须是非负整数`); } const expireDays = Number(rawExpireDays); if (!Number.isInteger(expireDays) || expireDays < 0) { throw new Error(`${basePath}.expire_days 必须是非负整数`); } const tipText = rule.tip_text === undefined || rule.tip_text === null ? '' : String(rule.tip_text); return { name, key, expire_days: expireDays, tip_text: tipText, }; }); }; /** * 规范化 HH:mm 时间文本(支持跨天:小时最大 maxHour)。 * 缺省或格式非法(含超出 maxHour)时回退指定默认值。 * * @param {string|undefined|null} value 原始时间文本。 * @param {string} defaultValue 默认 HH:mm。 * @param {number} [maxHour=23] 允许的最大小时(放开时间用 47,表示可跨到次日)。 * @return {string} 规范化后的 HH:mm 文本。 */ const normalizeHourMinuteTime = (value, defaultValue, maxHour = 23) => { if (value === undefined || value === null || value === '') { return defaultValue; } const text = String(value).trim(); const match = /^(\d{1,2}):([0-5]\d)$/.exec(text); if (!match || Number(match[1]) > maxHour) { return defaultValue; } return `${String(Number(match[1])).padStart(2, '0')}:${match[2]}`; }; /** * 将 HH:mm 文本解析为总分钟数(支持跨天,用于时间先后比较)。 * * @param {string} timeText HH:mm 文本(小时可超过 23)。 * @return {number} 总分钟数。 */ const parseHourMinuteToMinutes = timeText => { const match = /^(\d{1,2}):(\d{2})$/.exec(String(timeText || '').trim()); if (!match) return 0; return Number(match[1]) * 60 + Number(match[2]); }; /** * 规范化「允许当天出库最后时间」配置(HH:mm,当天内 00:00~23:59)。 * 缺省或格式非法时回退默认 06:00。 * * @param {string|undefined|null} value 原始时间文本。 * @return {string} 规范化后的 HH:mm 文本。 */ const normalizeSameDayOutboundDeadlineTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME, 23); /** * 规范化「放行时间」配置(HH:mm,支持跨天 00:00~47:59,如 27:00 = 次日 03:00)。 * 缺省或格式非法时回退默认 22:00。 * * @param {string|undefined|null} value 原始时间文本。 * @return {string} 规范化后的 HH:mm 文本。 */ const normalizeSameDayOutboundReleaseTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME, 47); /** * 规范化单条自动出库规则。 * 字段:require_pack(需已打包) / require_weigh(需已称重) / require_sync(需已同步) * / exclude_same_day_outbound(不出库当天订单) / same_day_outbound_deadline_time * / same_day_outbound_release_time。 * 三个 require_* 沿用「非 false 即 true(缺省开启)」口径;非对象项、时间越界抛错。 * * @param {Object} rawRule 原始单条规则。 * @param {number} index 规则下标(用于报错定位)。 * @return {Object} 规范化后的单条规则。 */ const normalizeAutoOutboundRule = (rawRule, index) => { const basePath = `subject_config.auto_outbound_rules[${index}]`; if (!rawRule || typeof rawRule !== 'object' || Array.isArray(rawRule)) { throw new Error(`${basePath} 必须是对象`); } const sameDayOutboundDeadlineTime = normalizeSameDayOutboundDeadlineTime(rawRule.same_day_outbound_deadline_time); const sameDayOutboundReleaseTime = normalizeSameDayOutboundReleaseTime(rawRule.same_day_outbound_release_time); // 保存时校验:允许当天出库最后时间不能大于当天放开时间 if (parseHourMinuteToMinutes(sameDayOutboundDeadlineTime) > parseHourMinuteToMinutes(sameDayOutboundReleaseTime)) { throw new Error(`自动出库规则第 ${index + 1} 条:允许当天出库最后时间不能大于当天放开时间`); } return { require_pack: rawRule.require_pack !== false, require_weigh: rawRule.require_weigh !== false, require_sync: rawRule.require_sync !== false, exclude_same_day_outbound: normalizeBooleanFlag( rawRule.exclude_same_day_outbound, `${basePath}.exclude_same_day_outbound` ) !== false, same_day_outbound_deadline_time: sameDayOutboundDeadlineTime, same_day_outbound_release_time: sameDayOutboundReleaseTime, }; }; /** * 规范化自动出库规则数组。 * 旧版本的对象结构(含 enabled/require_recheck/require_print/require_pick)不兼容: * 一律按默认(空数组)处理,需重新配置。 * * @param {Array|Object|string|undefined|null} rawRules 原始自动出库规则。 * @return {Array} 规范化后的自动出库规则数组。 */ const normalizeAutoOutboundRules = rawRules => { if (rawRules === undefined || rawRules === null || rawRules === '') { return []; } let parsed = rawRules; if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed); } catch (error) { return []; } } if (!Array.isArray(parsed)) { return []; } return parsed.map((rule, index) => normalizeAutoOutboundRule(rule, index)); }; /** * 规范化正整数字段(小于等于 0 或非整数时抛错)。 * * @param {*} value 原始值,空值返回默认值。 * @param {number} defaultValue 默认值。 * @param {string} fieldName 字段全名(用于报错)。 * @return {number} 规范化后的正整数。 */ const normalizePositiveInteger = (value, defaultValue, fieldName) => { if (value === undefined || value === null || value === '') { return defaultValue; } const normalized = Number(value); if (!Number.isInteger(normalized) || normalized <= 0) { throw new Error(`${fieldName} 必须是大于 0 的整数`); } return normalized; }; /** * 规范化通知短语:空值回退默认短语,非字符串转字符串,超长报错。 * * @param {*} value 原始短语。 * @param {string} defaultValue 默认短语。 * @param {string} fieldName 字段全名(用于报错)。 * @return {string} 规范化后的短语。 */ const normalizeNoticeTemplateText = (value, defaultValue, fieldName) => { if (value === undefined || value === null) { return defaultValue; } const normalized = String(value).trim(); if (!normalized) { return defaultValue; } if (normalized.length > PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH) { throw new Error(`${fieldName} 长度不能超过 ${PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH} 字符`); } return normalized; }; /** * 规范化「收货未入库提醒」配置。 * 字段:enabled(是否启用,默认否) / notice_time(提醒时间 HH:mm,默认 08:30) * / min_hours(超时下限小时,默认 24) / max_hours(超时上限小时,默认 48) * / notice_template(仓库客服群通知短语) / store_notice_template(货主群通知短语)。 * 非法结构(非对象/非法 JSON)回退默认值;时间格式、小时数越界、短语超长抛错。 * * @param {Object|string|null|undefined} rawValue 原始配置。 * @return {Object} 规范化后的配置对象。 */ const normalizeReceivingPendingInboundNotice = rawValue => { if (rawValue === undefined || rawValue === null || rawValue === '') { return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; } let parsed = rawValue; if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed); } catch (error) { return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; } const noticeTime = normalizeSubjectConfigText(parsed.notice_time, DEFAULT_PENDING_RECEIVING_NOTICE_TIME); if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(noticeTime)) { throw new Error('subject_config.receiving_pending_inbound_notice.notice_time 格式必须为 HH:mm(如 08:30)'); } const minHours = normalizePositiveInteger( parsed.min_hours, DEFAULT_PENDING_RECEIVING_MIN_HOURS, 'subject_config.receiving_pending_inbound_notice.min_hours' ); const maxHours = normalizePositiveInteger( parsed.max_hours, DEFAULT_PENDING_RECEIVING_MAX_HOURS, 'subject_config.receiving_pending_inbound_notice.max_hours' ); if (minHours >= maxHours) { throw new Error('subject_config.receiving_pending_inbound_notice.min_hours 必须小于 max_hours'); } return { enabled: normalizeBooleanFlag(parsed.enabled, 'subject_config.receiving_pending_inbound_notice.enabled') === true, notice_time: noticeTime, min_hours: minHours, max_hours: maxHours, notice_template: normalizeNoticeTemplateText( parsed.notice_template, DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, 'subject_config.receiving_pending_inbound_notice.notice_template' ), store_notice_template: normalizeNoticeTemplateText( parsed.store_notice_template, DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, 'subject_config.receiving_pending_inbound_notice.store_notice_template' ), }; }; /** * 规范化「站内信推送失败自动重发」配置(subject_config.inbox_push_retry)。 * 字段:enabled(是否启用,默认否) / window_minutes(重发时间范围分钟,默认 30,范围 1-1440)。 * 非法结构(非对象/非法 JSON)回退默认值;enabled 非布尔值、window_minutes 越界抛错。 * * @param {Object|string|null|undefined} rawValue 原始配置。 * @return {Object} 规范化后的配置对象。 */ const normalizeInboxPushRetry = rawValue => { if (rawValue === undefined || rawValue === null || rawValue === '') { return { ...DEFAULT_INBOX_PUSH_RETRY }; } let parsed = rawValue; if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed); } catch (error) { return { ...DEFAULT_INBOX_PUSH_RETRY }; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return { ...DEFAULT_INBOX_PUSH_RETRY }; } const rawWindowMinutes = parsed.window_minutes; let windowMinutes = DEFAULT_INBOX_PUSH_RETRY.window_minutes; if (!(rawWindowMinutes === undefined || rawWindowMinutes === null || rawWindowMinutes === '')) { const value = Number(rawWindowMinutes); if (!Number.isInteger(value) || value < INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN || value > INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX) { throw new Error( `subject_config.inbox_push_retry.window_minutes 必须是 ${INBOX_PUSH_RETRY_WINDOW_MINUTES_MIN}-${INBOX_PUSH_RETRY_WINDOW_MINUTES_MAX} 的整数(分钟)` ); } windowMinutes = value; } return { enabled: normalizeBooleanFlag(parsed.enabled, 'subject_config.inbox_push_retry.enabled') === true, window_minutes: windowMinutes, }; }; /** * 规范化主体配置,确保默认值与字段约束一致。 * * @param {Object|string|null|undefined} rawValue 主体配置原始值。 * @return {Object} 规范化后的主体配置对象。 */ const normalizeSubjectConfig = rawValue => { if (rawValue === undefined || rawValue === null || rawValue === '') { return { ...DEFAULT_SUBJECT_CONFIG, inventory_warning_rules: getDefaultInventoryWarningRules(), auto_outbound_rules: getDefaultAutoOutboundRules(), }; } 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; } const rawSingleOrderPackMaxMinutes = parsed.single_order_pack_max_minutes; if (rawSingleOrderPackMaxMinutes === undefined || rawSingleOrderPackMaxMinutes === null || rawSingleOrderPackMaxMinutes === '') { normalized.single_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.single_order_pack_max_minutes; } else { const singleOrderPackMaxMinutes = Number(rawSingleOrderPackMaxMinutes); if (!Number.isInteger(singleOrderPackMaxMinutes) || singleOrderPackMaxMinutes <= 0) { throw new Error('subject_config.single_order_pack_max_minutes 必须是大于 0 的整数'); } normalized.single_order_pack_max_minutes = singleOrderPackMaxMinutes; } const rawGroupOrderPackMaxMinutes = parsed.group_order_pack_max_minutes; if (rawGroupOrderPackMaxMinutes === undefined || rawGroupOrderPackMaxMinutes === null || rawGroupOrderPackMaxMinutes === '') { normalized.group_order_pack_max_minutes = DEFAULT_SUBJECT_CONFIG.group_order_pack_max_minutes; } else { const groupOrderPackMaxMinutes = Number(rawGroupOrderPackMaxMinutes); if (!Number.isInteger(groupOrderPackMaxMinutes) || groupOrderPackMaxMinutes <= 0) { throw new Error('subject_config.group_order_pack_max_minutes 必须是大于 0 的整数'); } normalized.group_order_pack_max_minutes = groupOrderPackMaxMinutes; } const rawBigGroupPackCoefficient = parsed.big_group_pack_coefficient; if (rawBigGroupPackCoefficient === undefined || rawBigGroupPackCoefficient === null || rawBigGroupPackCoefficient === '') { normalized.big_group_pack_coefficient = DEFAULT_SUBJECT_CONFIG.big_group_pack_coefficient; } else { const bigGroupPackCoefficient = Number(rawBigGroupPackCoefficient); if (!Number.isFinite(bigGroupPackCoefficient) || bigGroupPackCoefficient <= 0) { throw new Error('subject_config.big_group_pack_coefficient 必须是大于 0 的数字'); } normalized.big_group_pack_coefficient = bigGroupPackCoefficient; } // 散单称重是否需要打包:默认关闭(未配置的仓库不校验打包状态) if (Object.prototype.hasOwnProperty.call(parsed, 'single_weigh_require_pack')) { normalized.single_weigh_require_pack = normalizeBooleanFlag( parsed.single_weigh_require_pack, 'subject_config.single_weigh_require_pack' ); } // 是否开启库存预警:默认关闭 if (Object.prototype.hasOwnProperty.call(parsed, 'stock_warning_enabled')) { normalized.stock_warning_enabled = normalizeBooleanFlag( parsed.stock_warning_enabled, 'subject_config.stock_warning_enabled' ); } const rawStockWarningQuantity = parsed.stock_warning_quantity; if (rawStockWarningQuantity === undefined || rawStockWarningQuantity === null || rawStockWarningQuantity === '') { normalized.stock_warning_quantity = DEFAULT_SUBJECT_CONFIG.stock_warning_quantity; } else { const stockWarningQuantity = Number(rawStockWarningQuantity); if (!Number.isInteger(stockWarningQuantity) || stockWarningQuantity < 0) { throw new Error('subject_config.stock_warning_quantity 必须是非负整数'); } normalized.stock_warning_quantity = stockWarningQuantity; } const rawStockStaticHours = parsed.stock_static_hours; if (rawStockStaticHours === undefined || rawStockStaticHours === null || rawStockStaticHours === '') { normalized.stock_static_hours = DEFAULT_SUBJECT_CONFIG.stock_static_hours; } else { const stockStaticHours = Number(rawStockStaticHours); if (!Number.isFinite(stockStaticHours) || stockStaticHours <= 0) { throw new Error('subject_config.stock_static_hours 必须是大于 0 的数字(小时)'); } normalized.stock_static_hours = stockStaticHours; } const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes; if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') { normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes; } else { const returnUnpackMaxRecordMinutes = Number(rawReturnUnpackMaxRecordMinutes); if (!Number.isInteger(returnUnpackMaxRecordMinutes) || returnUnpackMaxRecordMinutes <= 0) { throw new Error('subject_config.return_unpack_max_record_minutes 必须是大于 0 的整数'); } normalized.return_unpack_max_record_minutes = returnUnpackMaxRecordMinutes; } const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks; if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') { normalized.auto_allocate_express_exclude_remarks = []; } else { if (!Array.isArray(rawExcludeRemarks)) { throw new Error('subject_config.auto_allocate_express_exclude_remarks 必须是字符串数组'); } normalized.auto_allocate_express_exclude_remarks = rawExcludeRemarks .map((item, index) => { if (item === undefined || item === null || item === '') { return null; } const trimmed = String(item).trim(); if (trimmed === '') { throw new Error(`subject_config.auto_allocate_express_exclude_remarks[${index}] 不能为空字符串`); } return trimmed; }) .filter(Boolean); } 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; } } normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); normalized.auto_outbound_enabled = normalizeBooleanFlag( parsed.auto_outbound_enabled, 'subject_config.auto_outbound_enabled' ) === true; normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); normalized.receiving_pending_inbound_notice = normalizeReceivingPendingInboundNotice( parsed.receiving_pending_inbound_notice ); normalized.inbox_push_retry = normalizeInboxPushRetry(parsed.inbox_push_retry); const rawDefaultLocationId = parsed.default_location_id; if (rawDefaultLocationId === undefined || rawDefaultLocationId === null || rawDefaultLocationId === '') { normalized.default_location_id = null; } else { const defaultLocationId = Number(rawDefaultLocationId); if (!Number.isInteger(defaultLocationId) || defaultLocationId <= 0) { throw new Error('subject_config.default_location_id 必须是正整数库位ID'); } normalized.default_location_id = defaultLocationId; } if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_enabled')) { normalized.cutoff_order_enabled = normalizeBooleanFlag(parsed.cutoff_order_enabled, 'subject_config.cutoff_order_enabled'); } if (Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time')) { const cutoffTime = normalizeSubjectConfigText(parsed.cutoff_order_time, DEFAULT_CUTOFF_ORDER_TIME); if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(cutoffTime)) { throw new Error('subject_config.cutoff_order_time 格式必须为 HH:mm(如 18:00)'); } if (cutoffTime < CUTOFF_ORDER_TIME_MIN || cutoffTime > CUTOFF_ORDER_TIME_MAX) { normalized.cutoff_order_time = DEFAULT_CUTOFF_ORDER_TIME; } else { normalized.cutoff_order_time = cutoffTime; } } if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time')) { const allocateStartTime = normalizeSubjectConfigText(parsed.allocate_start_time, DEFAULT_ALLOCATE_START_TIME); if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(allocateStartTime)) { throw new Error('subject_config.allocate_start_time 格式必须为 HH:mm(如 08:00)'); } if (allocateStartTime < ALLOCATE_START_TIME_MIN || allocateStartTime > ALLOCATE_START_TIME_MAX) { normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME; } else { normalized.allocate_start_time = allocateStartTime; } } else { // 旧数据补齐默认开始自动分配时间 normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME; } if (Object.prototype.hasOwnProperty.call(parsed, 'day_start_time')) { const dayStartTime = normalizeSubjectConfigText(parsed.day_start_time, DEFAULT_DAY_START_TIME); if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(dayStartTime)) { throw new Error('subject_config.day_start_time 格式必须为 HH:mm(如 06:00)'); } if (dayStartTime < DAY_START_TIME_MIN || dayStartTime > DAY_START_TIME_MAX) { normalized.day_start_time = DEFAULT_DAY_START_TIME; } else { normalized.day_start_time = dayStartTime; } } else { // 旧数据补齐默认自然日开始时间 normalized.day_start_time = DEFAULT_DAY_START_TIME; } // 跨字段校验:仅当显式同时提交两个时间字段且相等时拒绝(自动分配窗口为空) if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time') && Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time') && normalized.allocate_start_time === normalized.cutoff_order_time) { throw new Error('subject_config.allocate_start_time 不能等于 subject_config.cutoff_order_time(自动分配窗口为空)'); } 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: '更新时间', }, project: { type: STRING(20), 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_INVENTORY_WARNING_RULES = DEFAULT_INVENTORY_WARNING_RULES; Store.DEFAULT_SUBJECT_CONFIG = DEFAULT_SUBJECT_CONFIG; Store.normalizeSubjectConfig = normalizeSubjectConfig; Store.normalizeAutoOutboundRules = normalizeAutoOutboundRules; // 实例方法:检查商家是否启用 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; };