liufumingren 018bbd379d feat(warehouse): 前置仓前端配置与按域名公开拉取接口
- 新增模型 wms_warehouse_front_config 与迁移:建表、
  追加 favicon_url、追加 cert_pem(可回滚)
- systems/setting/warehouse.js 实现 getFrontConfig / saveFrontConfig / saveFrontCert、
  域名唯一性校验、按域名缓存读取(含未登记域名的短 TTL 空缓存防穿透)与缓存清理
- systemMethods/setting/warehouse.js 开放对应 system method
- 新增公共免登录接口 frontConfig.getByDomain:按域名返回公开字段
  (domain/title/logo_url/login_bg_url/favicon_url/theme),
  不返回 cert_path/key_path/sync_status 等内部字段;未登记域名返回 404
2026-09-13 15:31:02 +08:00

1385 lines
51 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 crypto = require('node:crypto');
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: '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: '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,
}),
]);
// 仓库前端配置品牌文本字段元信息(对应 wms_warehouse_front_config,一仓一行)。
// 域名与证书字段不在此列:domain/cert_pem/cert_key/cert_path/key_path 只能通过证书上传接口(saveFrontCert)变更。
const FRONT_CONFIG_TEXT_FIELDS = Object.freeze([
Object.freeze({ key: 'title', name: 'title', maxLength: 100 }),
Object.freeze({ key: 'logo_url', name: 'logo_url', maxLength: 255 }),
Object.freeze({ key: 'favicon_url', name: 'favicon_url', maxLength: 255 }),
Object.freeze({ key: 'login_bg_url', name: 'login_bg_url', maxLength: 255 }),
]);
// 公共按域名拉取接口对外输出的字段白名单(安全红线:严禁输出证书/私钥内容与证书路径、同步状态等内部字段)
const FRONT_CONFIG_PUBLIC_FIELDS = Object.freeze([
'domain',
'title',
'logo_url',
'login_bg_url',
'favicon_url',
'theme',
]);
// 公共按域名拉取接口缓存 TTL(秒)
const FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS = 600;
// 未登记域名空缓存 TTL(秒):短缓存兜底防穿透,域名登记后由保存流程主动失效
const FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS = 60;
// 证书/私钥 PEM 文本最大长度(正常 RSA/ECC 证书远小于该值,防止异常大报文)
const FRONT_CONFIG_PEM_MAX_LENGTH = 64 * 1024;
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,
};
}
/**
* 校验并规范化仓库前端配置的字符串字段。
*
* @param {*} value 原始值。
* @param {string} fieldName 字段名。
* @param {number} maxLength 字段最大长度。
* @return {string|null} 规范化后的字符串;空值返回 null(表示清空)。
* @throws {Error} 超长时抛出,状态码 400。
*/
normalizeFrontConfigText(value, fieldName, maxLength) {
if (value === undefined || value === null) {
return null;
}
const normalized = String(value).trim();
if (!normalized) {
return null;
}
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength} 字符`, 400);
}
return normalized;
}
/**
* 校验并规范化仓库前端配置的 theme 字段。
*
* @param {*} value 原始值(对象或 JSON 字符串)。
* @return {Object|null} 规范化后的主题对象;空值返回 null(表示清空)。
* @throws {Error} 非合法 JSON 对象时抛出,状态码 400。
*/
normalizeFrontConfigTheme(value) {
if (value === undefined || value === null || value === '') {
return null;
}
let parsed = value;
if (typeof value === 'string') {
try {
parsed = JSON.parse(value.trim());
} catch (error) {
throw this.createError('theme 必须是合法的 JSON 对象', 400);
}
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw this.createError('theme 必须是合法的 JSON 对象', 400);
}
return parsed;
}
/**
* 校验非空 domain 的全局唯一性(可空列唯一索引允许多 NULL,数据库不兜底)。
*
* @param {string} domain 待校验域名(非空)。
* @param {number} excludeWarehouseId 排除的仓库 ID(当前仓库自身)。
* @return {Promise<void>} 无返回值。
* @throws {Error} domain 已被其他仓库使用时抛出,状态码 409。
*/
async assertFrontConfigDomainUnique(domain, excludeWarehouseId) {
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
if (!configModel || typeof configModel.findOne !== 'function') {
throw this.createError('WarehouseFrontConfig model 不可用', 500);
}
const { Op } = this.app.Sequelize;
const existing = await configModel.findOne({
where: {
domain,
store_id: { [Op.ne]: excludeWarehouseId },
},
attributes: [ 'store_id', 'domain' ],
});
if (existing) {
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
}
}
/**
* 构建仓库前端配置的输出对象(无记录时返回默认空配置)。
*
* 证书回显:输出证书原文(cert_pem)与私钥原文(key_pem,取自 cert_key 列),
* 不再输出 cert_path/key_path 路径字段(保存时已置空,尚无真实路径)。
* 安全说明:私钥原文回显仅限仓库主体登录后的 settings 页
* (getFrontConfig/saveFrontConfig/saveFrontCert 三个需登录接口复用本输出);
* 公共无鉴权接口 getFrontConfigByDomain 走 buildFrontConfigPublicOutput 白名单,
* 不经过本方法,仍不暴露证书/私钥内容与同步状态等内部字段。
*
* @param {Object|null} record 配置记录实例(可为 null)。
* @param {number} warehouseId 当前仓库 ID。
* @return {Object} 规范化输出对象。
*/
buildFrontConfigOutput(record, warehouseId) {
const hasRecord = !!(record && typeof record.get === 'function');
const getValue = key => (hasRecord ? record.get(key) : null);
return {
warehouse_id: Number(warehouseId || 0),
domain: hasRecord ? (getValue('domain') || '') : '',
title: hasRecord ? (getValue('title') || '') : '',
logo_url: hasRecord ? (getValue('logo_url') || '') : '',
favicon_url: hasRecord ? (getValue('favicon_url') || '') : '',
login_bg_url: hasRecord ? (getValue('login_bg_url') || '') : '',
theme: hasRecord ? (getValue('theme') || null) : null,
cert_pem: hasRecord ? (getValue('cert_pem') || '') : '',
key_pem: hasRecord ? (getValue('cert_key') || '') : '',
cert_expire_at: hasRecord ? (getValue('cert_expire_at') || null) : null,
sync_status: hasRecord ? Number(getValue('sync_status') || 0) : 0,
sync_attempts: hasRecord ? Number(getValue('sync_attempts') || 0) : 0,
last_sync_error: hasRecord ? (getValue('last_sync_error') || '') : '',
last_synced_at: hasRecord ? (getValue('last_synced_at') || null) : null,
updated_at: hasRecord ? (getValue('updated_at') || null) : null,
};
}
/**
* 查询当前仓库的前端独立部署配置(settings 页回显)。
*
* 需登录(token 绑定仓库上下文,只能查到自己仓库的配置),
* 响应含证书原文(cert_pem)与私钥原文(key_pem),供仓库主体 settings 页回显;
* 公共无鉴权接口 getFrontConfigByDomain 仍只返回公开字段白名单。
*
* @return {Promise<Object>} 配置输出对象;无记录时返回默认空配置。
* @throws {Error} 未识别到当前仓库时抛出,状态码 400。
*/
async getFrontConfig() {
const warehouseId = this.getCurrentWarehouseId();
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
if (!configModel || typeof configModel.findOne !== 'function') {
throw this.createError('WarehouseFrontConfig model 不可用', 500);
}
const record = await configModel.findOne({
where: {
store_id: warehouseId,
},
});
return this.buildFrontConfigOutput(record, warehouseId);
}
/**
* 构建前端配置公共拉取接口的缓存键(按域名)。
*
* @param {string} domain 域名(内部会 trim 规范化)。
* @return {string} Redis 缓存键。
*/
getFrontConfigDomainCacheKey(domain) {
return `front:config:domain:${String(domain || '').trim()}`;
}
/**
* 构建前端配置公共拉取接口的输出对象(仅公开字段白名单)。
*
* 安全红线:只输出 FRONT_CONFIG_PUBLIC_FIELDS 白名单字段,
* 严禁输出 cert_pem/cert_key 证书与私钥内容,以及 cert_path、key_path、
* sync_status、sync_attempts、last_sync_error 等内部字段。
*
* @param {Object} record 配置记录实例。
* @return {Object} 仅含公开字段的输出对象。
*/
buildFrontConfigPublicOutput(record) {
const hasRecord = !!(record && typeof record.get === 'function');
const getValue = key => (hasRecord ? record.get(key) : null);
const output = {};
for (const key of FRONT_CONFIG_PUBLIC_FIELDS) {
const value = hasRecord ? getValue(key) : null;
output[key] = key === 'theme' ? (value || null) : (value || '');
}
return output;
}
/**
* 清理指定域名的前端配置公共拉取缓存(空域名跳过)。
*
* @param {string} domain 待清理的域名。
* @return {Promise<void>} 无返回值。
*/
async clearFrontConfigDomainCache(domain) {
const normalizedDomain = String(domain || '').trim();
if (!normalizedDomain) {
return;
}
await this.deleteCacheByKey(this.getFrontConfigDomainCacheKey(normalizedDomain));
}
/**
* 按域名查询前端配置(公共无鉴权接口业务实现,Redis 缓存 + 查库兜底)。
*
* 安全红线:只返回公开字段(domain/title/logo_url/login_bg_url/favicon_url/theme),
* 严禁返回 cert_pem/cert_key 证书与私钥内容,以及 cert_path/key_path/
* sync_status/sync_attempts/last_sync_error 等内部字段。
*
* @param {string} domain 待查询域名。
* @return {Promise<Object>} 仅含公开字段的配置对象。
* @throws {Error} domain 为空时抛出 400;未登记域名抛出 404;数据库异常抛出 500。
*/
async getFrontConfigByDomain(domain) {
const normalizedDomain = String(domain || '').trim();
if (!normalizedDomain) {
throw this.createError('domain 不能为空', 400);
}
if (normalizedDomain.length > 100) {
throw this.createError('domain 长度不能超过 100 字符', 400);
}
const cacheKey = this.getFrontConfigDomainCacheKey(normalizedDomain);
// 优先读缓存;Redis 异常时降级查库(getCacheAsync 内部已做 Redis 降级处理)
if (this.app && typeof this.app.getCacheAsync === 'function') {
try {
const cached = await this.app.getCacheAsync(cacheKey);
// 未登记域名空缓存标记:直接按未配置返回,防穿透
if (cached && typeof cached === 'object' && cached.configured === false) {
throw this.createError('域名未配置', 404);
}
if (cached && typeof cached === 'object' && typeof cached.domain === 'string' && cached.domain) {
return cached;
}
} catch (error) {
if (Number(error.code) === 404) {
throw error;
}
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 读取缓存失败,降级查库: %s', error.message);
}
}
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
if (!configModel || typeof configModel.findOne !== 'function') {
throw this.createError('WarehouseFrontConfig model 不可用', 500);
}
const record = await configModel.findOne({
where: {
domain: normalizedDomain,
},
});
if (!record) {
// 缓存穿透兜底:未登记域名写短 TTL 空缓存,防止高频探测打穿数据库
if (this.app && typeof this.app.setCacheAsync === 'function') {
try {
await this.app.setCacheAsync(cacheKey, { configured: false }, FRONT_CONFIG_PUBLIC_MISS_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入未命中空缓存失败: %s', error.message);
}
}
throw this.createError('域名未配置', 404);
}
const output = this.buildFrontConfigPublicOutput(record);
if (this.app && typeof this.app.setCacheAsync === 'function') {
try {
await this.app.setCacheAsync(cacheKey, output, FRONT_CONFIG_PUBLIC_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[SettingWarehouseService.getFrontConfigByDomain] 写入缓存失败: %s', error.message);
}
}
return output;
}
/**
* 规范化证书/私钥 PEM 文本:去首尾空白,空值返回 null(表示未提供)。
*
* @param {*} value 原始值(PEM 文本)。
* @param {string} fieldName 字段名(用于错误提示)。
* @return {string|null} 规范化后的 PEM 文本;空值返回 null。
* @throws {Error} 内容超过长度上限时抛出,状态码 400。
*/
normalizeFrontConfigPem(value, fieldName) {
if (value === undefined || value === null) {
return null;
}
const normalized = String(value).trim();
if (!normalized) {
return null;
}
if (normalized.length > FRONT_CONFIG_PEM_MAX_LENGTH) {
throw this.createError(`${fieldName} 内容长度不能超过 ${FRONT_CONFIG_PEM_MAX_LENGTH} 字符`, 400);
}
return normalized;
}
/**
* 用 Node 内置 crypto.X509Certificate 解析证书 PEM 文本。
*
* @param {string} certPem 证书 PEM 文本。
* @return {Object} 解析成功后的 X509Certificate 实例。
* @throws {Error} 证书无法解析时抛出,状态码 400,统一文案“证书不合法”。
*/
parseFrontConfigCertPem(certPem) {
try {
return new crypto.X509Certificate(certPem);
} catch (error) {
throw this.createError('证书不合法', 400);
}
}
/**
* 校验证书有效期:未生效或已过期的证书禁止提交。
*
* @param {Object} cert 已解析的 X509Certificate 实例。
* @return {void} 无返回值。
* @throws {Error} 证书未生效或已过期时抛出,状态码 400,统一文案“证书不合法”。
*/
assertFrontConfigCertValid(cert) {
const now = Date.now();
const validFrom = new Date(cert.validFrom);
const validTo = new Date(cert.validTo);
if (Number.isNaN(validFrom.getTime())) {
throw this.createError('证书不合法', 400);
}
if (validFrom.getTime() > now) {
throw this.createError('证书不合法', 400);
}
if (Number.isNaN(validTo.getTime())) {
throw this.createError('证书不合法', 400);
}
if (validTo.getTime() <= now) {
throw this.createError('证书不合法', 400);
}
}
/**
* 收集证书可覆盖的域名列表:SAN 中的 DNS 项与 CN,统一转小写。
*
* @param {Object} cert 已解析的 X509Certificate 实例。
* @return {string[]} 小写域名列表。
*/
collectFrontConfigCertNames(cert) {
const names = [];
const sanText = cert.subjectAltName || '';
for (const part of String(sanText).split(',')) {
const entry = String(part).trim();
if (entry.startsWith('DNS:')) {
const dnsName = entry.slice(4).trim();
if (dnsName) {
names.push(dnsName.toLowerCase());
}
}
}
const subjectText = cert.subject || '';
const cnMatch = /CN\s*=\s*([^,\n]+)/i.exec(String(subjectText));
if (cnMatch && cnMatch[1]) {
names.push(cnMatch[1].trim().toLowerCase());
}
return names;
}
/**
* 判断证书域名列表是否覆盖目标域名(支持精确匹配与通配符 *.example.com)。
*
* @param {string[]} names 证书 SAN/CN 域名列表(小写)。
* @param {string} domain 待校验域名。
* @return {boolean} 是否覆盖。
*/
frontConfigCertCoversDomain(names, domain) {
const target = String(domain).toLowerCase();
if (!target) {
return true;
}
return names.some(name => {
const normalized = String(name).toLowerCase();
if (normalized === target) {
return true;
}
if (normalized.startsWith('*.')) {
const suffix = normalized.slice(1);
return target.endsWith(suffix) && target.length > suffix.length;
}
return false;
});
}
/**
* 校验私钥与证书是否成对:对比两者的 SPKI DER 公钥指纹。
*
* @param {string} keyPem 私钥 PEM 文本。
* @param {Object} cert 已解析的 X509Certificate 实例。
* @return {void} 无返回值。
* @throws {Error} 私钥无法解析或与证书不匹配时抛出,状态码 400,统一文案“证书不合法”。
*/
validateFrontConfigKeyPem(keyPem, cert) {
let publicKey;
try {
publicKey = crypto.createPublicKey(keyPem);
} catch (error) {
throw this.createError('证书不合法', 400);
}
const keySpki = publicKey.export({ type: 'spki', format: 'der' });
const certSpki = cert.publicKey.export({ type: 'spki', format: 'der' });
if (Buffer.compare(keySpki, certSpki) !== 0) {
throw this.createError('证书不合法', 400);
}
}
/**
* 校验当前主体为仓库主体(前端独立部署配置仅仓库主体可操作)。
*
* @return {Promise<Object>} 当前主体对象(含 id/company_name/project/isWarehouse/status)。
* @throws {Error} 签约关系服务不可用时抛出 500;非仓库主体时抛出 403。
*/
async assertFrontConfigWarehouseSubject() {
const storeWarehouseService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.storeWarehouse;
if (!storeWarehouseService || typeof storeWarehouseService.getCurrentSubject !== 'function') {
throw this.createError('签约关系服务不可用', 500);
}
const currentSubject = await storeWarehouseService.getCurrentSubject();
if (!currentSubject || !currentSubject.isWarehouse) {
throw this.createError('仅仓库主体可配置前端独立部署', 403);
}
return currentSubject;
}
/**
* 保存当前仓库前端独立部署品牌配置(upsert,一仓一行,仅品牌字段部分更新)。
*
* 域名与证书不在本接口受理范围:domain 变更必须走 saveFrontCert 重新校验证书;
* cert_pem/key_pem/cert_path/key_path/cert_expire_at 一律不受理(方法层白名单过滤)。
* 保存仍视为一次配置变更:同步状态重置为待同步,写库成功后清理当前 domain 的公共拉取缓存。
*
* @param {Object} [data={}] 请求参数。
* @param {string} [data.title] 站点标题(≤100 字符,空值清空)。
* @param {string} [data.logo_url] Logo 地址(≤255 字符,空值清空)。
* @param {string} [data.favicon_url] 站点 favicon 图标地址(≤255 字符,空值清空)。
* @param {string} [data.login_bg_url] 登录页背景图地址(≤255 字符,空值清空)。
* @param {Object|string} [data.theme] 主题配置(合法 JSON 对象或 JSON 字符串,空值清空)。
* @return {Promise<Object>} 保存后的配置输出对象(同步状态已重置为待同步;证书回显口径与 getFrontConfig 一致)。
* @throws {Error} 非仓库主体时抛出 403;参数非法时抛出 400。
*/
async saveFrontConfig(data = {}) {
const warehouseId = this.getCurrentWarehouseId();
// 仅仓库主体管理员可配置前端独立部署(isWarehouse 判定)
await this.assertFrontConfigWarehouseSubject();
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
if (!configModel || typeof configModel.findOne !== 'function') {
throw this.createError('WarehouseFrontConfig model 不可用', 500);
}
const patch = {};
for (const field of FRONT_CONFIG_TEXT_FIELDS) {
if (Object.prototype.hasOwnProperty.call(data, field.key)) {
patch[field.key] = this.normalizeFrontConfigText(data[field.key], field.name, field.maxLength);
}
}
if (Object.prototype.hasOwnProperty.call(data, 'theme')) {
patch.theme = this.normalizeFrontConfigTheme(data.theme);
}
// 保存即重置同步状态:本次保存待同步
patch.sync_status = 0;
patch.sync_attempts = 0;
patch.last_sync_error = null;
patch.last_synced_at = null;
let record = await configModel.findOne({
where: {
store_id: warehouseId,
},
});
// 品牌字段不改变 domain:写库成功后清理当前 domain 的公共拉取缓存即可
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
try {
if (record) {
await record.update(patch);
} else {
record = await configModel.create({
store_id: warehouseId,
...patch,
});
}
} catch (error) {
// 并发写入兜底:唯一索引冲突统一转为业务错误
if (error && error.name === 'SequelizeUniqueConstraintError') {
const conflictFields = error.fields || {};
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
throw this.createError(`域名 ${patch.domain || ''} 已被其他仓库使用`, 409);
}
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
}
throw error;
}
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
const savedRecord = await configModel.findByPk(record.id);
// 写库成功后清理公共拉取缓存(先写库后清缓存);清缓存失败仅记日志,不影响保存结果
if (previousDomain) {
await this.clearFrontConfigDomainCache(previousDomain)
.catch(error => {
this.ctx.logger.warn('[SettingWarehouseService.saveFrontConfig] 清理前端配置缓存失败: %s', error.message);
});
}
return this.buildFrontConfigOutput(savedRecord, warehouseId);
}
/**
* 上传当前仓库前端独立部署证书(domain + 证书/私钥成对,upsert 该仓库行的证书与域名信息)。
*
* 校验链:证书可解析 → 未生效拒绝 → 已过期拒绝 → 私钥与证书成对 →
* 证书 SAN/CN 覆盖 domain(支持 *.example.com 通配,不覆盖返回 400)→
* domain 全局唯一(非空,409)。
* 证书校验链任一失败均返回统一文案“证书不合法”(400),不返回细节。
* 通过后自动写入 cert_expire_at(证书 validTo 权威值,不接受前端传值),
* 证书/私钥 PEM 内容直接写入 cert_pem/cert_key 列(内容仅定时任务读取,
* 不写暂存文件);cert_path/key_path 保存时置空,避免内容已换而路径陈旧,
* 等待未来定时任务部署后回填真实路径;同时更新该仓库行的 domain/cert_expire_at
* 并重置同步状态;写库成功后清理旧域名与新域名的公共拉取缓存(先写库后清缓存)。
*
* @param {Object} [data={}] 请求参数。
* @param {string} data.domain 仓库自持域名(必填,非空,≤100 字符,全局唯一)。
* @param {string} data.pem 证书 PEM 文本(必填)。
* @param {string} data.key 私钥 PEM 文本(必填,与证书成对)。
* @return {Promise<Object>} 保存后的完整配置输出对象(含证书/私钥原文回显,口径与 getFrontConfig 一致)。
* @throws {Error} 非仓库主体时抛出 403;参数非法/证书不合法时抛出 400(证书校验失败统一文案“证书不合法”);域名重复时抛出 409。
*/
async saveFrontCert(data = {}) {
const warehouseId = this.getCurrentWarehouseId();
// 仅仓库主体管理员可上传前端独立部署证书(isWarehouse 判定)
await this.assertFrontConfigWarehouseSubject();
const configModel = this.ctx.model && this.ctx.model.WarehouseFrontConfig;
if (!configModel || typeof configModel.findOne !== 'function') {
throw this.createError('WarehouseFrontConfig model 不可用', 500);
}
// 入参必填校验:domain 非空且 ≤100;pem/key 必填(nginx 起 HTTPS 需要成对)
const domain = this.normalizeFrontConfigText(data.domain, 'domain', 100);
if (!domain) {
throw this.createError('domain 不能为空', 400);
}
const certPem = this.normalizeFrontConfigPem(data.pem, 'pem');
if (!certPem) {
throw this.createError('pem 不能为空', 400);
}
const keyPem = this.normalizeFrontConfigPem(data.key, 'key');
if (!keyPem) {
throw this.createError('key 不能为空', 400);
}
// 校验链:证书可解析 → 未生效/已过期拒绝 → 私钥匹配 → SAN/CN 覆盖 domain → domain 全局唯一
const cert = this.parseFrontConfigCertPem(certPem);
this.assertFrontConfigCertValid(cert);
this.validateFrontConfigKeyPem(keyPem, cert);
const certNames = this.collectFrontConfigCertNames(cert);
if (!this.frontConfigCertCoversDomain(certNames, domain)) {
throw this.createError('证书不合法', 400);
}
await this.assertFrontConfigDomainUnique(domain, warehouseId);
// 证书/私钥内容直接入库(不再写暂存文件),有效期以证书 validTo 权威写入。
// cert_path/key_path 保存时置空:内容已换而路径陈旧,避免 nginx 误读;
// 等待未来定时任务(Egg schedule/外部 crontab)部署后回填真实路径。
const patch = {
domain,
cert_pem: certPem,
cert_key: keyPem,
cert_path: null,
key_path: null,
cert_expire_at: new Date(cert.validTo),
// 保存即重置同步状态:本次上传待同步
sync_status: 0,
sync_attempts: 0,
last_sync_error: null,
last_synced_at: null,
};
let record = await configModel.findOne({
where: {
store_id: warehouseId,
},
});
// 记录更新前的域名,写库成功后用于清理旧域名公共拉取缓存
const previousDomain = record ? String(record.get('domain') || '').trim() : '';
try {
if (record) {
await record.update(patch);
} else {
record = await configModel.create({
store_id: warehouseId,
...patch,
});
}
} catch (error) {
// 并发写入兜底:唯一索引冲突统一转为业务错误
if (error && error.name === 'SequelizeUniqueConstraintError') {
const conflictFields = error.fields || {};
if (Object.prototype.hasOwnProperty.call(conflictFields, 'domain')) {
throw this.createError(`域名 ${domain} 已被其他仓库使用`, 409);
}
throw this.createError('仓库前端配置保存冲突,请稍后重试', 409);
}
throw error;
}
// 回查一次再输出,避免实例上残留 CURRENT_TIMESTAMP 等字面量
const savedRecord = await configModel.findByPk(record.id);
// 写库成功后清理公共拉取缓存(先写库后清缓存:避免先清后写时并发读把旧值重新写回缓存)。
// 需同时清理旧域名(更新前记录)与新域名(本次上传)两个 key;清缓存失败仅记日志,不影响保存结果。
const affectedDomains = [ ...new Set([ previousDomain, domain ].filter(item => item)) ];
await Promise.all(affectedDomains.map(affectedDomain => this.clearFrontConfigDomainCache(affectedDomain)
.catch(error => {
this.ctx.logger.warn('[SettingWarehouseService.saveFrontCert] 清理前端配置缓存失败: %s', error.message);
})));
return this.buildFrontConfigOutput(savedRecord, warehouseId);
}
}
module.exports = SettingWarehouseService;