liufumingren 4bf3268596 feat(workbench): 大团购打包系数与打包时长闸门,packOrder/queryOrder 响应新增 wave_scope 与倒计时字段
- 仓库设置新增 big_group_pack_coefficient(数字,默认 3,单位秒/单):store.js 默认值与归一化校验、setting.warehouse 字段元信息(type=number、min=0.1)

- workbench.queryOrder:响应 order 新增 wave_scope;当前工作台 wave_scope=1 打包任务未到「打包数x系数」秒时扫描其他波次订单返回「打包时长不足」,本波次放行,已到时不受限;闸门按 wms_pack_task.wave_scope=1 快捷判定

- workbench.packOrder:wms_pack_task 落库 wave_scope(服务端复查,非法/缺省兜底订单行值);响应新增 pack_wait_seconds(当前波次打包数x系数)与 pack_start_time(毫秒时间戳),仅 wave_scope=1 下发,其他为 0

- 迁移 20260924150000-add-wave-scope-to-pack-task.js:wms_pack_task 新增 wave_scope 列(幂等;开发与生产均已执行,生产因存在更早 pending 迁移改为等价 DDL+SequelizeMeta 记录)

- 测试:新增 workbench.bigGroupTimeGate.regression.test.js(11 用例全绿);workbench.queryOrder.performance.test.js 与基线一致(8 pass / 6 既有失败,非本次引入);ESLint 通过(workbench.js 历史类字段 parse error 为既有问题,与基线一致)

- 文档:methods/system.json 升至 0.3.181、changes 新增 2 条记录;已全量导入库表(wms_api_method_doc/wms_method_doc_meta)后重新导出,恢复 3 条库表已有但文件缺失的 setting.warehouse 前端配置方法
2026-09-24 03:16:35 +08:00

865 lines
32 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';
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: 'inbox_push_retry',
name: '站内信推送失败自动重发',
type: 'object',
default: Object.freeze({
enabled: false,
window_minutes: 30,
}),
required: false,
description: '开启后,站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发;仅重发失败时间在 window_minutes 内的消息,超出范围不再补发',
item_keys: Object.freeze([
Object.freeze({
key: 'enabled',
name: '启用自动重发',
type: 'flag',
default: false,
required: true,
description: '默认否,开启后定时任务才会自动重发推送失败的消息',
}),
Object.freeze({
key: 'window_minutes',
name: '重发时间范围(分钟)',
type: 'integer',
default: 30,
required: false,
min: 1,
max: 1440,
description: '仅自动重发「失败时间在该范围内」的消息,单位:分钟,默认 30,范围 1-1440;仅在开关开启时生效',
}),
]),
}),
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, exclude_same_day_outbound: true, same_day_outbound_deadline_time: '06:00', same_day_outbound_release_time: '22:00' }),
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: 'exclude_same_day_outbound', name: '不出库当天订单', type: 'flag', required: false, default: true, description: '开启后,在当天放开时间前,「允许当天出库最后时间」之后复核的订单不自动出库,到达当天放开时间后恢复' }),
Object.freeze({ key: 'same_day_outbound_deadline_time', name: '允许当天出库最后时间', type: 'string', required: false, default: '06:00', maxLength: 5, min: '00:00', max: '23:59', description: '复核时间早于该时间的订单不受「不出库当天订单」开启的影响,格式 HH:mm,不能大于当天放开时间' }),
Object.freeze({ key: 'same_day_outbound_release_time', name: '当天放开时间', type: 'string', required: false, default: '22:00', maxLength: 5, min: '00:00', max: '23:59', description: '开启「不出库当天订单」时,当天到达该时间后不再限制当天复核订单的自动出库,格式 HH:mm' }),
]),
}),
Object.freeze({
key: 'cutoff_order_enabled',
name: '启用截单',
type: 'flag',
default: 1,
required: false,
description: '启用后,订单创建时间早于开始自动分配时间或超过截单时间(开始时间晚于截单时间时截单时间视为次日),不再自动分配快递和储位,不再自动加团',
}),
Object.freeze({
key: 'allocate_start_time',
name: '开始自动分配时间',
type: 'string',
default: '08:00',
required: false,
maxLength: 5,
min: '00:00',
max: '23:59',
description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日',
}),
Object.freeze({
key: 'cutoff_order_time',
name: '截单时间',
type: 'string',
default: '18:00',
required: false,
maxLength: 5,
min: '00: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: 'big_group_pack_coefficient',
name: '大团购打包系数',
type: 'number',
default: 3,
required: false,
description: '大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0',
min: 0.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: 'receiving_pending_inbound_notice',
name: '收货未入库提醒',
type: 'object',
default: Object.freeze({
enabled: false,
notice_time: '08:30',
min_hours: 24,
max_hours: 48,
notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:',
store_notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:',
}),
required: false,
description: '开启后每天按提醒时间扫描「创建超过 min_hours 且不足 max_hours 仍未完成入库」的收货单,绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群',
item_keys: Object.freeze([
Object.freeze({
key: 'enabled',
name: '是否通知收货未入库',
type: 'flag',
default: false,
required: true,
description: '默认否,开启后定时任务才会执行提醒',
}),
Object.freeze({
key: 'notice_time',
name: '提醒时间',
type: 'string',
default: '08:30',
required: false,
maxLength: 5,
min: '00:00',
max: '23:59',
description: '每日提醒时间,格式 HH:mm,默认 08:30',
}),
Object.freeze({
key: 'min_hours',
name: '超时下限(小时)',
type: 'integer',
default: 24,
required: false,
min: 1,
description: '收货单创建时间距今超过该小时数才提醒,默认 24',
}),
Object.freeze({
key: 'max_hours',
name: '超时上限(小时)',
type: 'integer',
default: 48,
required: false,
min: 1,
description: '收货单创建时间距今小于该小时数才提醒,超过则不再提醒,默认 48',
}),
Object.freeze({
key: 'notice_template',
name: '通知短语(仓库/客服群)',
type: 'string',
default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:',
required: false,
maxLength: 500,
description: '消息第一行短语,可插入变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名 / {store_id} 货主ID / {count} 单数 / {min_hours} / {max_hours} / {date} 提醒日期 / {numbers} 收货单号;短语后换行逐行列出明细,留空用默认短语',
}),
Object.freeze({
key: 'store_notice_template',
name: '通知短语(货主群)',
type: 'string',
default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:',
required: false,
maxLength: 500,
description: '推送给货主群的消息第一行短语,变量同 notice_template,留空用默认短语',
}),
]),
}),
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<Object>} 返回字段 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<void>} 无返回值。
*/
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<void>} 无返回值。
*/
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<Array>} 字段元信息数组(浅拷贝,含 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<Object>} 包含 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<void>} 无返回值。
* @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<Object>} 更新后的仓库设置。
*/
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,
};
}
/**
* 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。
*
* 只拉取一条启用记录(is_enabled=1,按 id 升序取第一条),返回值为对象;
* 无可用记录时返回 null(接口 data 为空)。
* 出于安全考虑不返回 authorizer_refresh_token 长期令牌。
*
* @return {Promise<Object|null>} 微信小程序配置对象;无可用记录时 null。
* @throws {Error} 未识别到当前仓库时抛出,状态码 400。
*/
async getWechatApp() {
const warehouseId = this.getCurrentWarehouseId();
const wechatAppModel = this.ctx.model && this.ctx.model.WechatApp;
if (!wechatAppModel || typeof wechatAppModel.findOne !== 'function') {
throw this.createError('WechatApp model 不可用', 500);
}
const record = await wechatAppModel.findOne({
where: {
warehouse_id: warehouseId,
is_enabled: 1,
},
order: [[ 'id', 'ASC' ]],
});
if (!record) {
return null;
}
const plain = record.get ? record.get({ plain: true }) : record;
return {
id: plain.id,
warehouse_id: plain.warehouse_id,
appid: plain.appid,
nickname: plain.nickname,
user_name: plain.user_name,
head_img: plain.head_img,
auth_time: plain.auth_time,
func_info: plain.func_info,
is_enabled: plain.is_enabled,
created_at: plain.created_at,
updated_at: plain.updated_at,
};
}
}
module.exports = SettingWarehouseService;