'use strict'; const { Service } = require('egg'); const INTERNAL_WAVE_STRATEGY_VERSION_KEY = 'wave_strategy_version'; const DEFAULT_WAVE_STRATEGY_VERSION = 1; const DEFAULT_INVENTORY_WARNING_RULES = Object.freeze([ Object.freeze({ name: '01级', key: '#ff4d4f', expire_days: 0, tip_text: '立即报废' }), Object.freeze({ name: '02级', key: '#ff7a45', expire_days: 30, tip_text: '优先处理' }), Object.freeze({ name: '03级', key: '#faad14', expire_days: 90, tip_text: '尽快处理' }), Object.freeze({ name: '04级', key: '#fadb14', expire_days: 180, tip_text: '建议处理' }), Object.freeze({ name: '05级', key: '#95de64', expire_days: 365, tip_text: '库存关注' }), Object.freeze({ name: '06级', key: '#52c41a', expire_days: 999999, tip_text: '常规监控' }), ]); // 仓库设置字段元信息(对应 wms_store.subject_config) const WAREHOUSE_SETTING_FIELDS = Object.freeze([ Object.freeze({ key: 'max_notice_webhook_count', name: '最大通知 Webhook 次数', type: 'integer', default: 5, required: false, description: '单次事件最多触发的 Webhook 通知次数(0-5)', min: 0, max: 5, }), Object.freeze({ key: 'max_wave_quantity', name: '仓库波次最大数量限制', type: 'integer', default: 500, required: false, description: '控制单个波次允许的最大订单数量,默认 500', min: 1, }), Object.freeze({ key: 'min_group_order_fetch_quantity', name: '最小团购订单抓取数量', type: 'integer', default: 13, required: false, description: '控制团购波次最小抓取订单数量,默认 13', min: 1, }), Object.freeze({ key: 'auto_grouping_enabled', name: '自动加团开关', type: 'flag', default: false, required: false, description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)', }), Object.freeze({ key: 'auto_allocate_express_exclude_remarks', name: '自动分配快递排除备注', type: 'string_array', default: [], required: false, description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)', }), Object.freeze({ key: 'inbox_reply_exclude_keywords', name: '排除快递回复关键词', type: 'string_array', default: [], required: false, description: '消息命中任一关键词时仅记录工单不发送回信通知,默认 [](正常回信)', }), Object.freeze({ key: 'default_express_code', name: '默认快递编码', type: 'string', default: 'STO', required: false, description: '仓库默认使用的快递编码', maxLength: 50, }), Object.freeze({ key: 'default_platform_code', name: '默认平台编码', type: 'string', default: 'TB', required: false, description: '仓库默认使用的平台编码', maxLength: 50, }), 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: 'receiver_address', name: '仓库收货地址', type: 'string', default: '', required: false, description: '仓库收货地址(退货/退件收件地址),一行文本', maxLength: 500, }), Object.freeze({ key: 'group_wave_prefix', name: '团购波次前缀', type: 'string', default: 'B', required: false, description: '团购波次编号前缀,最多 5 个字符,默认 B', maxLength: 5, }), Object.freeze({ key: 'delete_order_wave_prefix', name: '散单波次前缀', type: 'string', default: 'A', required: false, description: '散单波次编号前缀,最多 5 个字符,默认 A', maxLength: 5, }), Object.freeze({ key: 'inventory_warning_rules', name: '库存预警配置', type: 'array', item_keys: [ Object.freeze({ key: 'name', name: '名称', type: 'string', required: true, description: '预警等级名称' }), Object.freeze({ key: 'key', name: '颜色标识', type: 'color', required: true, description: '预警颜色值' }), Object.freeze({ key: 'expire_days', name: '过期天数', type: 'integer', required: true, description: '距过期天数阈值' }), Object.freeze({ key: 'tip_text', name: '提示语', type: 'string', required: false, description: '预警提示文案' }), ], default: DEFAULT_INVENTORY_WARNING_RULES, required: false, description: '可配置多个库存预警项,每项包含 name、key、expire_days、tip_text', }), Object.freeze({ key: 'auto_outbound_rules', name: '自动出库规则', type: 'object', default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true, require_print: true, require_pick: true }), required: false, description: '满足条件自动标记出库。全部条件满足时自动标记待出库', item_keys: Object.freeze([ Object.freeze({ key: 'enabled', name: '启用', type: 'flag', required: true, description: '是否启用自动出库' }), Object.freeze({ key: 'require_recheck', name: '需已复核', type: 'flag', required: false, description: '是否要求 recheck_status=fin' }), Object.freeze({ key: 'require_pack', name: '需已打包', type: 'flag', required: false, description: '是否要求 pack_status=fin' }), Object.freeze({ key: 'require_weigh', name: '需已称重', type: 'flag', required: false, description: '是否要求 weighing_weight>0' }), Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }), Object.freeze({ key: 'require_print', name: '需已打印', type: 'flag', required: false, description: '是否要求 print_status=fin' }), Object.freeze({ key: 'require_pick', name: '需已拣货', type: 'flag', required: false, description: '是否要求 pick_status=fin' }), ]), }), 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,如 18:00', }), Object.freeze({ key: 'after_sale_followup_hours', name: '售后跟进时间(h)', type: 'object', required: false, description: '按售后类型+子类型设置跟进小时数。_default 为该类型默认值,具体子类型可覆盖', item_keys: [ Object.freeze({ key: 'order', name: '订单售后', type: 'object', required: false, description: '订单类型跟进配置', item_keys: [ Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), Object.freeze({ key: 'intercept', name: '拦截', type: 'integer', default: 4, min: 1, max: 720 }), Object.freeze({ key: 'urge', name: '催件', type: 'integer', default: 4, min: 1, max: 720 }), Object.freeze({ key: 'change_address', name: '改地址', type: 'integer', default: 8, min: 1, max: 720 }), Object.freeze({ key: 'change_carrier', name: '换快递', type: 'integer', default: 8, min: 1, max: 720 }), Object.freeze({ key: 'delivery_delay', name: '发货延迟', type: 'integer', default: 12, min: 1, max: 720 }), Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), Object.freeze({ key: 'quality_issue', name: '质量问题', type: 'integer', default: 48, min: 1, max: 720 }), Object.freeze({ key: 'missing_item', name: '少发', type: 'integer', default: 24, min: 1, max: 720 }), ], }), Object.freeze({ key: 'receiving', name: '收货单售后', type: 'object', required: false, description: '收货单类型跟进配置', item_keys: [ Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), ], }), Object.freeze({ key: 'entry', name: '入库单售后', type: 'object', required: false, description: '入库单类型跟进配置', item_keys: [ Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }), Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }), ], }), Object.freeze({ key: 'stockout', name: '出库单售后', type: 'object', required: false, description: '出库单类型跟进配置', item_keys: [ Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }), Object.freeze({ key: 'return_issue', name: '退货异常', type: 'integer', default: 48, min: 1, max: 720 }), Object.freeze({ key: 'shortage', name: '少发', type: 'integer', default: 48, min: 1, max: 720 }), ], }), ], default: Object.freeze({ order: Object.freeze({ _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }), receiving: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), entry: Object.freeze({ _default: 24, shortage: 48, damage: 48 }), stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }), }), }), Object.freeze({ key: 'single_order_pack_max_minutes', name: '散单打包最大时长(分钟)', type: 'integer', default: 3, required: false, description: '散单打包最大时长,单位:分钟,默认 3', min: 1, }), Object.freeze({ key: 'group_order_pack_max_minutes', name: '团购打包最大时长(分钟)', type: 'integer', default: 40, required: false, description: '团购打包最大时长,单位:分钟,默认 40', min: 1, }), Object.freeze({ key: 'return_unpack_max_record_minutes', name: '拆包最大录制时长(分钟)', type: 'integer', default: 5, required: false, description: '拆包最大录制时长,单位:分钟,默认 5;超过上限时提交的结束时间自动截断为开始时间+上限', min: 1, }), Object.freeze({ key: 'default_location_id', name: '默认库位', type: 'location', default: null, required: false, description: '仓库未指定库位入库/上架时使用的默认库位(库位ID)', }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', type: 'integer', default: DEFAULT_WAVE_STRATEGY_VERSION, required: false, description: '内部字段:仓库波次策略版本号', min: 0, hidden: true, internal: true, }), ]); class SettingWarehouseService extends Service { /** * 读取默认快递与平台编码选项,查询失败时自动降级为空列表。 * * @return {Promise} 返回字段 key 到 options 的映射。 */ async getDefaultCodeFieldOptionsMap() { const modelContainer = this.ctx && this.ctx.model ? this.ctx.model : (this.app && this.app.model ? this.app.model : {}); const expressModel = modelContainer && modelContainer.Express; const platformModel = modelContainer && modelContainer.Platform; const fetchOptions = async model => { if (!model || typeof model.findAll !== 'function') { return []; } try { const rows = await model.findAll({ attributes: [ 'code', 'name' ], order: [[ 'code', 'ASC' ]], }); if (!Array.isArray(rows)) { return []; } return rows .map(item => { const code = item && item.code !== undefined && item.code !== null ? String(item.code) : ''; if (!code) { return null; } const name = item && item.name !== undefined && item.name !== null ? String(item.name) : ''; return { value: code, label: name || code, }; }) .filter(Boolean); } catch (_error) { return []; } }; const [ expressOptions, platformOptions ] = await Promise.all([ fetchOptions(expressModel), fetchOptions(platformModel), ]); return { default_express_code: expressOptions, default_platform_code: platformOptions, }; } /** * 规范化仓库波次策略版本号,返回数字。 * * @param {number|string|null|undefined} value 原始版本号。 * @param {Object} [options={}] 额外选项。 * @param {boolean} [options.useDefaultWhenEmpty=false] 空值时是否使用默认值。 * @return {number} 规范化后的版本号数字。 * @throws {Error} 输入不合法时抛出,状态码 400。 */ normalizeWaveStrategyVersion(value, options = {}) { const { useDefaultWhenEmpty = false } = options; if (value === undefined || value === null || value === '') { if (useDefaultWhenEmpty) { return DEFAULT_WAVE_STRATEGY_VERSION; } throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); } if (typeof value === 'number') { if (!Number.isSafeInteger(value) || value < 0) { throw this.createError('subject_config.wave_strategy_version 必须是非负整数', 400); } return value; } if (typeof value === 'string') { const trimmed = value.trim(); if (!/^\d+$/.test(trimmed)) { throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); } const numericVersion = Number(trimmed); if (!Number.isSafeInteger(numericVersion)) { throw this.createError('subject_config.wave_strategy_version 超出安全整数范围', 400); } return numericVersion; } throw this.createError('subject_config.wave_strategy_version 必须是数字或数字字符串', 400); } /** * 规范化 subject_config 内部字段,确保内部字段落库时为数字。 * * @param {Object} subjectConfig 原始配置对象。 * @return {Object} 规范化后的配置对象。 */ normalizeSubjectConfigInternalFields(subjectConfig) { const nextConfig = { ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), }; nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY] = this.normalizeWaveStrategyVersion( nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY], { useDefaultWhenEmpty: true } ); return nextConfig; } /** * 对外响应时移除内部字段,避免暴露内部配置。 * * @param {Object} subjectConfig 配置对象。 * @return {Object} 过滤后的配置对象。 */ sanitizeSubjectConfigForOutput(subjectConfig) { const nextConfig = { ...(subjectConfig && typeof subjectConfig === 'object' && !Array.isArray(subjectConfig) ? subjectConfig : {}), }; delete nextConfig[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; return nextConfig; } createError(message, code = 500) { const error = new Error(message); error.code = code; return error; } /** * 从 ctx.user.store_id 获取当前仓库 ID。 * * @return {number} 仓库 ID。 * @throws {Error} 未识别到仓库时抛出,状态码 400。 */ getCurrentWarehouseId() { const warehouseId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw this.createError('未识别到当前仓库,无法操作仓库设置', 400); } return warehouseId; } /** * 删除指定缓存键。 * * @param {string} cacheKey 缓存键。 * @return {Promise} 无返回值。 */ async deleteCacheByKey(cacheKey) { if (!cacheKey) { return; } if (this.app && typeof this.app.delCacheAsync === 'function') { await this.app.delCacheAsync(cacheKey); return; } if (this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(cacheKey, null, 0); } } /** * 清理指定仓库设置相关缓存。 * * @param {number|string} warehouseId 仓库 ID。 * @return {Promise} 无返回值。 */ async clearWarehouseSettingCache(warehouseId) { const normalizedWarehouseId = Number(warehouseId || 0); if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) { return; } const keys = [ `delivery_order:store:${normalizedWarehouseId}:subject_config`, `warehouse:${normalizedWarehouseId}store:${normalizedWarehouseId}:info`, ]; await Promise.all(keys.map(key => this.deleteCacheByKey(key).catch(() => null))); } /** * 获取仓库设置字段元信息列表。 * * @return {Promise} 字段元信息数组(浅拷贝,含 options 拷贝)。 */ async getFieldMeta() { const dynamicOptionsMap = await this.getDefaultCodeFieldOptionsMap(); return WAREHOUSE_SETTING_FIELDS .filter(field => !field.internal && field.key !== INTERNAL_WAVE_STRATEGY_VERSION_KEY) .map(field => ({ key: field.key, name: field.name, type: field.type, ...(field.item_keys !== undefined ? { item_keys: Array.isArray(field.item_keys) ? field.item_keys.map(itemKey => (itemKey && typeof itemKey === 'object' ? { ...itemKey } : itemKey)) : field.item_keys, } : {}), default: field.default, required: field.required, description: field.description, ...((Array.isArray(field.options) || Object.prototype.hasOwnProperty.call(dynamicOptionsMap, field.key)) ? { options: (Array.isArray(field.options) ? field.options.map(o => ({ ...o })) : (dynamicOptionsMap[field.key] || [])).map(o => ({ ...o })), } : {}), ...(field.min !== undefined ? { min: field.min } : {}), ...(field.max !== undefined ? { max: field.max } : {}), ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), ...(field.hidden !== undefined ? { hidden: field.hidden } : {}), ...(field.internal !== undefined ? { internal: field.internal } : {}), })); } /** * 读取当前仓库的设置(wms_store.subject_config)。 * * @return {Promise} 包含 warehouse_id 与 subject_config 的对象。 * @throws {Error} 仓库不存在时抛出,状态码 404。 */ async getSettings() { const warehouseId = this.getCurrentWarehouseId(); const store = await this.ctx.model.Store.findByPk(warehouseId, { attributes: [ 'id', 'subject_config' ], }); if (!store) { throw this.createError('仓库不存在', 404); } const normalizedSubjectConfig = this.normalizeSubjectConfigInternalFields(store.subject_config); return { warehouse_id: warehouseId, subject_config: this.sanitizeSubjectConfigForOutput(normalizedSubjectConfig), }; } /** * 校验默认库位是否属于当前仓库。 * * 传入的 default_location_id 为库位ID(wms_location_space.id),仅当该库位 * 属于当前仓库且未删除、已启用时才允许写入。 * * @param {*} locationIdValue 待校验的库位ID。 * @param {number} warehouseId 当前仓库 ID。 * @return {Promise} 无返回值。 * @throws {Error} 库位ID非法或不属于当前仓库时抛出,状态码 400。 */ async validateDefaultLocation(locationIdValue, warehouseId) { if (locationIdValue === undefined || locationIdValue === null || locationIdValue === '') { return; } const locationId = Number(locationIdValue); if (!Number.isInteger(locationId) || locationId <= 0) { throw this.createError('default_location_id 必须是正整数库位ID', 400); } const locationModel = this.ctx && this.ctx.model && this.ctx.model.LocationSpace; if (!locationModel || typeof locationModel.findOne !== 'function') { return; } const locationSpace = await locationModel.findOne({ where: { id: locationId, warehouse_id: warehouseId, is_enabled: true, deleted_at: null, }, attributes: [ 'id' ], }); if (!locationSpace) { throw this.createError(`默认库位 ${locationId} 不属于当前仓库`, 400); } } /** * 修改当前仓库设置并清理当前仓库缓存。 * * @param {Object} [data={}] 请求参数。 * @param {Object} [data.subject_config] 仓库设置对象,支持部分字段更新。 * @return {Promise} 更新后的仓库设置。 */ async saveSettings(data = {}) { const warehouseId = this.getCurrentWarehouseId(); const storeModel = this.ctx.model && this.ctx.model.Store; if (!storeModel || typeof storeModel.findByPk !== 'function') { throw this.createError('Store model 不可用', 500); } const store = await storeModel.findByPk(warehouseId, { attributes: [ 'id', 'subject_config' ], }); if (!store) { throw this.createError('仓库不存在', 404); } const hasSubjectConfig = Object.prototype.hasOwnProperty.call(data || {}, 'subject_config'); const nextPatch = hasSubjectConfig ? data.subject_config : null; if (!nextPatch || typeof nextPatch !== 'object' || Array.isArray(nextPatch)) { throw this.createError('subject_config 参数不能为空且必须是对象', 400); } // 默认库位必须属于当前仓库(值为库位ID) if (Object.prototype.hasOwnProperty.call(nextPatch, 'default_location_id')) { await this.validateDefaultLocation(nextPatch.default_location_id, warehouseId); } const nextPatchForMerge = { ...nextPatch, }; delete nextPatchForMerge[INTERNAL_WAVE_STRATEGY_VERSION_KEY]; const mergedConfig = { ...(store.subject_config && typeof store.subject_config === 'object' ? store.subject_config : {}), ...nextPatchForMerge, }; const mergedConfigWithInternalDefaults = this.normalizeSubjectConfigInternalFields(mergedConfig); let normalizedConfig; try { normalizedConfig = typeof storeModel.normalizeSubjectConfig === 'function' ? storeModel.normalizeSubjectConfig(mergedConfigWithInternalDefaults) : mergedConfigWithInternalDefaults; } catch (error) { throw this.createError(error.message || 'subject_config 参数不合法', Number(error.code) || 400); } await store.update({ subject_config: normalizedConfig, }); const cacheWarehouseId = warehouseId; await this.clearWarehouseSettingCache(cacheWarehouseId); return { warehouse_id: warehouseId, subject_config: this.sanitizeSubjectConfigForOutput(store.subject_config), cache_cleared_warehouse_id: cacheWarehouseId, }; } } module.exports = SettingWarehouseService;