- functions.js: 拦截/取消拦截波次感知写订单日志 businessId 误用仓库 ID,改为订单 ID (生产订单 JY2026091813795 已发起拦截但订单详情查不到拦截日志的根因) - rules/v2/processor/config/functionSync: 新增 help 指令、create_work_order=0 时跳过 工单登记、系统级回复与无单号提示、白名单范围修正 - after_sale_reply 模型 + 6 个迁移: create_work_order 字段与相关配置种子 - return_unpack: 列表 count 统计修复、分页排序追加主键防重漏行、视频附加 camera_name - methods/system.json + changes + sync 脚本: 接口文档与权限同步
799 lines
36 KiB
JavaScript
799 lines
36 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* v2 可配置回信引擎 —— 配置管理系统服务层。
|
||
*
|
||
* 规则:
|
||
* - warehouseId 一律从登录上下文 ctx.user.store_id 注入(仓库隔离);
|
||
* - 系统预设锁定:is_system=1 的主数据只读;系统级子类型(warehouse_id=NULL)
|
||
* 的关联行只读(群白名单另尊重关联行 is_system 列);
|
||
* - 关键词属仓库级数据(warehouse_id=当前仓库),可挂在系统级子类型下
|
||
* (keyword.create/update/delete 不做子类型「仓库自定义」限制);
|
||
* - 自定义子类型可挂在系统级或本仓库自定义类型下(subType.create 父类型只校验存在性);
|
||
* - 删除子类型前校验引用(关键词/函数/规则/群/回复),有引用拒绝删除;
|
||
* - 函数表由代码同步权威:只允许改 is_enabled / sort_order,不允许增删改 code;
|
||
* - 取号规则为全局资源,仓库侧只读;
|
||
* - 所有写操作完成后失效该仓库 v2 配置缓存(inbox:v2:cfg:{warehouseId})。
|
||
*/
|
||
class InboxV2ConfigManageService extends Service {
|
||
/** 当前仓库ID(从登录上下文注入)。 */
|
||
get wid() {
|
||
return Number(this.ctx.user?.store_id || 0);
|
||
}
|
||
|
||
/** 写操作后失效缓存。 */
|
||
async _invalidate() {
|
||
try {
|
||
await this.ctx.service.inbox.v2.config.invalidate(this.wid);
|
||
} catch (e) {
|
||
this.ctx.logger.warn(`[inbox v2 manage] 失效缓存失败: ${e.message}`);
|
||
}
|
||
}
|
||
|
||
_op() {
|
||
return this.ctx.app.Sequelize.Op;
|
||
}
|
||
|
||
/**
|
||
* 校验子类型是否属于当前仓库可写范围(仓库自定义,warehouse_id=当前仓库)。
|
||
* @param {number} subTypeId 子类型ID。
|
||
* @param {string} [label] 错误提示中的实体名称。
|
||
* @return {Promise<Object>} 子类型记录(raw)。
|
||
*/
|
||
async _assertWritableSubType(subTypeId, label = '子类型') {
|
||
const row = await this.ctx.model.AfterSaleSubType.findOne({
|
||
where: { id: Number(subTypeId) || 0, warehouse_id: this.wid },
|
||
attributes: [ 'id', 'warehouse_id', 'is_system' ],
|
||
raw: true,
|
||
});
|
||
if (!row) {
|
||
throw new Error(`${label}不存在或不是本仓库自定义(系统级只读)`);
|
||
}
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* 取子类型(含系统级+仓库级,用于只读查询)。
|
||
* @param {number} subTypeId 子类型ID。
|
||
* @return {Promise<Object|null>} 子类型记录(raw),不存在返回 null。
|
||
*/
|
||
async _findSubType(subTypeId) {
|
||
const Op = this._op();
|
||
return this.ctx.model.AfterSaleSubType.findOne({
|
||
where: { id: Number(subTypeId) || 0, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] },
|
||
attributes: [ 'id', 'warehouse_id', 'is_system', 'sub_type', 'type' ],
|
||
raw: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 通用分页参数。
|
||
* @param {Object} [params] 请求参数(含 page/pageSize)。
|
||
* @return {{page: number, pageSize: number}} 归一化分页参数。
|
||
*/
|
||
_page(params = {}) {
|
||
const page = Math.max(1, Number(params.page) || 1);
|
||
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
|
||
return { page, pageSize };
|
||
}
|
||
|
||
// ─────────────────────────── 类型 ───────────────────────────
|
||
|
||
get type() {
|
||
const svc = this;
|
||
return {
|
||
list: params => svc._typeList(params),
|
||
create: params => svc._typeCreate(params),
|
||
update: params => svc._typeUpdate(params),
|
||
delete: params => svc._typeDelete(params),
|
||
};
|
||
}
|
||
|
||
async _typeList(params = {}) {
|
||
const Op = this._op();
|
||
const { page, pageSize } = this._page(params);
|
||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
}
|
||
const { rows, count } = await this.ctx.model.AfterSaleType.findAndCountAll({
|
||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||
});
|
||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||
}
|
||
|
||
async _typeCreate(params = {}) {
|
||
const { AfterSaleType } = this.ctx.model;
|
||
const type = String(params.type || '').trim();
|
||
const name = String(params.name || '').trim();
|
||
if (!type || !name) throw new Error('type 与 name 不能为空');
|
||
if (type.length > 20 || name.length > 50) throw new Error('type(≤20)/name(≤50) 超长');
|
||
const exist = await AfterSaleType.findOne({
|
||
where: { type, warehouse_id: this.wid }, raw: true,
|
||
});
|
||
if (exist) throw new Error(`类型编码 ${type} 已存在`);
|
||
const row = await AfterSaleType.create({
|
||
warehouse_id: this.wid, type, name, is_system: 0, is_enabled: 1,
|
||
sort_order: Number(params.sortOrder) || 0,
|
||
});
|
||
await this._invalidate();
|
||
return { id: row.id, message: '创建成功' };
|
||
}
|
||
|
||
async _typeUpdate(params = {}) {
|
||
const { AfterSaleType } = this.ctx.model;
|
||
const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)');
|
||
if (row.is_system === 1) throw new Error('系统预设类型不可修改');
|
||
const patch = {};
|
||
if (params.name !== undefined) {
|
||
const name = String(params.name || '').trim();
|
||
if (!name) throw new Error('name 不能为空');
|
||
patch.name = name.slice(0, 50);
|
||
}
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||
await AfterSaleType.update(patch, { where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '更新成功' };
|
||
}
|
||
|
||
async _typeDelete(params = {}) {
|
||
const { AfterSaleType, AfterSaleSubType } = this.ctx.model;
|
||
const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)');
|
||
if (row.is_system === 1) throw new Error('系统预设类型不可删除');
|
||
const subCount = await AfterSaleSubType.count({ where: { type: row.type, warehouse_id: this.wid } });
|
||
if (subCount > 0) throw new Error(`该类型下还有 ${subCount} 个子类型,请先删除子类型`);
|
||
await AfterSaleType.destroy({ where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '删除成功' };
|
||
}
|
||
|
||
// ─────────────────────────── 子类型 ───────────────────────────
|
||
|
||
get subType() {
|
||
const svc = this;
|
||
return {
|
||
list: params => svc._subTypeList(params),
|
||
create: params => svc._subTypeCreate(params),
|
||
update: params => svc._subTypeUpdate(params),
|
||
delete: params => svc._subTypeDelete(params),
|
||
};
|
||
}
|
||
|
||
async _subTypeList(params = {}) {
|
||
const Op = this._op();
|
||
const { page, pageSize } = this._page(params);
|
||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||
if (params.type) where.type = String(params.type).trim();
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
}
|
||
const { rows, count } = await this.ctx.model.AfterSaleSubType.findAndCountAll({
|
||
where, order: [[ 'type', 'ASC' ], [ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||
});
|
||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||
}
|
||
|
||
async _subTypeCreate(params = {}) {
|
||
const { AfterSaleSubType } = this.ctx.model;
|
||
const type = String(params.type || '').trim();
|
||
const subType = String(params.subType || '').trim();
|
||
const name = String(params.name || '').trim();
|
||
if (!type || !subType || !name) throw new Error('type/subType/name 不能为空');
|
||
if (subType.length > 50 || name.length > 50) throw new Error('subType/name 超长(≤50)');
|
||
// 自定义子类型可挂在系统级类型或本仓库自定义类型下:父类型只需存在且可见即可;
|
||
// 子类型自身始终写 warehouse_id=当前仓库 + is_system=0,因此后续配置全部可写。
|
||
const Op = this._op();
|
||
const parent = await this.ctx.model.AfterSaleType.findOne({
|
||
where: { type, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] },
|
||
raw: true,
|
||
});
|
||
if (!parent) throw new Error(`类型 ${type} 不存在`);
|
||
const exist = await AfterSaleSubType.findOne({ where: { type, sub_type: subType, warehouse_id: this.wid }, raw: true });
|
||
if (exist) throw new Error(`子类型 ${type}:${subType} 已存在`);
|
||
const row = await AfterSaleSubType.create({
|
||
warehouse_id: this.wid, type, sub_type: subType, name, is_system: 0, is_enabled: 1,
|
||
sort_order: Number(params.sortOrder) || 0,
|
||
});
|
||
await this._invalidate();
|
||
return { id: row.id, message: '创建成功' };
|
||
}
|
||
|
||
async _subTypeUpdate(params = {}) {
|
||
const row = await this._assertWritableSubType(params.id, '子类型');
|
||
const patch = {};
|
||
if (params.name !== undefined) {
|
||
const name = String(params.name || '').trim();
|
||
if (!name) throw new Error('name 不能为空');
|
||
patch.name = name.slice(0, 50);
|
||
}
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||
await this.ctx.model.AfterSaleSubType.update(patch, { where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '更新成功' };
|
||
}
|
||
|
||
async _subTypeDelete(params = {}) {
|
||
const { ctx } = this;
|
||
const row = await this._assertWritableSubType(params.id, '子类型');
|
||
// 级联清理关联(关键词/函数关联/取号关联/群白名单/回复),避免逐个手动清理
|
||
const t = await this.ctx.model.transaction();
|
||
const counts = {};
|
||
try {
|
||
counts.keyword = await ctx.model.AfterSaleKeyword.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||
counts.function = await ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||
counts.rule = await ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||
counts.group = await ctx.model.AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||
counts.reply = await ctx.model.AfterSaleReply.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||
await ctx.model.AfterSaleSubType.destroy({ where: { id: row.id }, transaction: t });
|
||
await t.commit();
|
||
} catch (e) {
|
||
await t.rollback();
|
||
throw e;
|
||
}
|
||
await this._invalidate();
|
||
return {
|
||
message: `删除成功(已级联清理:关键词 ${counts.keyword}、函数关联 ${counts.function}、取号关联 ${counts.rule}、群白名单 ${counts.group}、回复 ${counts.reply})`,
|
||
};
|
||
}
|
||
|
||
// ─────────────────────────── 关键词 ───────────────────────────
|
||
|
||
get keyword() {
|
||
const svc = this;
|
||
return {
|
||
list: params => svc._keywordList(params),
|
||
create: params => svc._keywordCreate(params),
|
||
update: params => svc._keywordUpdate(params),
|
||
delete: params => svc._keywordDelete(params),
|
||
};
|
||
}
|
||
|
||
async _keywordList(params = {}) {
|
||
const Op = this._op();
|
||
const { page, pageSize } = this._page(params);
|
||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||
if (params.subTypeId) where.sub_type_id = Number(params.subTypeId) || 0;
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
}
|
||
const { rows, count } = await this.ctx.model.AfterSaleKeyword.findAndCountAll({
|
||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||
});
|
||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||
}
|
||
|
||
/**
|
||
* 同词查重(可见范围:系统级 + 本仓库)。
|
||
* @param {string} keyword 关键词。
|
||
* @param {number} [excludeId] 排除自身ID(更新场景)。
|
||
* @return {Promise<string|null>} 重复时的提示文案(含所在级别与子类型),无重复返回 null。
|
||
*/
|
||
async _keywordDupDescribe(keyword, excludeId) {
|
||
const Op = this._op();
|
||
const rows = await this.ctx.model.AfterSaleKeyword.findAll({
|
||
where: {
|
||
keyword,
|
||
[Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }],
|
||
},
|
||
attributes: [ 'id', 'sub_type_id', 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
const dup = rows.find(r => Number(r.id) !== Number(excludeId || 0));
|
||
if (!dup) return null;
|
||
const sub = await this.ctx.model.AfterSaleSubType.findOne({
|
||
where: { id: dup.sub_type_id },
|
||
attributes: [ 'type', 'sub_type', 'name' ],
|
||
raw: true,
|
||
});
|
||
const level = dup.warehouse_id === null ? '系统级' : '本仓库';
|
||
const rule = sub ? `${sub.type}:${sub.sub_type}(${sub.name})` : `子类型ID ${dup.sub_type_id}`;
|
||
return `关键词「${keyword}」已存在于【${level}】${rule}下,不可重复添加`;
|
||
}
|
||
|
||
async _keywordCreate(params = {}) {
|
||
const { AfterSaleKeyword } = this.ctx.model;
|
||
const subTypeId = Number(params.subTypeId) || 0;
|
||
const keyword = String(params.keyword || '').trim();
|
||
if (!subTypeId || !keyword) throw new Error('subTypeId 与 keyword 不能为空');
|
||
if (keyword.length > 100) throw new Error('关键词超长(≤100)');
|
||
// 关键词为仓库级数据(warehouse_id=当前仓库):允许绑定系统级子类型或本仓库自定义子类型,
|
||
// 只校验子类型存在,不做「仓库自定义」限制(与 keyword.update / keyword.delete 的可写范围对齐)。
|
||
const subType = await this._findSubType(subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
// 同词查重(系统级+本仓库),重复时提示在哪个规则(子类型)下
|
||
const dupMsg = await this._keywordDupDescribe(keyword);
|
||
if (dupMsg) throw new Error(dupMsg);
|
||
const row = await AfterSaleKeyword.create({
|
||
warehouse_id: this.wid, sub_type_id: subTypeId, keyword, is_system: 0, is_enabled: 1,
|
||
sort_order: Number(params.sortOrder) || 0,
|
||
});
|
||
await this._invalidate();
|
||
return { id: row.id, message: '创建成功' };
|
||
}
|
||
|
||
async _keywordUpdate(params = {}) {
|
||
const { AfterSaleKeyword } = this.ctx.model;
|
||
const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)');
|
||
if (row.is_system === 1) throw new Error('系统预设关键词不可修改');
|
||
const patch = {};
|
||
if (params.keyword !== undefined) {
|
||
const keyword = String(params.keyword || '').trim();
|
||
if (!keyword) throw new Error('keyword 不能为空');
|
||
const sliced = keyword.slice(0, 100);
|
||
// 改词同样查重(排除自身),重复时提示在哪个规则(子类型)下
|
||
const dupMsg = await this._keywordDupDescribe(sliced, row.id);
|
||
if (dupMsg) throw new Error(dupMsg);
|
||
patch.keyword = sliced;
|
||
}
|
||
if (params.subTypeId) {
|
||
await this._assertWritableSubType(params.subTypeId, '子类型');
|
||
patch.sub_type_id = Number(params.subTypeId);
|
||
}
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||
await AfterSaleKeyword.update(patch, { where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '更新成功' };
|
||
}
|
||
|
||
async _keywordDelete(params = {}) {
|
||
const { AfterSaleKeyword } = this.ctx.model;
|
||
const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)');
|
||
if (row.is_system === 1) throw new Error('系统预设关键词不可删除');
|
||
await AfterSaleKeyword.destroy({ where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '删除成功' };
|
||
}
|
||
|
||
// ─────────────────────────── 取号规则(全局只读) ───────────────────────────
|
||
|
||
get numberRule() {
|
||
const svc = this;
|
||
return { list: params => svc._numberRuleList(params) };
|
||
}
|
||
|
||
async _numberRuleList() {
|
||
const rows = await this.ctx.model.InboxNumberRule.findAll({
|
||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||
});
|
||
return { list: rows };
|
||
}
|
||
|
||
// ─────────────────────────── 处理函数(代码同步权威,只允许开关/排序) ───────────────────────────
|
||
|
||
get function() {
|
||
const svc = this;
|
||
return {
|
||
list: params => svc._functionList(params),
|
||
update: params => svc._functionUpdate(params),
|
||
};
|
||
}
|
||
|
||
async _functionList(params = {}) {
|
||
const Op = this._op();
|
||
const where = {};
|
||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||
}
|
||
if (params.keyword) {
|
||
const like = `%${String(params.keyword).trim()}%`;
|
||
where[Op.or] = [{ function_code: { [Op.like]: like } }, { name: { [Op.like]: like } }];
|
||
}
|
||
const rows = await this.ctx.model.AfterSaleFunction.findAll({
|
||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||
});
|
||
// 附上代码注册表中是否存在(便于识别已下线函数)
|
||
let registry = null;
|
||
try {
|
||
registry = this.ctx.service.inbox.functions.registry;
|
||
} catch (e) { /* ignore */ }
|
||
return {
|
||
list: rows.map(r => ({
|
||
...r,
|
||
in_registry: registry instanceof Map ? registry.has(r.function_code) : null,
|
||
})),
|
||
};
|
||
}
|
||
|
||
async _functionUpdate(params = {}) {
|
||
const { AfterSaleFunction } = this.ctx.model;
|
||
const row = await AfterSaleFunction.findOne({ where: { id: Number(params.id) || 0 }, raw: true });
|
||
if (!row) throw new Error('函数不存在');
|
||
const patch = {};
|
||
// 启用状态硬编码(代码注册表存在即启用),接口只允许调整排序
|
||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||
if (Object.keys(patch).length === 0) throw new Error('只允许更新 sortOrder(是否启用由代码硬编码,不做接口配置)');
|
||
await AfterSaleFunction.update(patch, { where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '更新成功' };
|
||
}
|
||
|
||
// ─────────────────────────── 回复 ───────────────────────────
|
||
|
||
get reply() {
|
||
const svc = this;
|
||
return {
|
||
create: params => svc._replyCreate(params),
|
||
update: params => svc._replyUpdate(params),
|
||
delete: params => svc._replyDelete(params),
|
||
// 推荐接口:保存(upsert)/ 还原(删除仓库级,回退系统级)
|
||
save: params => svc._replySave(params),
|
||
restore: params => svc._replyRestore(params),
|
||
merged: params => svc._replyMerged(params),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 保存仓库级回复配置(upsert):按传入字段保存,未传字段保持原值;
|
||
* 无仓库级配置时按传入字段创建(默认 reply 空、is_reply=1、create_work_order=1)。
|
||
* 停用即回退系统级语义由 restore 承担,不再提供 isEnabled 开关。
|
||
* @param {Object} params 请求参数。
|
||
* @return {Promise<Object>} 保存结果。
|
||
*/
|
||
async _replySave(params = {}) {
|
||
const { AfterSaleReply } = this.ctx.model;
|
||
const subTypeId = Number(params.subTypeId) || 0;
|
||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||
const subType = await this._findSubType(subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
|
||
const patch = {};
|
||
if (params.reply !== undefined && params.reply !== null) patch.reply = String(params.reply).slice(0, 2000);
|
||
if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 0 ? 0 : 1;
|
||
if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 0 ? 0 : 1;
|
||
if (params.noNumberHint !== undefined && params.noNumberHint !== null) patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null;
|
||
|
||
const exist = await AfterSaleReply.findOne({
|
||
where: { warehouse_id: this.wid, sub_type_id: subTypeId },
|
||
raw: true,
|
||
});
|
||
if (exist) {
|
||
if (Object.keys(patch).length > 0) {
|
||
await AfterSaleReply.update(patch, { where: { id: exist.id } });
|
||
}
|
||
} else {
|
||
await AfterSaleReply.create({
|
||
warehouse_id: this.wid,
|
||
sub_type_id: subTypeId,
|
||
reply: patch.reply !== undefined ? patch.reply : '',
|
||
is_reply: patch.is_reply !== undefined ? patch.is_reply : 1,
|
||
create_work_order: patch.create_work_order !== undefined ? patch.create_work_order : 1,
|
||
no_number_hint: patch.no_number_hint !== undefined ? patch.no_number_hint : null,
|
||
is_enabled: 1,
|
||
});
|
||
}
|
||
await this._invalidate();
|
||
return {
|
||
id: exist ? exist.id : null,
|
||
message: exist ? '保存成功' : '创建成功',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 还原仓库级回复配置:删除仓库级行,回退到系统级配置。
|
||
* @param {Object} params 请求参数。
|
||
* @return {Promise<Object>} 还原结果。
|
||
*/
|
||
async _replyRestore(params = {}) {
|
||
const { AfterSaleReply } = this.ctx.model;
|
||
const subTypeId = Number(params.subTypeId) || 0;
|
||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||
const row = await AfterSaleReply.findOne({
|
||
where: { warehouse_id: this.wid, sub_type_id: subTypeId },
|
||
raw: true,
|
||
});
|
||
if (row) {
|
||
await AfterSaleReply.destroy({ where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '已还原为系统级配置' };
|
||
}
|
||
return { message: '本仓库无自定义回复配置,已是系统级配置' };
|
||
}
|
||
|
||
/**
|
||
* 回复配置(合并后生效配置):以全部有效子类型(系统级+本仓库)为基底,
|
||
* 每个子类型只返回一条「生效配置」:本仓库有自定义则整行覆盖系统级;
|
||
* 无任何回复配置行的子类型返回初始值(reply={back_text}、is_reply=1、create_work_order=1、
|
||
* no_number_hint 按取号规则:express_name→快递提示、有其他规则→运单号提示、无规则→空),
|
||
* 保证任何仓库都有完整列表。无启用状态字段:停用即回退系统级由 restore 承担。
|
||
* @param {Object} params 请求参数。
|
||
* @return {Promise<Object>} { merged, total } 合并后生效配置数组与总数。
|
||
*/
|
||
async _replyMerged(params = {}) {
|
||
const Op = this._op();
|
||
const wh = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||
// 拉全量(系统级+本仓库级)在内存合并,数据量小
|
||
const [ rows, subs, ruleRelRows, ruleRows ] = await Promise.all([
|
||
this.ctx.model.AfterSaleReply.findAll({
|
||
where: wh,
|
||
order: [[ 'sub_type_id', 'ASC' ], [ 'warehouse_id', 'ASC' ]],
|
||
raw: true,
|
||
}),
|
||
this.ctx.model.AfterSaleSubType.findAll({
|
||
where: wh,
|
||
attributes: [ 'id', 'type', 'sub_type', 'name', 'warehouse_id' ],
|
||
raw: true,
|
||
}),
|
||
this.ctx.model.AfterSaleSubTypeRule.findAll({
|
||
attributes: [ 'sub_type_id', 'number_rule_id' ],
|
||
raw: true,
|
||
}),
|
||
this.ctx.model.InboxNumberRule.findAll({
|
||
attributes: [ 'id', 'target' ],
|
||
raw: true,
|
||
}),
|
||
]);
|
||
const ruleTargets = {};
|
||
for (const n of ruleRows) ruleTargets[n.id] = n.target;
|
||
const subTargets = {};
|
||
for (const rel of ruleRelRows) {
|
||
const t = ruleTargets[rel.number_rule_id];
|
||
if (!t) continue;
|
||
if (!subTargets[rel.sub_type_id]) subTargets[rel.sub_type_id] = [];
|
||
if (!subTargets[rel.sub_type_id].includes(t)) subTargets[rel.sub_type_id].push(t);
|
||
}
|
||
const initialHint = st => {
|
||
const ts = subTargets[st.id] || [];
|
||
if (ts.includes('express_name')) {
|
||
return '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)';
|
||
}
|
||
return ts.length > 0 ? '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)' : '';
|
||
};
|
||
const mergedMap = new Map();
|
||
for (const r of rows) {
|
||
const isWh = r.warehouse_id !== null && r.warehouse_id !== undefined;
|
||
const existing = mergedMap.get(r.sub_type_id);
|
||
if (!existing || (isWh && !existing._wh)) {
|
||
mergedMap.set(r.sub_type_id, { ...r, _wh: isWh });
|
||
}
|
||
}
|
||
const subMap = {};
|
||
for (const s of subs) subMap[s.id] = s;
|
||
const toRow = (st, r) => ({
|
||
id: r ? r.id : null,
|
||
sub_type_id: st.id,
|
||
type: String(st.type || ''),
|
||
sub_type: String(st.sub_type || ''),
|
||
sub_type_name: String(st.name || ''),
|
||
warehouse_id: r ? (r._wh ? r.warehouse_id : null) : (st.warehouse_id === null || st.warehouse_id === undefined ? null : this.wid),
|
||
is_custom: r ? (r._wh ? 1 : 0) : (st.warehouse_id === null || st.warehouse_id === undefined ? 0 : 1),
|
||
reply: r ? String(r.reply || '') : '{back_text}',
|
||
is_reply: r ? (Number(r.is_reply) === 1 ? 1 : 0) : 1,
|
||
create_work_order: r ? (Number(r.create_work_order) === 0 ? 0 : 1) : 1,
|
||
no_number_hint: r ? (r.no_number_hint ? String(r.no_number_hint) : '') : initialHint(st),
|
||
created_at: r ? r.created_at : null,
|
||
updated_at: r ? r.updated_at : null,
|
||
});
|
||
let list = subs.map(st => {
|
||
const r = mergedMap.get(st.id);
|
||
return toRow(st, r);
|
||
});
|
||
if (params.subTypeId) {
|
||
const sid = Number(params.subTypeId) || 0;
|
||
list = list.filter(x => x.sub_type_id === sid);
|
||
}
|
||
const total = list.length;
|
||
return { merged: list, total };
|
||
}
|
||
|
||
async _replyCreate(params = {}) {
|
||
const { AfterSaleReply } = this.ctx.model;
|
||
const subTypeId = Number(params.subTypeId) || 0;
|
||
const reply = String(params.reply || '');
|
||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||
if (!reply) throw new Error('reply 不能为空');
|
||
// 允许系统级子类型:仓库级回复的语义就是覆盖系统级配置(读取时仓库级优先)
|
||
const subType = await this._findSubType(subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
const exist = await AfterSaleReply.findOne({ where: { warehouse_id: this.wid, sub_type_id: subTypeId }, raw: true });
|
||
if (exist) throw new Error('该子类型已有仓库级回复,请用更新');
|
||
const row = await AfterSaleReply.create({
|
||
warehouse_id: this.wid, sub_type_id: subTypeId, reply,
|
||
is_reply: Number(params.isReply) === 0 ? 0 : 1,
|
||
create_work_order: Number(params.createWorkOrder) === 0 ? 0 : 1,
|
||
no_number_hint: params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null,
|
||
is_enabled: 1,
|
||
});
|
||
await this._invalidate();
|
||
return { id: row.id, message: '创建成功' };
|
||
}
|
||
|
||
async _replyUpdate(params = {}) {
|
||
const { AfterSaleReply } = this.ctx.model;
|
||
const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)');
|
||
const patch = {};
|
||
if (params.reply !== undefined) {
|
||
const reply = String(params.reply || '');
|
||
if (!reply) throw new Error('reply 不能为空');
|
||
patch.reply = reply;
|
||
}
|
||
if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 1 ? 1 : 0;
|
||
if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 1 ? 1 : 0;
|
||
if (params.noNumberHint !== undefined) {
|
||
patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null;
|
||
}
|
||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||
await AfterSaleReply.update(patch, { where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '更新成功' };
|
||
}
|
||
|
||
async _replyDelete(params = {}) {
|
||
const { AfterSaleReply } = this.ctx.model;
|
||
const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||
if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)');
|
||
await AfterSaleReply.destroy({ where: { id: row.id } });
|
||
await this._invalidate();
|
||
return { message: '删除成功' };
|
||
}
|
||
|
||
// ─────────────────────────── 关联关系(set=全量替换,仅本仓库自定义子类型可写) ───────────────────────────
|
||
|
||
get relation() {
|
||
const svc = this;
|
||
return {
|
||
function: {
|
||
list: params => svc._relFunctionList(params),
|
||
set: params => svc._relFunctionSet(params),
|
||
},
|
||
rule: {
|
||
list: params => svc._relRuleList(params),
|
||
set: params => svc._relRuleSet(params),
|
||
},
|
||
group: {
|
||
list: params => svc._relGroupList(params),
|
||
set: params => svc._relGroupSet(params),
|
||
},
|
||
};
|
||
}
|
||
|
||
async _relFunctionList(params = {}) {
|
||
const subType = await this._findSubType(params.subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
const rows = await this.ctx.model.AfterSaleSubTypeFunction.findAll({
|
||
where: { sub_type_id: subType.id },
|
||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||
});
|
||
return { list: rows };
|
||
}
|
||
|
||
async _relFunctionSet(params = {}) {
|
||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||
const items = Array.isArray(params.items) ? params.items : [];
|
||
const funcRows = await this.ctx.model.AfterSaleFunction.findAll({ attributes: [ 'id' ], raw: true });
|
||
const validIds = new Set(funcRows.map(r => r.id));
|
||
const t = await this.ctx.model.transaction();
|
||
try {
|
||
await this.ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: subType.id }, transaction: t });
|
||
let order = 0;
|
||
for (const item of items) {
|
||
const fid = Number(item.functionId) || 0;
|
||
if (!validIds.has(fid)) continue;
|
||
await this.ctx.model.AfterSaleSubTypeFunction.create({
|
||
sub_type_id: subType.id, function_id: fid,
|
||
sort_order: Number(item.sortOrder) || order,
|
||
}, { transaction: t });
|
||
order += 1;
|
||
}
|
||
await t.commit();
|
||
} catch (e) {
|
||
await t.rollback();
|
||
throw e;
|
||
}
|
||
await this._invalidate();
|
||
return { message: '关联已更新' };
|
||
}
|
||
|
||
async _relRuleList(params = {}) {
|
||
const subType = await this._findSubType(params.subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
const rows = await this.ctx.model.AfterSaleSubTypeRule.findAll({
|
||
where: { sub_type_id: subType.id },
|
||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||
});
|
||
return { list: rows };
|
||
}
|
||
|
||
async _relRuleSet(params = {}) {
|
||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||
const items = Array.isArray(params.items) ? params.items : [];
|
||
const ruleRows = await this.ctx.model.InboxNumberRule.findAll({ attributes: [ 'id' ], raw: true });
|
||
const validIds = new Set(ruleRows.map(r => r.id));
|
||
const t = await this.ctx.model.transaction();
|
||
try {
|
||
await this.ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: subType.id }, transaction: t });
|
||
let order = 0;
|
||
for (const item of items) {
|
||
const rid = Number(item.ruleId) || 0;
|
||
if (!validIds.has(rid)) continue;
|
||
await this.ctx.model.AfterSaleSubTypeRule.create({
|
||
sub_type_id: subType.id, number_rule_id: rid,
|
||
sort_order: Number(item.sortOrder) || order,
|
||
}, { transaction: t });
|
||
order += 1;
|
||
}
|
||
await t.commit();
|
||
} catch (e) {
|
||
await t.rollback();
|
||
throw e;
|
||
}
|
||
await this._invalidate();
|
||
return { message: '关联已更新' };
|
||
}
|
||
|
||
async _relGroupList(params = {}) {
|
||
const subType = await this._findSubType(params.subTypeId);
|
||
if (!subType) throw new Error('子类型不存在');
|
||
const rows = await this.ctx.model.AfterSaleSubTypeGroup.findAll({
|
||
where: { sub_type_id: subType.id },
|
||
order: [[ 'group_type', 'ASC' ], [ 'sub_group', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||
});
|
||
return { list: rows };
|
||
}
|
||
|
||
async _relGroupSet(params = {}) {
|
||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||
const items = Array.isArray(params.items) ? params.items : [];
|
||
const { AfterSaleSubTypeGroup } = this.ctx.model;
|
||
const validTypes = [ 'store', 'warehouse', 'express', '*' ];
|
||
const t = await this.ctx.model.transaction();
|
||
try {
|
||
// 系统预设行(is_system=1)不可删:保留并合并
|
||
const sysRows = await AfterSaleSubTypeGroup.findAll({
|
||
where: { sub_type_id: subType.id, is_system: 1 }, raw: true, transaction: t,
|
||
});
|
||
await AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: subType.id, is_system: 0 }, transaction: t });
|
||
const seen = new Set();
|
||
for (const row of sysRows) {
|
||
seen.add(`${row.group_type}:${row.sub_group}`);
|
||
}
|
||
// 通配覆盖:groupType='*' 覆盖所有具体类型行;主类型内 subGroup='*' 覆盖该主类型其他具体行
|
||
const norm = items
|
||
.map(it => ({
|
||
gt: String(it.groupType || '').trim(),
|
||
sg: String(it.subGroup || '').trim(),
|
||
so: Number(it.sortOrder) || 0,
|
||
}))
|
||
.filter(x => validTypes.includes(x.gt));
|
||
const hasWildcardAll = norm.some(x => x.gt === '*');
|
||
const wildcardTypes = new Set(norm.filter(x => x.gt !== '*' && x.sg === '*').map(x => x.gt));
|
||
for (const { gt, sg: rawSg, so } of norm) {
|
||
let sg = rawSg;
|
||
if (gt === '*') sg = ''; // 全通配时子类型无意义,归一化为空
|
||
if (hasWildcardAll && gt !== '*') continue; // 有全部时覆盖掉对应类型
|
||
if (gt !== '*' && wildcardTypes.has(gt) && sg !== '*') continue; // 主类型内通配覆盖具体行
|
||
const key = `${gt}:${sg}`;
|
||
if (seen.has(key)) continue;
|
||
seen.add(key);
|
||
await AfterSaleSubTypeGroup.create({
|
||
sub_type_id: subType.id, group_type: gt, sub_group: sg,
|
||
is_system: 0, sort_order: so,
|
||
}, { transaction: t });
|
||
}
|
||
await t.commit();
|
||
} catch (e) {
|
||
await t.rollback();
|
||
throw e;
|
||
}
|
||
await this._invalidate();
|
||
return { message: '关联已更新' };
|
||
}
|
||
}
|
||
|
||
module.exports = InboxV2ConfigManageService;
|