liufumingren e7fcd2549e 20260625
2026-06-25 02:01:59 +08:00

558 lines
18 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: '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: '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: 'webhook_enabled',
name: '是否启用 Webhook',
type: 'flag',
default: false,
required: false,
description: '控制仓库是否启用 Webhook 事件推送',
}),
Object.freeze({
key: 'callback_strategy',
name: '回调策略',
type: 'enum',
default: 'async',
required: false,
description: '仓库 Webhook 事件的回调执行策略',
options: [
Object.freeze({ value: 'sync', label: '同步回调' }),
Object.freeze({ value: 'async', label: '异步回调' }),
],
}),
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: 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),
};
}
/**
* 修改当前仓库设置并清理当前仓库缓存。
*
* @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);
}
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;