feat: 拦截链路全流程完善 — 新增interceptScan + 运单表同步 + 工单通知

新增:
- order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态
- afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群

修复:
- confirmIntercept: 补运单is_back同步(仅限is_intercept=Y),补工单创建+通知
- batchIntercept: 补运单is_intercept同步,补工单创建+通知
- batchUnintercept: 补运单is_intercept/is_back清除
- Qimen/OpenAPI cancel: 补运单is_intercept同步,补工单创建+通知
- interceptScan: 删除死查询,加空指针兜底

文档:
- methods/system.json: interceptScan + confirmIntercept 完整API文档
- methods/changes/system.json: 变更记录
This commit is contained in:
liufumingren 2026-08-12 20:47:19 +08:00
parent 4c5807dbbc
commit b436b6dd9e
35 changed files with 5951 additions and 1111 deletions

View File

@ -86,11 +86,12 @@ module.exports = app => {
/**
* 售后单状态枚举。
* @type {{pending: string, processing: string, completed: string, closed: string, cancelled: string}}
* @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}}
*/
const AFTER_SALE_STATUS = {
pending: '待处理',
processing: '处理中',
pending_feedback: '等待外部反馈',
completed: '已完成',
closed: '已关闭',
cancelled: '已取消',
@ -156,7 +157,7 @@ module.exports = app => {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '售后状态:pending=待处理, processing=处理中, completed=已完成, closed=已关闭, cancelled=已取消',
comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消',
},
/** 优先级 */
priority: {
@ -207,6 +208,12 @@ module.exports = app => {
allowNull: true,
comment: '完结时间(状态变为 completed 时写入)',
},
/** 下次跟进时间 */
followup_at: {
type: DATE,
allowNull: true,
comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进',
},
/** 仓库理赔标记 */
claim_needed: {
type: TINYINT(1),
@ -258,6 +265,12 @@ module.exports = app => {
allowNull: true,
comment: '运单号(冗余字段,方便查询展示)',
},
/** 订单ID */
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入',
},
/** 发货订单ID */
order_delivery_id: {
type: BIGINT(20).UNSIGNED,

View File

@ -6,21 +6,22 @@
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 售后进度步骤 Model(含常量挂载)
*/
module.exports = app => {
const { STRING, BIGINT, TEXT, TINYINT, DATE } = app.Sequelize;
const { STRING, BIGINT, TEXT, DATE } = app.Sequelize;
// ============================
// 枚举常量定义
// ============================
/**
* 步骤状态枚举。
* @type {{0: string, 1: string, 2: string, 3: string}}
* 步骤状态枚举(与 wms_after_sale.status 一致)。
*/
const STEP_STATUS = {
0: '待开始',
1: '进行中',
2: '已完成',
3: '已跳过',
pending: '待处理',
processing: '处理中',
pending_feedback: '等待外部反馈',
completed: '已完成',
closed: '已关闭',
cancelled: '已取消',
};
// ============================
@ -41,12 +42,12 @@ module.exports = app => {
allowNull: false,
comment: '关联售后主表ID(wms_after_sale.id)',
},
/** 步骤状态 */
/** 步骤记录时售后主表的状态 */
step_status: {
type: TINYINT(3).UNSIGNED,
type: STRING(20),
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过',
defaultValue: 'processing',
comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled',
},
/** 操作人账户ID */
operator_id: {

View File

@ -8,7 +8,7 @@
* @return {Object} Sequelize Model 定义。
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize;
const InboxGroup = app.model.define('inbox_group', {
id: {
@ -80,6 +80,11 @@ module.exports = app => {
allowNull: true,
comment: '系统快递编码(仅群类型为 express 时必填)',
},
ext_data: {
type: JSON_TYPE,
allowNull: true,
comment: '群扩展数据(IM平台信息等)',
},
created_at: {
type: DATE,
allowNull: false,

View File

@ -216,6 +216,16 @@ module.exports = app => {
max: '23:59',
description: '截单时间,格式 HH:mm,如 16:00',
}),
Object.freeze({
key: 'after_sale_followup_hours',
name: '售后跟进时间(h)',
type: 'integer',
default: 24,
required: false,
min: 1,
max: 720,
description: '售后单设为等待外部反馈后,默认多少小时需二次跟进。具体类型可在代码枚举中覆盖',
}),
]);
const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => {
result[field.key] = field;

370
app/service/inbox/ai.js Normal file
View File

@ -0,0 +1,370 @@
'use strict';
const Service = require('egg').Service;
/**
* AI 推理引擎。
* 负责调用 DeepSeek API 进行多轮推理:思考→调函数→评估→(重复或输出)。
* 函数注册、分组管理等纯工具箱逻辑在 inbox/functions.js 中。
*/
class InboxAIService extends Service {
/**
* 调用 DeepSeek API。
*
* @param {Array<{role: string, content: string}>} messages 消息列表。
* @param {Object} [options] 额外选项。
* @return {Promise<string>} AI 返回的文本内容。
*/
async callDeepSeek(messages, options = {}) {
const { ctx } = this;
const apiKey = ctx.app.config.deepseek.apiKey;
const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) {
throw new Error('DeepSeek API Key 未配置');
}
const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: { Authorization: `Bearer ${apiKey}` },
data: {
model: 'deepseek-v4-pro',
messages,
temperature: options.temperature ?? 0,
max_tokens: options.maxTokens ?? 1000,
},
timeout: options.timeout || 30000,
});
if (result.status !== 200 || !result.data) {
throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`);
}
let content = result.data.choices?.[0]?.message?.content || '';
// 清理 markdown 代码块
content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
return content.trim();
}
/**
* 获取智能对话历史上下文。
* 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。
* 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。
*
* @param {Object} opts 查询选项。
* @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。
* @param {number} [opts.maxMessages=5] 最大历史消息数。
* @return {Promise<Array<{role: string, content: string, seq?: number}>>} 历史消息列表。
*/
async getConversationHistory(opts = {}) {
const parentId = Number(opts.parentId) || 0;
const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5));
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const groupId = String(ctx.inboxContext?.group_id || '').trim();
const userId = String(ctx.inboxContext?.user_id || '').trim();
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
// 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯
if (!groupId || !userId || !warehouseId) {
if (!parentId) return [];
try {
const history = [];
let currentId = parentId;
const visited = new Set();
while (currentId && history.length < maxMessages) {
if (visited.has(currentId)) break;
visited.add(currentId);
const msg = await InboxMessage.findOne({
attributes: [ 'id', 'parent_id', 'direction', 'content' ],
where: { id: currentId },
raw: true,
});
if (!msg) break;
history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' });
currentId = msg.parent_id;
}
return history;
} catch (error) {
ctx.logger.warn(`[inbox ai] 对话历史回退查询失败: ${error.message}`);
return [];
}
}
// 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员)
try {
const messages = await InboxMessage.findAll({
attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ],
where: {
warehouse_id: warehouseId,
group_id: groupId,
direction: { [Op.in]: [ 'inbound', 'outbound' ] },
},
order: [[ 'created_at', 'DESC' ]],
limit: maxMessages,
raw: true,
});
if (messages.length === 0) return [];
// 升序排列,附加上下文信息供 AI 判断真人接管
const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set();
return messages.reverse().map(msg => {
const u = String(msg.user_id || '').trim();
const name = String(msg.user_name || '').trim();
const isBlocked = u && blockedUsers.has(u);
return {
role: msg.direction === 'inbound' ? 'user' : 'assistant',
content: msg.content || '',
user_id: u || null,
user_name: name || null,
blocked: isBlocked,
};
});
} catch (error) {
ctx.logger.warn(`[inbox ai] 智能对话历史查询失败: ${error.message}`);
return [];
}
}
/**
* DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。
*
* 每轮 AI 返回 JSON,通过 action 字段决定行为:
* { "action": "call", "function": "函数名", "params": {...}, "reason": "..." }
* { "action": "reply", "reply": "最终回复内容" }
*
* 最多 MAX_ROUNDS 轮,防止无限循环。
*
* @param {Object} data 消息数据。
* @param {string} data.content 消息正文。
* @param {Object} [data.ext_data] 透传数据。
* @param {number} [data.parentId] 父消息ID。
* @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。
*/
async processWithAI(data = {}) {
const { ctx } = this;
const content = String(data.content || '').trim();
if (!content) {
return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null };
}
const funcSvc = ctx.service.inbox.functions;
const groupsSvc = ctx.service.inbox.groups;
const activeGroups = groupsSvc.resolveActiveGroups();
ctx.logger.info(`[inbox ai] 当前活跃分组: ${activeGroups.join(', ')}`);
const functionListText = groupsSvc.buildFunctionListText(activeGroups);
if (!functionListText) {
ctx.logger.info('[inbox ai] 当前上下文无可用的 AI 函数');
return { reply: null, functionName: null, functionResult: null };
}
// 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文
const history = await this.getConversationHistory({
parentId: data.parentId,
maxMessages: 10,
});
const historyContext = history.length > 0
? history.map(h => {
const tag = h.blocked ? '[已屏蔽]' : '';
return `[${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}]${tag}: ${h.content}`;
}).join('\n')
: '(无历史)';
const MAX_ROUNDS = 5;
const executedFunctions = [];
const thoughts = [];
let finalReply = null;
let lastFunctionName = null;
let lastFunctionResult = null;
const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。
已注册函数:\n${functionListText}\n
=== 群最近对话历史 ===
${historyContext}
===
对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。
如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。
你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON:
如果还需要调用函数获取信息:
{
"action": "call",
"function": "函数名",
"params": { "参数名": "参数值" },
"reason": "为什么需要这个函数"
}
如果信息充足可以回复用户了:
{
"action": "reply",
"reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)"
}
如果消息无需回复(用户只是确认、道谢、告别或表示自己处理):
{
"action": "silent"
}
真人接管判断规则(优先级最高,先于所有其他规则):
- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent
- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户
- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复
一般约束:
- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复
- 同一函数不要重复调用(除非参数不同)
- 信息中如果携带了@标记,说明信息是针对某个特定用户的,请注意是否需要回复该用户
- 如果函数执行失败,换其他方式或直接告知用户
- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性
- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88")
- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候
- 无法判断时,宁可回复也不要 silent
- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定
- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品
- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品
- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接
- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对
- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理
- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知
- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`;
// 多轮推理循环
for (let round = 1; round <= MAX_ROUNDS; round++) {
const contextLines = [];
if (executedFunctions.length > 0) {
contextLines.push('已执行的函数及结果:');
executedFunctions.forEach((f, i) => {
contextLines.push(
` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}`
);
});
}
const messages = [
{ role: 'system', content: systemPrompt },
...history,
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
{ role: 'user', content: round === 1
? content
: (executedFunctions.length > 0
? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮`
: `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`),
},
];
let raw = '';
try {
raw = await this.callDeepSeek(messages, { maxTokens: 600 });
ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`);
const result = JSON.parse(raw);
// 记录思考过程
thoughts.push({
round,
action: result.action || 'unknown',
function: result.function || null,
params: result.params || null,
reason: result.reason || null,
});
if (result.action === 'reply') {
finalReply = String(result.reply || '').trim();
if (!finalReply) finalReply = '已处理完成';
break;
}
if (result.action === 'silent') {
// 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent
const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory');
if (actionFunctions.length > 0) {
ctx.logger.info('[inbox ai] 已有操作类函数调用,忽略 silent 继续要求回复');
continue;
}
ctx.logger.info('[inbox ai] AI 判定无需回复,跳过回执');
return { reply: null, functionName: null, functionResult: null, thoughts, skip: true };
}
if (result.action === 'call' && result.function) {
const fnName = String(result.function).trim();
const params = result.params || {};
if (fnName === 'none' || fnName === 'stop') {
finalReply = result.reply || '已处理完成';
break;
}
lastFunctionName = fnName;
lastFunctionResult = await funcSvc.callFunction(fnName, params);
executedFunctions.push({ name: fnName, params, result: lastFunctionResult });
// 补充函数执行结果到思考记录
const lastThought = thoughts[thoughts.length - 1];
if (lastThought) lastThought.functionResult = lastFunctionResult;
ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`);
// 最后一轮强制输出
if (round === MAX_ROUNDS) {
finalReply = lastFunctionResult?.data?.message
|| lastFunctionResult?.data?.greeting
|| JSON.stringify(lastFunctionResult?.data || lastFunctionResult);
}
continue;
}
// 无法解析 → 尝试提取 reply
finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求';
break;
} catch (error) {
ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`);
// 不是 JSON → 当作文本回复
if (error instanceof SyntaxError && raw) {
finalReply = raw;
break;
}
// 最后一轮兜底
if (round === MAX_ROUNDS) {
finalReply = '抱歉,暂时无法处理您的请求,请稍后重试';
}
continue;
}
}
// 无回复的兜底
if (!finalReply && lastFunctionResult) {
finalReply = lastFunctionResult?.data?.message
|| lastFunctionResult?.data?.greeting
|| (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成');
}
if (!finalReply) {
finalReply = '抱歉,暂时无法处理您的请求';
}
ctx.logger.info(`[inbox ai] 最终回复: ${finalReply}`);
return {
reply: finalReply,
functionName: lastFunctionName,
functionResult: lastFunctionResult,
thoughts,
};
}
}
module.exports = InboxAIService;

File diff suppressed because it is too large Load Diff

224
app/service/inbox/groups.js Normal file
View File

@ -0,0 +1,224 @@
'use strict';
const Service = require('egg').Service;
/**
* ## 群类型统一定义(唯一数据源)
*
* 所有 AI 函数分组常量(GROUP)、合法子类型映射(VALID_SUB_TYPES)、
* 通配展开(WILDCARD_EXPAND)均由此结构自动派生,修改群类型只需维护此处。
*
* @constant {Array<{type: string, label: string, mainGroup: string, wildcardGroup: string|null, subTypes: Array<{key: string, label: string}>}>}
*/
const GROUP_TYPES = [
{
type: 'store',
label: '货主群',
mainGroup: 'bound:store',
wildcardGroup: 'bound:store:*',
subTypes: [
{ key: 'after_sales', label: '售后' },
{ key: 'finance', label: '财务' },
{ key: 'receiving', label: '收货' },
],
},
{
type: 'warehouse',
label: '仓库群',
mainGroup: 'bound:warehouse',
wildcardGroup: null,
subTypes: [
{ key: 'receiving', label: '收货' },
{ key: 'production', label: '生产' },
{ key: 'stockout', label: '出库' },
{ key: 'finance', label: '财务' },
{ key: 'all', label: '全体' },
{ key: 'customer_service', label: '客服' },
{ key: 'exception', label: '异常' },
],
},
{
type: 'express',
label: '快递群',
mainGroup: 'bound:express',
wildcardGroup: null,
subTypes: [
{ key: 'pickup', label: '揽收' },
{ key: 'after_sales', label: '售后' },
],
},
];
// ========== 以下均为 GROUP_TYPES 的派生值,禁止手动修改 ==========
/**
* AI 函数分组常量,由 {@link GROUP_TYPES} 自动生成。
* @constant {Record<string, string>}
*/
const GROUP = (() => {
const map = { COMMON: 'common' };
for (const gt of GROUP_TYPES) {
const prefix = gt.mainGroup.split(':').pop();
const upper = prefix.toUpperCase();
map[`BOUND_${upper}`] = gt.mainGroup;
if (gt.wildcardGroup) {
map[`BOUND_${upper}_WILDCARD`] = gt.wildcardGroup;
}
for (const st of gt.subTypes) {
map[`BOUND_${upper}_${st.key.toUpperCase()}`] = `${gt.mainGroup}:${st.key}`;
}
}
return Object.freeze(map);
})();
/**
* 各群类型下合法的子类型 key → GROUP 常量映射,由 {@link GROUP_TYPES} 自动生成。
* @constant {Record<string, Record<string, string>>}
*/
const VALID_SUB_TYPES = (() => {
const map = {};
for (const gt of GROUP_TYPES) {
if (gt.subTypes.length === 0) continue;
const sub = {};
for (const st of gt.subTypes) {
const prefix = gt.mainGroup.split(':').pop().toUpperCase();
sub[st.key] = GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`];
}
map[gt.type] = sub;
}
return Object.freeze(map);
})();
/**
* 通配展开映射,由 {@link GROUP_TYPES} 自动生成。
* @constant {Record<string, string[]>}
*/
const WILDCARD_EXPAND = (() => {
const map = {};
for (const gt of GROUP_TYPES) {
if (!gt.wildcardGroup) continue;
const prefix = gt.mainGroup.split(':').pop().toUpperCase();
const list = [ GROUP[`BOUND_${prefix}`] ];
for (const st of gt.subTypes) {
list.push(GROUP[`BOUND_${prefix}_${st.key.toUpperCase()}`]);
}
map[gt.wildcardGroup] = list;
}
return Object.freeze(map);
})();
/**
* 群分组匹配服务。
* 负责根据当前上下文解析可用分组、判断函数可见性、构建函数列表。
* 纯策略/匹配逻辑,不涉及函数注册与执行。
*/
class InboxGroupsService extends Service {
/**
* 根据当前上下文解析可用分组集合。
*
* - 始终包含 `common`(通用分组)。
* - 根据 `groupType` + `subType` 查询 VALID_SUB_TYPES 激活对应的子分组。
* - 只有 VALID_SUB_TYPES 中声明的 subType 才会生效,防止越界激活。
*
* @param {Object} [opts] 可选覆盖参数。
* @param {string} [opts.groupType] 群类型(store / warehouse / express)。
* @param {string} [opts.subType] 子类型。
* @return {string[]} 当前上下文中可用的分组列表。
*/
resolveActiveGroups(opts = {}) {
const { ctx } = this;
const groups = [ GROUP.COMMON ];
const groupType = String(
opts.groupType || ctx.inboxContext?.group_type || ''
).trim();
const subType = String(
opts.subType || ctx.inboxContext?.sub_type || ''
).trim();
const storeId = Number(ctx.inboxContext?.store_id || 0);
const gtDef = GROUP_TYPES.find(gt => gt.type === groupType);
if (gtDef && (groupType === 'express' || storeId > 0)) {
groups.push(gtDef.mainGroup);
const subMap = VALID_SUB_TYPES[groupType];
if (subMap && subMap[subType]) {
groups.push(subMap[subType]);
}
}
return groups;
}
/**
* 判断某个函数在当前活跃分组集合中是否可用。
*
* @param {Object} def 函数定义对象(含 `groups` 字段)。
* @param {string[]} activeGroups 当前上下文的活跃分组列表。
* @return {boolean} 该函数在当前分组中是否可用。
*/
isFunctionAvailable(def, activeGroups) {
if (!Array.isArray(def.groups) || def.groups.length === 0) return true;
const expanded = [];
for (const g of def.groups) {
if (WILDCARD_EXPAND[g]) {
expanded.push(...WILDCARD_EXPAND[g]);
} else {
expanded.push(g);
}
}
return expanded.some(g => g === GROUP.COMMON || activeGroups.includes(g));
}
/**
* 获取指定分组下的函数列表。
*
* @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部已注册函数。
* @return {Array<{name: string, description: string, params: Object}>} 函数列表。
*/
getFunctionList(activeGroups) {
const { ctx } = this;
const funcSvc = ctx.service.inbox.functions;
const list = [];
for (const [ name, def ] of funcSvc.registry) {
if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue;
list.push({
name,
description: def.description,
params: def.params,
});
}
return list;
}
/**
* 构建函数列表的文本描述,供 AI prompt 使用。
*
* @param {string[]} [activeGroups] 活跃分组列表,不传则返回全部。
* @return {string} 函数列表文本。
*/
buildFunctionListText(activeGroups) {
const { ctx } = this;
const funcSvc = ctx.service.inbox.functions;
const lines = [];
for (const [ name, def ] of funcSvc.registry) {
if (activeGroups && !this.isFunctionAvailable(def, activeGroups)) continue;
const paramEntries = Object.entries(def.params);
const paramStr = paramEntries.length > 0
? paramEntries.map(([ k, v ]) => `${k}(${v.type || 'string'}, ${v.required ? '必填' : '可选'}): ${v.description}`).join(', ')
: '无参数';
const weightStr = def.weight ? ` [权重:${def.weight}]` : '';
const keywordStr = def.keywords && def.keywords.length > 0
? ` [触发词:${def.keywords.join(',')}]`
: '';
lines.push(`- ${name}${weightStr}${keywordStr}: ${def.description}。参数: ${paramStr}`);
}
return lines.join('\n');
}
}
module.exports = InboxGroupsService;
module.exports.GROUP_TYPES = GROUP_TYPES;
module.exports.GROUP = GROUP;

View File

@ -3,7 +3,6 @@
const Service = require('egg').Service;
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s
/**
* 站内信内容处理器。
@ -11,6 +10,69 @@ const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s
* 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。
*/
class InboxProcessorService extends Service {
constructor(ctx) {
super(ctx);
/**
* 群信息缓存(groupId:warehouseId → { group_type, sub_type, ai_enabled, ext_data })。
* 生命周期跟随进程,写回 ext_data 时清除对应条目。
*/
this._groupCache = new Map();
}
/**
* 从缓存或 DB 拉取群信息。若群 ext_data 为空且消息携带 ext_data,自动写回并清缓存。
* @param {string} groupId 外部群ID
* @param {number} warehouseId 仓库ID
* @param {Object|null} msgExtData 入站消息的 ext_data
* @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>}
*/
async _loadGroupInfo(groupId, warehouseId, msgExtData) {
const { ctx } = this;
const cacheKey = `${groupId}:${warehouseId}`;
// 命中缓存直接返回
const cached = this._groupCache.get(cacheKey);
if (cached) return cached;
let group = null;
try {
group = await ctx.model.InboxGroup.findOne({
attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'ext_data' ],
where: { group_id: groupId, warehouse_id: warehouseId },
raw: true,
});
} catch (e) {
ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`);
}
const info = {
group_type: (group && group.group_type) || '',
sub_type: (group && group.sub_type) || '',
ai_enabled: group ? group.ai_enabled : 0,
ext_data: (group && group.ext_data) || null,
};
// 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置
if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) {
try {
await ctx.model.InboxGroup.update(
{ ext_data: msgExtData },
{ where: { group_id: groupId, warehouse_id: warehouseId } }
);
info.ext_data = msgExtData;
ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`);
} catch (e) {
ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`);
// 写回失败不阻塞,直接返回 info(ext_data 仍为空)
return info;
}
}
// 写入缓存
this._groupCache.set(cacheKey, info);
return info;
}
/**
* 处理入站消息内容。
* 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。
@ -88,8 +150,6 @@ class InboxProcessorService extends Service {
const warehouseId = Number(data.warehouse_id) || 0;
const extId = String(data.ext_id || '');
const parentId = Number(data.parent_id) || null;
let ackExtId = '';
let callbackConfig = { url: null, appKey: null, appSecret: null };
try {
// 1. 处理消息正文,挂载上下文
@ -106,24 +166,16 @@ class InboxProcessorService extends Service {
const bindHandled = await this.tryBindGroup(data);
if (bindHandled) return;
// 4. 加载群的 group_type / sub_type / ai_enabled
// 4. 加载群的 group_type / sub_type / ai_enabled / ext_data(带缓存 + 自动写回)
if (ctx.inboxContext.ai_enabled === undefined) {
try {
const groupId = String(ctx.inboxContext.group_id || '').trim();
if (groupId) {
const group = await ctx.model.InboxGroup.findOne({
attributes: [ 'group_type', 'sub_type', 'ai_enabled' ],
where: { group_id: groupId, warehouse_id: warehouseId },
raw: true,
});
ctx.inboxContext.group_type = (group && group.group_type) || '';
ctx.inboxContext.sub_type = (group && group.sub_type) || '';
ctx.inboxContext.ai_enabled = group ? group.ai_enabled : 0;
} else {
ctx.inboxContext.ai_enabled = 0;
}
} catch (e) {
ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`);
const groupId = String(ctx.inboxContext.group_id || '').trim();
if (groupId) {
const info = await this._loadGroupInfo(groupId, warehouseId, data.ext_data || null);
ctx.inboxContext.group_type = info.group_type;
ctx.inboxContext.sub_type = info.sub_type;
ctx.inboxContext.ai_enabled = info.ai_enabled;
ctx.inboxContext.group_ext_data = info.ext_data;
} else {
ctx.inboxContext.ai_enabled = 0;
}
}
@ -136,6 +188,7 @@ class InboxProcessorService extends Service {
}
// 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认)
// 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理
if (ctx.inboxContext.ai_enabled !== 1) {
ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`);
return;
@ -158,8 +211,11 @@ class InboxProcessorService extends Service {
}
}
// 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单
ctx.inboxContext.inbound_message_id = parentId || null;
// 6. DeepSeek 两步交互(AI 内部自行判断真人接管)
const aiResult = await ctx.service.inbox.functions.processWithAI({
const aiResult = await ctx.service.inbox.ai.processWithAI({
content: data.content || '',
ext_data: data.ext_data || null,
parentId: data.parent_id || null,
@ -189,182 +245,37 @@ class InboxProcessorService extends Service {
`function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}`
);
// 7. 写入 outbound 回执记录
ackExtId = `sys:ack:${extId}`;
let outboundId = null;
try {
const existAck = await InboxMessage.findOne({
where: { ext_id: ackExtId },
attributes: [ 'id' ],
paranoid: false,
});
if (existAck) {
outboundId = existAck.id;
} else {
const created = await InboxMessage.create({
ext_id: ackExtId,
warehouse_id: warehouseId,
store_id: data.store_id || null,
direction: 'outbound',
parent_id: parentId,
source_type: 'system',
source_extra: null,
target_type: 'api',
group_id: ctx.inboxContext?.group_id || data.group_id || null,
user_id: ctx.inboxContext?.user_id || data.user_id || null,
group_name: ctx.inboxContext?.group_name || data.group_name || null,
user_name: ctx.inboxContext?.user_name || data.user_name || null,
content: replyContent,
ext_data: data.ext_data || null,
ai_thoughts: aiResult.thoughts || null,
flags: {},
});
outboundId = created.id;
ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`);
// 7. AI 推理写入入站消息(便于排查)
if (aiResult.thoughts && aiResult.thoughts.length > 0) {
try {
await InboxMessage.update(
{ ai_thoughts: aiResult.thoughts },
{ where: { ext_id: extId } }
);
} catch (e) {
ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`);
}
} catch (writeError) {
ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`);
}
// 8. 查回调地址并发送(带 MD5 签名)
callbackConfig = await this.getApiAppCallbackConfig(warehouseId);
const callbackUrl = callbackConfig.url;
if (!callbackUrl) {
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`);
// 8. 快递群:仅执行函数,不回信
if (groupType === 'express') {
ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`);
return;
}
const crypto = require('crypto');
const method = 'notify.reply';
const notifyBody = {
code: 200,
data: {
type: 'ai',
content: replyContent,
ext_data: data.ext_data || null,
ext_id: String(outboundId || ''),
group_id: ctx.inboxContext?.group_id || data.group_id || '',
user_id: ctx.inboxContext?.user_id || data.user_id || '',
group_name: ctx.inboxContext?.group_name || data.group_name || '',
user_name: ctx.inboxContext?.user_name || data.user_name || '',
timestamp: Math.floor(Date.now() / 1000),
},
};
const bodyJson = JSON.stringify(notifyBody);
const timestamp = Math.floor(Date.now() / 1000);
const appKey = callbackConfig.appKey || '';
const appSecret = callbackConfig.appSecret || '';
const sign = appSecret
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
: '';
const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`);
const response = await ctx.curl(urlWithSign, {
method: 'POST',
dataType: 'json',
contentType: 'json',
data: notifyBody,
headers: { 'Content-Type': 'application/json' },
timeout: CALLBACK_TIMEOUT_MS,
});
// 记录出站通知日志到 wms_warehouse_log
try {
const { WarehouseLog } = ctx.model;
await WarehouseLog.create({
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
app_key: appKey || null,
method,
warehouse_id: warehouseId || null,
url: urlWithSign || null,
http_status: response ? response.status : null,
body: JSON.stringify(notifyBody).substring(0, 65535),
result: response ? JSON.stringify(response.data || {}).substring(0, 65535) : '',
use_time: null,
created_at: new Date(),
});
} catch (logErr) {
ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message);
}
ctx.logger.info(
`[inbox processor] API 回执完成 ext_id=${extId} ` +
`http_status=${response.status}`
);
// 更新出站+入站推送状态
if (response && response.status === 200
&& (!response.data || response.data.code === undefined || response.data.code === 200)) {
await InboxMessage.update(
{
push_status: 2,
push_response: { http_status: response.status, body: response.data || null },
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { ext_id: ackExtId } }
);
if (parentId) {
await InboxMessage.update(
{
push_status: 2,
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { id: parentId } }
);
}
} else {
await InboxMessage.update(
{
push_status: 3,
push_response: { http_status: response ? response.status : null, body: response ? response.data : null },
},
{ where: { ext_id: ackExtId } }
);
}
// 9. 统一回信
await this.writeOutboundReply({
warehouse_id: warehouseId,
ext_id: extId,
parent_id: parentId,
ext_data: data.ext_data || null,
group_id: ctx.inboxContext?.group_id || data.group_id || null,
user_id: ctx.inboxContext?.user_id || data.user_id || null,
group_name: ctx.inboxContext?.group_name || data.group_name || null,
user_name: ctx.inboxContext?.user_name || data.user_name || null,
}, replyContent);
} catch (error) {
ctx.logger.error(
`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`
);
// 更新推送状态为失败
try {
await InboxMessage.update(
{
push_status: 3,
push_response: { error: error.message },
},
{ where: { ext_id: ackExtId } }
);
} catch (updateErr) {
ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message);
}
// 记录失败日志到 warehouse_log
try {
const { WarehouseLog } = ctx.model;
const crypto = require('crypto');
await WarehouseLog.create({
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
app_key: callbackConfig.appKey || null,
method: 'notify.reply',
warehouse_id: warehouseId || null,
url: callbackConfig.url || null,
http_status: null,
body: '', result: 'Error: ' + error.message,
use_time: null,
created_at: new Date(),
});
} catch (logErr) {
ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message);
}
ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`);
}
}
@ -470,7 +381,8 @@ class InboxProcessorService extends Service {
* @param {string} data.group_name 群名称(必填)。
* @param {string} data.user_name 用户名称(必填)。
* @param {string} replyContent 回复内容。
* @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error。
* @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。
* system 类型不要求 user_id/user_name。
* @return {Promise<void>}
*/
async writeOutboundReply(data, replyContent, source = 'ai_reply') {
@ -480,18 +392,19 @@ class InboxProcessorService extends Service {
const warehouseId = Number(data.warehouse_id || 0);
const extId = String(data.ext_id || '');
const parentId = Number(data.parent_id || 0);
const isSystem = source === 'system';
// 强制入参校验
// 强制入参校验(system 类型不要求 user_id/user_name)
const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim();
const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim();
const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim();
const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim();
if (!groupId || !userId || !groupName || !userName) {
throw new Error(
`回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` +
`group_name=${groupName || '?'}, user_name=${userName || '?'}`
);
if (!groupId || !groupName) {
throw new Error(`回执缺少必填字段: group_id=${groupId || '?'}, group_name=${groupName || '?'}`);
}
if (!isSystem && (!userId || !userName)) {
throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`);
}
const ackExtId = `sys:ack:${extId}`;
@ -511,9 +424,9 @@ class InboxProcessorService extends Service {
source_type: 'system', source_extra: null,
target_type: 'api',
group_id: groupId,
user_id: userId,
user_id: isSystem ? null : userId,
group_name: groupName,
user_name: userName,
user_name: isSystem ? null : userName,
content: replyContent,
ext_data: data.ext_data || null, flags: {},
});
@ -527,14 +440,13 @@ class InboxProcessorService extends Service {
const notifyBody = {
code: 200,
data: {
type: source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error',
type: isSystem ? 'system' : source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error',
content: replyContent,
ext_data: data.ext_data || null,
ext_id: String(outboundId),
group_id: groupId,
user_id: userId,
...(isSystem ? {} : { user_id: userId, user_name: userName }),
group_name: groupName,
user_name: userName,
timestamp: Math.floor(Date.now() / 1000),
},
};
@ -767,6 +679,45 @@ class InboxProcessorService extends Service {
return config.url;
}
/**
* 系统通知异步推送:仅 POST 回调,不写 inbox_message。
* @param {Object} data 通知数据。
* @param {number} data.warehouse_id 仓库ID。
* @param {string} data.group_id 目标群ID。
* @param {string} data.group_name 目标群名称。
* @param {string} data.content 通知内容。
* @param {Object} [data.ext_data] 群扩展数据(渠道信息)。
*/
pushSystemNotification(data = {}) {
const { ctx } = this;
const warehouseId = Number(data.warehouse_id);
const groupId = String(data.group_id || '').trim();
const groupName = String(data.group_name || '').trim();
const content = String(data.content || '').trim();
const extData = data.ext_data || null;
if (!warehouseId || !groupId || !content) return;
// 构造 data 对象,复用 writeOutboundReply
const replyData = {
warehouse_id: warehouseId,
ext_id: `sys:notify:${warehouseId}:${groupId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,
parent_id: null,
ext_data: extData,
group_id: groupId,
user_id: '',
group_name: groupName,
user_name: '',
};
// 写库 + POST,异步不阻塞
setImmediate(() => {
this.writeOutboundReply(replyData, content, 'system').catch(err => {
ctx.logger.warn(`[pushNotify] 推送异常 group=${groupName}: ${err.message}`);
});
});
}
/**
* 尝试从消息正文中提取仓库ID。
* 子类或业务方可覆盖此方法以实现自定义解析逻辑。

View File

@ -61,7 +61,41 @@ class OpenapiOrderService extends MainService {
transaction,
});
// 同步更新运单表拦截标记
try {
const { ctx } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (warehouseId > 0) {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: warehouseId }, transaction }
);
}
} catch (expressErr) {
this.ctx.logger.warn(
`[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
await transaction.commit();
// 创建售后工单 + 通知快递群(失败不影响主流程)
try {
const { ctx } = this;
const whId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (whId > 0) {
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ existingOrder.id ],
warehouseId: whId,
creatorLabel: ctx.user?.employees_name || 'OpenAPI系统',
});
}
} catch (workOrderErr) {
this.ctx.logger.warn(
`[openapi order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}`
);
}
return this.fail('取消失败,已通知拦截执行');
}

View File

@ -194,7 +194,33 @@ class orderServer extends MainService {
transaction,
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
await transaction.commit();
// 创建售后工单 + 通知快递群(失败不影响主流程)
try {
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ existingOrder.id ],
warehouseId: info.warehouseId,
creatorLabel: ctx.user?.employees_name || '奇门系统',
});
} catch (workOrderErr) {
ctx.logger.warn(
`[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}`
);
}
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,

View File

@ -16,9 +16,10 @@ const BLOCK_PERMISSION_ROLE_GROUP_MAP = Object.freeze({
});
/**
* 售后模块工作列表排除的状态(已完成/已取消)。
* 售后模块工作列表排除的终态(已完成/已关闭/已取消)。
* pending_feedback 不在静态排除列表中,由 workList 根据 followup_at 动态判断。
*/
const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'cancelled' ]);
const WORK_LIST_EXCLUDED_STATUSES = Object.freeze([ 'completed', 'closed', 'cancelled' ]);
/**
* 系统方法层:afterSale(售后模块接口包装层)。
@ -29,9 +30,9 @@ class AfterSaleMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress';
const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress';
const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,registerClaim,export,exportTaskProgress';
const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount';
const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount';
const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -62,7 +63,7 @@ class AfterSaleMethodService extends MainService {
});
// 提取当前用户的售后 block 权限 → role_group 列表
const allowedRoleGroups = this._resolveAfterSaleBlockRoleGroups();
const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups();
// 强制过滤:仅展示当前用户可处理的 role_group,且排除已完成/已取消
const enforcedWhere = {
@ -77,37 +78,112 @@ class AfterSaleMethodService extends MainService {
},
};
const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort);
const result = await service.systems.afterSale.list(enforcedWhere, pagination, sort, {
order: [[ 'priority', 'DESC' ], [ 'updated_at', 'DESC' ]],
excludeFutureFollowup: true,
});
return this.success('ok', result);
}
/**
* 解析当前用户所拥有的售后 block 权限对应的 role_group 列表。
* 从 ctx.user.role.permissions 中筛选 type=block 且 ID 为 516/517/518 的权限项。
* 从 wms_role.permissions 中查询当前激活角色的原始权限 ID,
* 若 permissions='*' 则返回全部 role_group,否则筛选 516/517/518。
*
* @return {string[]} 当前用户可处理的 role_group 列表
* @return {Promise<string[]>} 当前用户可处理的 role_group 列表
*/
_resolveAfterSaleBlockRoleGroups() {
async _resolveAfterSaleBlockRoleGroups() {
const { ctx } = this;
const rolePermissions = ctx.user && ctx.user.role && Array.isArray(ctx.user.role.permissions)
? ctx.user.role.permissions
: [];
const allowedRoleGroups = [];
for (const perm of rolePermissions) {
const permId = Number(perm && (perm.id || perm.permission_id || 0));
const permType = String(perm && (perm.type || '')).trim();
if (permType === 'block' && BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) {
allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]);
}
}
// 如果未匹配到任何售后 block 权限,默认不给任何 role_group 可见范围
if (allowedRoleGroups.length === 0) {
const employeeId = ctx.user && ctx.user.employees_id;
if (!employeeId) {
return [ '__none__' ];
}
return allowedRoleGroups;
try {
// 1. 通过 EmployeeRole 找到 role_id
const employeeRole = await ctx.model.EmployeeRole.findOne({
where: { employee_id: employeeId },
attributes: [ 'role_id' ],
raw: true,
});
if (!employeeRole || !employeeRole.role_id) {
return [ '__none__' ];
}
// 2. 读取 wms_role.permissions
const role = await ctx.model.Role.findOne({
where: { id: employeeRole.role_id, status: 1 },
attributes: [ 'permissions' ],
raw: true,
});
if (!role) {
return [ '__none__' ];
}
// 3. 标准化解析
const state = ctx.service.systems.auth.rolePermission.normalizePermissionSet(role.permissions);
// 超级管理员 → 全部 role_group
if (state.allAccess) {
return [ 'customer_service', 'warehouse', 'finance' ];
}
// 匹配 block 权限 516/517/518
const allowedRoleGroups = [];
for (const permId of state.permissionIds) {
if (BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]) {
allowedRoleGroups.push(BLOCK_PERMISSION_ROLE_GROUP_MAP[permId]);
}
}
if (allowedRoleGroups.length === 0) {
return [ '__none__' ];
}
return allowedRoleGroups;
} catch (err) {
ctx.logger.warn(`[_resolveAfterSaleBlockRoleGroups] 权限查询失败: ${err.message}`);
return [ '__none__' ];
}
}
// ===========================
// 待处理工单计数(角标用)
// ===========================
/**
* 快速查询当前用户待处理售后工单数量(用于角标显示)。
* 过滤逻辑与 workList 一致:role_group 按 block 权限,排除已完成/已取消。
* 返回 { count: number },前端自行判断 >99 显示 99+。
*
* @param {Object} data 请求体(可选 where 条件)
* @return {Promise<Object>} { count: number }
*/
async workCount(data = {}) {
const { service } = this;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
// 与 workList 一致的角色组 + 状态过滤
const allowedRoleGroups = await this._resolveAfterSaleBlockRoleGroups();
const enforcedWhere = {
...where,
role_group: {
operator: 'in',
value: allowedRoleGroups,
},
status: {
operator: 'notin',
value: WORK_LIST_EXCLUDED_STATUSES,
},
};
const result = await service.systems.afterSale.countPending(enforcedWhere, { excludeFutureFollowup: true });
return this.success('ok', { count: result.count });
}
// ===========================
@ -177,7 +253,7 @@ class AfterSaleMethodService extends MainService {
* @param {string} [data.description] 售后详细描述
* @param {number} [data.priority=0] 优先级
* @param {number} [data.waybill_id] 关联运单ID
* @param {number} [data.order_delivery_id] 关联发货订单ID
* @param {number} [data.order_delivery_id] 关联发货订单ID(兼容别名 order_id)
* @param {number} [data.entry_order_id] 关联入库单ID
* @param {number} [data.order_stockout_id] 关联出库单ID
* @param {number} [data.receiving_id] 关联收货单ID
@ -201,7 +277,8 @@ class AfterSaleMethodService extends MainService {
description,
priority,
waybill_id: waybillId,
order_delivery_id: orderDeliveryId,
order_delivery_id: orderDeliveryIdRaw,
order_id: orderIdRaw,
entry_order_id: entryOrderId,
order_stockout_id: orderStockoutId,
receiving_id: receivingId,
@ -209,6 +286,9 @@ class AfterSaleMethodService extends MainService {
inbox_message_id: inboxMessageId,
} = data || {};
// 兼容 order_id 别名(优先 order_delivery_id,为空时取 order_id)
const orderDeliveryId = orderDeliveryIdRaw || orderIdRaw || null;
// 生成售后单号
const afterSaleNo = await this.generateAfterSaleNo(warehouseId);
@ -397,7 +477,6 @@ class AfterSaleMethodService extends MainService {
*
* @param {Object} data 请求体
* @param {number} data.id 售后单主键ID
* @param {string} data.action 操作动作描述
* @param {string} [data.remark] 处理备注
* @param {string} [data.status] 目标售后状态
* @param {string} [data.resolution] 完结处理结果(status=completed 时写入)
@ -408,7 +487,6 @@ class AfterSaleMethodService extends MainService {
const { ctx, service } = this;
const {
id,
action,
remark,
status: targetStatus,
resolution,
@ -418,9 +496,10 @@ class AfterSaleMethodService extends MainService {
if (!id) {
return this.fail('缺少售后单ID');
}
if (!action) {
return this.fail('缺少操作动作');
}
// status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作
const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending');
const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing';
const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const operatorSnapshot = this._buildOperatorSnapshot();
@ -428,9 +507,8 @@ class AfterSaleMethodService extends MainService {
const result = await service.systems.afterSale.handleWorkOrder({
id: Number(id),
action,
remark: remark || null,
targetStatus: targetStatus || null,
targetStatus: safeStatus,
resolution: resolution || null,
attachmentIds: Array.isArray(attachmentIds) ? attachmentIds : [],
operatorId,
@ -441,6 +519,96 @@ class AfterSaleMethodService extends MainService {
return this.success('处理成功', result);
}
// ===========================
// 批量设为待反馈
// ===========================
/**
* 批量将售后工单设为"待反馈"状态,按仓库配置自动计算下次跟进时间。
* 所有工单在同一事务中处理,任一失败则全部回滚。
*
* @param {Object} data 请求体
* @param {number[]} data.ids 售后单主键ID列表
* @param {string} [data.remark] 统一处理备注(所有工单共用)
* @return {Promise<Object>} 统一 success 包装,包含 total/success/failed
*/
async batchSetPendingFeedback(data = {}) {
const { ctx, service } = this;
const { ids, remark } = data || {};
if (!Array.isArray(ids) || ids.length === 0) {
return this.fail('ids 不能为空且必须为数组');
}
const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const operatorSnapshot = this._buildOperatorSnapshot();
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (!warehouseId) {
return this.fail('无法获取当前仓库上下文');
}
const result = await service.systems.afterSale.batchSetPendingFeedback({
ids,
remark: remark || null,
operatorId,
operatorSnapshot,
warehouseId,
});
return this.success('批量设为待反馈完成', result);
}
// ===========================
// 批量完结/关闭
// ===========================
/**
* 批量将售后工单设为完结或关闭状态。
* completed 时自动写入 resolved_at 并清除 followup_at。
* 所有工单在同一事务中处理,任一失败则全部回滚。
*
* @param {Object} data 请求体
* @param {number[]} data.ids 售后单主键ID列表
* @param {string} data.status 目标状态:completed | closed
* @param {string} [data.resolution] 完结处理结果(仅 status=completed 时写入)
* @param {string} [data.remark] 统一处理备注(所有工单共用)
* @return {Promise<Object>} 统一 success 包装,包含 total/success/failed
*/
async batchClose(data = {}) {
const { ctx, service } = this;
const { ids, status: targetStatus, resolution, remark } = data || {};
if (!Array.isArray(ids) || ids.length === 0) {
return this.fail('ids 不能为空且必须为数组');
}
const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]);
if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) {
return this.fail('status 必须为 completed 或 closed');
}
const operatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0;
const operatorSnapshot = this._buildOperatorSnapshot();
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
if (!warehouseId) {
return this.fail('无法获取当前仓库上下文');
}
const result = await service.systems.afterSale.batchClose({
ids,
status: targetStatus,
resolution: resolution || null,
remark: remark || null,
operatorId,
operatorSnapshot,
warehouseId,
});
return this.success('批量操作完成', result);
}
// ===========================
// 登记理赔
// ===========================
@ -838,6 +1006,7 @@ class AfterSaleMethodService extends MainService {
return null;
}
}
}
module.exports = AfterSaleMethodService;

View File

@ -1287,8 +1287,13 @@ class indexService extends MainService {
// 构建嵌套路径
for (let i = 0; i < keys.length - 1; i++) {
const key = keys[i];
if (!current[key]) {
// 如果路径节点已存在但非对象(被其他叶子键占用),先保存旧值再转为对象
if (!current[key] || typeof current[key] !== 'object') {
const oldValue = current[key];
current[key] = {};
if (oldValue !== undefined) {
current[key]._self = oldValue;
}
}
current = current[key];
}

View File

@ -1,14 +1,24 @@
'use strict';
const OrderBaseService = require('./base');
const fs = require('fs');
const path = require('path');
const DEBUG_LOG = path.join(__dirname, '..', '..', '..', '..', 'temp', 'quickSearch_debug.log');
function dbg(msg) {
const ts = new Date().toISOString();
const line = `[${ts}] ${msg}\n`;
try { fs.appendFileSync(DEBUG_LOG, line, 'utf8'); } catch (_) { /* ignore */ }
}
class DeliveryOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,deliveryOrder';
const _noNeedLog = 'list';
const _noNeedAuth = 'list,deliveryOrder';
const _noNeedRight = 'list,deliveryOrder,quickSearch';
const _noNeedLog = 'list,quickSearch';
const _noNeedAuth = 'list,deliveryOrder,quickSearch';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -50,6 +60,321 @@ class DeliveryOrderService extends OrderBaseService {
return await super.detail(detailParams);
}
/**
* 订单快速搜索。
* 跨表联合搜索:运单号(wms_order_express,精确)、发货单号/外部订单号/平台交易单号(dispatch 表,模糊)。
* 返回匹配的订单列表(最多 20 条),包含订单关键信息及关联运单号。
*
* @param {Object} data 请求体。
* @param {string} data.keyword 搜索关键词(必填)。
* @return {Promise<Object>} { list, keyword }
*/
async quickSearch(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const requestData = this.isPlainObject(data) ? data : {};
const keyword = String(requestData.keyword || '').trim();
const warehouseId = this.getWarehouseId();
dbg('========== quickSearch START ==========');
dbg(`keyword="${keyword}" warehouseId=${warehouseId}`);
if (!keyword) {
dbg('keyword empty → return []');
return { list: [], keyword: '' };
}
if (!warehouseId) {
dbg('warehouseId empty → throw');
throw new Error('缺少仓库上下文');
}
const MAX_RESULTS = 20;
// 收集匹配的订单 ID(去重)
const matchedOrderIds = new Set();
// ====== 第一步:express 表 OR 搜索 ======
dbg('--- Step1: express OR query ---');
const expressWhere = {
warehouse_id: warehouseId,
[Op.or]: [
{ waybill_code: keyword },
{ delivery_order_code: { [Op.like]: `%${keyword}%` } },
{ source_order_codes: { [Op.like]: `%${keyword}%` } },
],
};
dbg(`expressWhere: ${JSON.stringify(expressWhere)}`);
let expressRecords;
try {
expressRecords = await ctx.model.OrderExpress.findAll({
attributes: [
'id', 'order_id', 'waybill_code', 'delivery_order_code', 'source_order_codes', 'store_id',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code', 'status', 'is_back', 'is_intercept', 'is_galaxy_receive',
'weighing_weight',
],
where: expressWhere,
raw: true,
limit: MAX_RESULTS,
});
dbg(`expressRecords count: ${expressRecords.length}`);
} catch (e) {
dbg(`expressRecords ERROR: ${e.message}`);
expressRecords = [];
}
const waybillMap = new Map();
for (const er of expressRecords) {
dbg(` er: id=${er.id} order_id=${er.order_id} waybill_code=${er.waybill_code} delivery_order_code=${er.delivery_order_code}`);
if (er.order_id) {
matchedOrderIds.add(er.order_id);
if (!waybillMap.has(er.order_id)) {
waybillMap.set(er.order_id, []);
}
waybillMap.get(er.order_id).push(this.buildWaybillItem(er));
}
}
dbg(`matchedOrderIds: [${[ ...matchedOrderIds ].join(',')}]`);
dbg(`waybillMap keys: [${[ ...waybillMap.keys() ].join(',')}]`);
if (matchedOrderIds.size === 0) {
dbg('matchedOrderIds empty → return []');
return { list: [], keyword };
}
// ====== 第二步:订单表 IN 查详情 ======
const orderIds = [ ...matchedOrderIds ].slice(0, MAX_RESULTS);
const orderMap = new Map();
dbg(`--- Step2: order detail IN query, orderIds=[${orderIds.join(',')}] ---`);
if (orderIds.length > 0) {
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
dbg(`factory exists: ${!!factory}`);
dbg(`factory keys: ${factory ? Object.keys(factory).join(',') : 'N/A'}`);
dbg(`factory.getDispatchModel type: ${factory && typeof factory.getDispatchModel}`);
// 直接尝试调用,不判断 typeof,看具体报什么错
if (factory) {
const tableDefs = [
{ label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) },
{ label: 'current', getModel: () => factory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => factory.getHistoryModel(warehouseId) },
];
const remainingIds = new Set(orderIds.map(String));
for (const entry of tableDefs) {
if (remainingIds.size === 0) break;
dbg(` trying table: ${entry.label}, remainingIds=[${[ ...remainingIds ].join(',')}]`);
try {
const model = await entry.getModel();
dbg(` ${entry.label} model: ${!!model}, typeof findAll=${model && typeof model.findAll}`);
if (!model || typeof model.findAll !== 'function') {
dbg(` ${entry.label} model invalid, skip`);
continue;
}
const whereClause = { id: [ ...remainingIds ].map(Number) };
dbg(` ${entry.label} where: ${JSON.stringify(whereClause)}`);
const rows = await model.findAll({
attributes: [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
],
where: whereClause,
raw: true,
});
dbg(` ${entry.label} rows count: ${rows.length}`);
for (const r of (rows || [])) {
dbg(` row: id=${r.id} delivery_order_code=${r.delivery_order_code} status=${r.status}`);
const rid = String(r.id);
if (!orderMap.has(rid)) { orderMap.set(rid, r); remainingIds.delete(rid); }
}
} catch (e) {
dbg(` ${entry.label} ERROR: ${e.message} | stack: ${(e.stack || '').split('\n').slice(0, 3).join(' | ')}`);
continue;
}
}
}
}
dbg(`orderMap.size: ${orderMap.size}, keys: [${[ ...orderMap.keys() ].join(',')}]`);
// ====== 第三步:货主备注 ======
dbg('--- Step3: store remark ---');
const storeRemarkMap = new Map();
const allStoreIds = new Set();
for (const oid of orderIds) {
const wb = (waybillMap.get(oid) || [])[0];
const sid = (wb && wb.store_id) || (orderMap.get(String(oid)) || {}).store_id || 0;
if (sid) allStoreIds.add(sid);
}
dbg(`allStoreIds: [${[ ...allStoreIds ].join(',')}]`);
if (allStoreIds.size > 0 && ctx.model.StoreWarehouse) {
try {
const swRows = await ctx.model.StoreWarehouse.findAll({
where: { store_id: { [Op.in]: [ ...allStoreIds ] }, warehouse_id: warehouseId },
attributes: [ 'store_id', 'store_remask' ], raw: true,
});
dbg(`store_warehouse rows: ${swRows.length}`);
for (const sw of swRows) {
dbg(` sw: store_id=${sw.store_id} store_remask="${sw.store_remask}"`);
storeRemarkMap.set(sw.store_id, sw.store_remask || '');
}
} catch (e) { dbg(`store_warehouse ERROR: ${e.message}`); }
}
// ====== 合并输出 ======
dbg('--- Merge output ---');
const list = [];
for (const oid of orderIds) {
const order = orderMap.get(String(oid)) || {};
const waybills = waybillMap.get(oid) || [];
dbg(` oid=${oid} orderKeys=[${Object.keys(order).join(',')}] waybills=${waybills.length}`);
if (waybills.length === 0) {
list.push({
order_id: oid, waybill_id: 0, waybill_code: '',
logistics_code: '', logistics_name: '', logistics_interface_id: 0, logistics_interface_name: '',
platform_code: '', waybill_status: null, waybill_status_text: '',
is_back: 'N', is_intercept: 'N', is_galaxy_receive: 'N',
weighing_weight: 0, weighing_weight_display: '0 kg',
delivery_order_code: order.delivery_order_code || '',
source_order_codes: order.source_order_codes || '',
pay_no: order.pay_no || '',
store_id: order.store_id || 0, store_name: order.store_name || '',
store_remask: storeRemarkMap.get(order.store_id) || '',
status: order.status || '', name: order.name || '', mobile: order.mobile || '',
province: order.province || '', city: order.city || '', area: order.area || '',
detail_address: order.detail_address || '',
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
});
} else {
for (const wb of waybills) {
list.push({
order_id: oid, waybill_id: wb.id, waybill_code: wb.waybill_code,
logistics_code: wb.logistics_code, logistics_name: wb.logistics_name,
logistics_interface_id: wb.logistics_interface_id, logistics_interface_name: wb.logistics_interface_name,
platform_code: wb.platform_code,
waybill_status: wb.status, waybill_status_text: wb.status_text,
is_back: wb.is_back, is_intercept: wb.is_intercept, is_galaxy_receive: wb.is_galaxy_receive,
weighing_weight: wb.weighing_weight, weighing_weight_display: wb.weighing_weight_display,
delivery_order_code: wb.delivery_order_code || order.delivery_order_code || '',
source_order_codes: wb.source_order_codes || order.source_order_codes || '',
pay_no: order.pay_no || '',
store_id: wb.store_id || order.store_id || 0, store_name: order.store_name || '',
store_remask: storeRemarkMap.get(wb.store_id || order.store_id) || '',
status: order.status || '', name: order.name || '', mobile: order.mobile || '',
province: order.province || '', city: order.city || '', area: order.area || '',
detail_address: order.detail_address || '',
buyer_nick: order.buyer_nick || '', seller_nick: order.seller_nick || '', shop_nick: order.shop_nick || '',
total_amount: order.total_amount || 0, item_amount: order.item_amount || 0, freight: order.freight || 0,
items_count: order.items_count || 0, items_weight: order.items_weight || 0,
wave_no: order.wave_no || '',
delivery_time: order.delivery_time ? app.formatDate(order.delivery_time) : null,
create_at: order.create_at ? app.formatDate(order.create_at) : null,
});
}
}
}
dbg(`list.length: ${list.length}`);
dbg('========== quickSearch END ==========');
return { list, keyword };
}
buildWaybillItem(er) {
return {
id: er.id,
waybill_code: er.waybill_code,
delivery_order_code: er.delivery_order_code || '',
source_order_codes: er.source_order_codes || '',
store_id: er.store_id || 0,
logistics_code: er.logistics_code || '',
logistics_name: er.logistics_name || '',
logistics_interface_id: er.logistics_interface_id || 0,
logistics_interface_name: er.logistics_interface_name || '',
platform_code: er.platform_code || '',
status: er.status,
status_text: er.status === 1 ? '已分配' : '未分配',
is_back: er.is_back || 'N',
is_intercept: er.is_intercept || 'N',
is_galaxy_receive: er.is_galaxy_receive || 'N',
weighing_weight: er.weighing_weight || 0,
weighing_weight_display: er.weighing_weight > 0
? `${(er.weighing_weight / 1000).toFixed(2)} kg` : '0 kg',
};
}
/**
* 按订单 ID 列表批量查询订单关键字段(遍历 dispatch → current → history)。
* @param {number[]} orderIds 订单ID列表
* @param {number} warehouseId 仓库ID
* @return {Promise<Map<number, Object>>} orderId → 订单行
*/
async fetchOrderMapByIds(orderIds, warehouseId) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getDispatchModel !== 'function') {
return [];
}
const tableOrders = [
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
];
const resultMap = new Map();
const remainingIds = new Set(orderIds.map(id => String(id)));
for (const entry of tableOrders) {
if (remainingIds.size === 0) break;
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') continue;
const rows = await model.findAll({
attributes: [
'id', 'delivery_order_code', 'source_order_codes', 'pay_no',
'store_id', 'status',
'name', 'mobile', 'province', 'city', 'area', 'detail_address',
'buyer_nick', 'seller_nick', 'shop_nick',
'total_amount', 'item_amount', 'freight',
'items_count', 'items_weight',
'wave_no', 'delivery_time', 'create_at',
],
where: {
id: { [Op.in]: [ ...remainingIds ].map(Number) },
},
raw: true,
});
for (const r of rows) {
const rid = String(r.id);
if (!resultMap.has(rid)) {
resultMap.set(rid, r);
remainingIds.delete(rid);
}
}
} catch (_err) {
continue;
}
}
return resultMap;
}
}
module.exports = DeliveryOrderService;

View File

@ -4105,6 +4105,32 @@ class PendingOrderService extends OrderBaseService {
},
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } }
);
} catch (expressErr) {
ctx.logger.warn(
`[order.pendingOrder.batchIntercept] 更新运单拦截标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}`
);
}
// 创建售后工单 + 通知快递群(失败不影响主流程)
try {
const op = this.getOrderLogOperator();
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: chunkOrderIds,
warehouseId,
creatorLabel: op.name || '系统',
});
} catch (workOrderErr) {
ctx.logger.warn(
`[order.pendingOrder.batchIntercept] 创建工单/通知失败, count=${chunkOrderIds.length}, error=${workOrderErr.message}`
);
}
// 写入操作日志
const logPayloads = chunkRows.map(row => {
const orderId = Number(row.id || 0);
@ -5635,6 +5661,18 @@ class PendingOrderService extends OrderBaseService {
},
});
// 同步清除运单表拦截+退回标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'N', is_back: 'N' },
{ where: { order_id: { [Op.in]: chunkOrderIds }, warehouse_id: warehouseId } }
);
} catch (expressErr) {
ctx.logger.warn(
`[order.pendingOrder.batchUnintercept] 清除运单标记失败, count=${chunkOrderIds.length}, error=${expressErr.message}`
);
}
// 写入操作日志 ORDER_INTERCEPT_CANCEL
const logPayloads = chunkRows.map(row => {
const orderId = Number(row.id || 0);

View File

@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList';
const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave';
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList';
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan';
const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,interceptScan';
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,batchQuickRecheckByWave,queryRecheckOrderSingleList,interceptScan';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -3611,6 +3611,18 @@ class RecheckOrderService extends OrderBaseService {
throw new Error('拦截状态更新失败,请稍后重试');
}
// 同步更新运单表:仅对已标记拦截的运单设置退回标记
try {
await ctx.model.OrderExpress.update(
{ is_back: 'Y' },
{ where: { order_id: orderId, warehouse_id: warehouseId, is_intercept: 'Y' } }
);
} catch (expressErr) {
ctx.logger.warn(
`[recheckOrder.confirmIntercept] 更新运单退回标记失败, orderId=${orderId}, error=${expressErr.message}`
);
}
// 拦截成功后释放储位分配(归还库存)
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
@ -3634,6 +3646,20 @@ class RecheckOrderService extends OrderBaseService {
);
}
// 创建售后工单 + 通知快递群(失败不影响主流程)
try {
const operator = this.getOrderLogOperator();
await this.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ orderId ],
warehouseId,
creatorLabel: operator.name || '系统',
});
} catch (workOrderErr) {
ctx.logger.warn(
`[recheckOrder.confirmIntercept] 创建工单/通知失败, orderId=${orderId}, error=${workOrderErr.message}`
);
}
const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim();
// 写入操作日志(失败不影响主流程)
@ -3668,6 +3694,182 @@ class RecheckOrderService extends OrderBaseService {
};
}
/**
* 拦截扫描:通过运单号查找运单记录,标记退回并处理关联工单与订单拦截状态。
*
* 处理流程:
* 1. 根据运单号查询 wms_order_express,找到则将 is_back 设为 'Y';未找到则创建新记录补充缺失快递
* 2. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
* "库内拦截成功"步骤并将工单置为 completed
* 3. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
* 并释放储位分配与订单锁(与 confirmIntercept 行为一致,订单级拦截覆盖所有面单含子面单)
*
* @param {Object} data 请求体。
* @param {string} data.waybill_code 运单号。
* @return {Promise<Object>} 拦截扫描结果,包含 waybill_code、is_back、after_sale(若有)、order。
*/
async interceptScan(data = {}) {
const { ctx, service } = this;
const { waybill_code: waybillCode } = data || {};
if (!waybillCode || !String(waybillCode).trim()) {
throw new Error('运单号不能为空');
}
const normalizedWaybillCode = String(waybillCode).trim();
const warehouseId = this.getWarehouseId();
const now = new Date();
// 1. 查询运单记录
let expressRecord = await ctx.model.OrderExpress.findOne({
where: { waybill_code: normalizedWaybillCode, warehouse_id: warehouseId },
raw: true,
});
// 1a. 缺失快递补充:运单记录不存在则创建新记录
if (!expressRecord) {
const created = await ctx.model.OrderExpress.create({
waybill_code: normalizedWaybillCode,
order_id: null,
warehouse_id: warehouseId,
is_back: 'Y',
is_intercept: 'Y',
create_at: now,
});
expressRecord = (created && created.toJSON ? created.toJSON() : created) || {};
} else {
// 2. 标记退回
await ctx.model.OrderExpress.update(
{ is_back: 'Y', is_intercept: 'Y' },
{ where: { id: expressRecord.id } }
);
}
// 3. 检查关联的未完结售后工单
const afterSale = await ctx.model.AfterSale.findOne({
where: {
waybill_no: normalizedWaybillCode,
warehouse_id: warehouseId,
deleted_at: null,
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
order: [[ 'id', 'DESC' ]],
raw: true,
});
let afterSaleResult = null;
if (afterSale) {
const operator = this.getOrderLogOperator();
const operatorId = operator.id ? Number(operator.id) : 0;
const operatorSnapshot = JSON.stringify({
id: String(operator.id || ''),
name: String(operator.name || ''),
});
try {
afterSaleResult = await service.systems.afterSale.handleWorkOrder({
id: afterSale.id,
remark: '库内拦截成功',
targetStatus: 'completed',
resolution: '库内拦截成功',
attachmentIds: [],
operatorId,
operatorSnapshot,
warehouseId,
});
} catch (workOrderErr) {
ctx.logger.warn(
`[recheckOrder.interceptScan] 处理工单失败, afterSaleId=${afterSale.id}, waybill=${normalizedWaybillCode}, error=${workOrderErr.message}`
);
// 工单处理失败不阻断主流程
}
}
// 4. 更新订单拦截状态(与 confirmIntercept 一致:订单级拦截,覆盖所有面单含子面单)
const orderId = Number(expressRecord.order_id || 0);
let orderResult = null;
if (orderId > 0) {
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const order = await orderModel.findOne({
where: orderWhere,
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'intercept_status' ],
raw: true,
});
if (order) {
await orderModel.update(
{ intercept_status: 'intercepted_at_warehouse', updated_at: now },
{ where: orderWhere }
);
// 释放储位分配
try {
await service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
});
} catch (allocErr) {
ctx.logger.warn(
`[recheckOrder.interceptScan] 释放储位分配失败, orderId=${orderId}, error=${allocErr.message}`
);
}
// 释放订单锁
try {
await orderModel.update(
{ lock_status: 'none', updated_at: now },
{ where: orderWhere }
);
} catch (lockErr) {
ctx.logger.warn(
`[recheckOrder.interceptScan] 释放锁失败, orderId=${orderId}, error=${lockErr.message}`
);
}
const orderNo = String(order.delivery_order_code || order.pre_delivery_order_code || '').trim();
// 写入操作日志
try {
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: logWarehouseId,
operationCode: 'ORDER_INTERCEPT_CONFIRM',
operator,
extras: {
warehouseId: logWarehouseId,
orderId,
orderNo,
previousInterceptStatus: String(order.intercept_status || '').trim(),
newInterceptStatus: 'intercepted_at_warehouse',
},
beforeChanges: null,
});
} catch (logErr) {
ctx.logger.warn(
`[recheckOrder.interceptScan] 写入操作日志失败, orderId=${orderId}, error=${logErr.message}`
);
}
orderResult = {
order_id: orderId,
order_no: orderNo,
intercept_status: 'intercepted_at_warehouse',
};
}
}
return {
waybill_code: normalizedWaybillCode,
is_back: 'Y',
is_intercept: 'Y',
after_sale: afterSaleResult ? afterSaleResult.after_sale : null,
order: orderResult,
};
}
/**
* 批量快捷复核:对一批订单 IDs 依次执行前置条件检查与复核流程。
* 支持部分失败:不满足前置条件的订单直接跳过并记录失败原因,其余订单继续走完拣货完成 + 复核标记流程。

View File

@ -11,9 +11,9 @@ class PickCartService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck';
const _noNeedRight = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck';
const _noNeedLog = '';
const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,detail,list,codeDuplicateCheck';
const _noNeedAuth = 'scan,bindTaskCart,create,update,delete,batchDelete,detail,list,codeDuplicateCheck';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -208,6 +208,41 @@ class PickCartService extends MainService {
}
}
/**
* 批量删除拣货车。已绑定任务的将被跳过。
*
* @param {Object} data 请求参数。
* @param {Array<number|string>} data.ids 拣货车ID列表。
* @return {Promise<Object>} 统一 success/fail 包装结果。
*/
async batchDelete(data = {}) {
const { service, ctx } = this;
const ids = Array.isArray(data && data.ids) ? data.ids : [];
if (ids.length === 0) {
return this.fail('ids 必填且必须为非空数组', {}, 400);
}
try {
const result = await service.systems.pickCart.batchDelete({ ids });
return this.success('ok', {
data: result,
code: 200,
});
} catch (error) {
const code = Number(error && error.code);
if (Number.isInteger(code) && code >= 400 && code < 600) {
const errorData = error && error.data && typeof error.data === 'object' && !Array.isArray(error.data)
? error.data
: {};
return this.fail(error.message || '批量删除失败', errorData, code);
}
ctx.logger.error('[PickCartService.batchDelete] 批量删除拣货车失败: %s', error && error.message ? error.message : error);
return this.fail('批量删除失败', {}, 500);
}
}
/**
* 查询拣货车详情。
*

View File

@ -14,7 +14,7 @@ class configService extends MainService {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
const _noNeedLog = '';
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}

View File

@ -23,9 +23,9 @@ class StorageTransactionService extends MainService {
*/
async list(data = {}) {
const { service } = this;
const { pagination, sort, group_by_batch } = data;
const { pagination, sort, group_by_batch, keyword } = data;
this.prepareWhereContext(data);
const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch);
const result = await service.systems.stockTransaction.list(pagination, sort, group_by_batch, keyword);
return this.success('ok', result);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,9 @@
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
// 从分组服务导入群类型定义,用于两层类型校验
const { GROUP_TYPES: INBOX_GROUP_TYPES } = require('../../inbox/groups');
/**
* 站内信群管理业务逻辑层。
* 提供群列表查询、禁用、修改等核心能力。
@ -262,6 +265,25 @@ class InboxGroupService extends Service {
const targetGroupType = data.groupType !== undefined
? String(data.groupType).trim()
: group.group_type || '';
// 两层类型校验:subType 必须在对应 groupType 的合法子类型列表中
if (data.subType !== undefined && targetGroupType) {
const gtDef = INBOX_GROUP_TYPES.find(gt => gt.type === targetGroupType);
if (!gtDef) {
throw new Error(`无效的群类型: ${targetGroupType}`);
}
const subType = String(data.subType || '').trim();
if (subType) {
const validKeys = gtDef.subTypes.map(st => st.key);
if (!validKeys.includes(subType)) {
throw new Error(
`子类型 "${subType}" 不在群类型 "${targetGroupType}" 的合法范围内,` +
`可用值: ${validKeys.join(', ')}`
);
}
}
}
const isExpress = targetGroupType === 'express';
// express_interfaces 处理
@ -374,6 +396,105 @@ class InboxGroupService extends Service {
throw new Error(`系统快递编码 "${trimmed}" 不存在`);
}
}
/**
* 根据快递接口ID和快递编码,查询绑定的售后群和揽收群。
*
* 匹配规则:
* 1. group_type = 'express'
* 2. system_express_code 精确匹配 expressCode
* 3. express_interfaces 为空(未设置)→ 视为匹配所有该快递的接口
* 4. express_interfaces 不为空 → 必须包含传入的 expressInterfaceId
*
* @param {Object} params 查询参数。
* @param {number} params.expressInterfaceId 快递接口ID(wms_express_interface.id)。
* @param {string} params.expressCode 快递编码(wms_express.code)。
* @param {number} [params.warehouseId] 仓库ID,不传则查所有仓库。
* @return {Promise<{afterSalesGroups: Array, pickupGroups: Array}>} 售后群和揽收群列表。
*/
async findGroupsByExpress({ expressInterfaceId, expressCode, warehouseId }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const eid = Number(expressInterfaceId);
const code = String(expressCode || '').trim();
if (!eid || !code) {
throw new Error('expressInterfaceId 和 expressCode 不能为空');
}
const where = {
group_type: 'express',
system_express_code: code,
[Op.or]: [
{ express_interfaces: { [Op.or]: [ null, '' ] } },
{ express_interfaces: { [Op.like]: `%${eid}%` } },
],
};
if (warehouseId) {
where.warehouse_id = Number(warehouseId);
}
const rows = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'group_id', 'sub_type', 'express_interfaces', 'warehouse_id', 'ext_data' ],
where,
raw: true,
});
const afterSalesGroups = rows.filter(r => r.sub_type === 'after_sales');
const pickupGroups = rows.filter(r => r.sub_type === 'pickup');
ctx.logger.info(
`[inbox group] 查快递绑定群 eid=${eid} code=${code} ` +
`after_sales=${afterSalesGroups.length} pickup=${pickupGroups.length}`
);
return { afterSalesGroups, pickupGroups };
}
/**
* 根据货主ID列表,查询绑定的货主售后群。
*
* 匹配规则:
* 1. group_type = 'store'
* 2. sub_type = 'after_sales'
* 3. store_id 在传入列表中
*
* @param {Object} params 查询参数。
* @param {number[]} params.storeIds 货主ID列表。
* @param {number} params.warehouseId 仓库ID。
* @return {Promise<Array>} 货主售后群列表 [{group_id, group_name, store_id, ext_data}]。
*/
async findStoreAfterSalesGroups({ storeIds, warehouseId }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0);
if (ids.length === 0) {
return [];
}
const rows = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'ext_data' ],
where: {
warehouse_id: Number(warehouseId),
group_type: 'store',
sub_type: 'after_sales',
store_id: { [Op.in]: ids },
},
raw: true,
});
ctx.logger.info(
`[inbox group] 查货主售后群 warehouse=${warehouseId} ` +
`stores=[${ids.join(',')}] found=${rows.length}`
);
return rows;
}
}
module.exports = InboxGroupService;

View File

@ -2592,42 +2592,54 @@ class PickSystemService extends Service {
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
}
await this.assertPickCartCodeUnique(cartCode, warehouseId);
// 使用事务:唯一性检查 + INSERT + LAST_INSERT_ID() 在同一连接,避免竞态
const transaction = await ctx.model.transaction();
let cartId = 0;
try {
await this.assertPickCartCodeUnique(cartCode, warehouseId, 0, transaction);
const insertResult = await ctx.model.query(`
INSERT INTO wms_pick_cart (
warehouse_id,
cart_code,
cart_name,
status,
create_time,
update_time
) VALUES (
:warehouseId,
:cartCode,
:cartName,
:status,
NOW(),
NOW()
)
`, {
replacements: {
warehouseId,
cartCode,
cartName,
status,
},
});
await ctx.model.query(`
INSERT INTO wms_pick_cart (
warehouse_id,
cart_code,
cart_name,
status,
create_time,
update_time
) VALUES (
:warehouseId,
:cartCode,
:cartName,
:status,
NOW(),
NOW()
)
`, {
replacements: {
warehouseId,
cartCode,
cartName,
status,
},
transaction,
});
const insertHead = Array.isArray(insertResult) ? insertResult[0] : null;
const insertMeta = Array.isArray(insertResult) ? insertResult[1] : null;
const cartId = Number(
(insertMeta && (insertMeta.insertId || insertMeta.lastID || insertMeta.id))
|| (insertHead && (insertHead.insertId || insertHead.lastID || insertHead.id))
|| 0
);
if (!Number.isInteger(cartId) || cartId <= 0) {
throw this.createBusinessError('拣货车创建失败', 500);
const idRows = await ctx.model.query('SELECT LAST_INSERT_ID() AS cart_id', {
type: ctx.model.QueryTypes.SELECT,
transaction,
});
cartId = Number(Array.isArray(idRows) && idRows.length > 0 ? (idRows[0].cart_id || 0) : 0);
if (!Number.isInteger(cartId) || cartId <= 0) {
throw new Error('cartId 无效');
}
await transaction.commit();
} catch (error) {
await transaction.rollback();
if (error.message === 'cartId 无效') {
throw this.createBusinessError('拣货车创建失败', 500);
}
throw error;
}
const cartRow = await this.getPickCartById(cartId, warehouseId);
@ -2823,6 +2835,104 @@ class PickSystemService extends Service {
};
}
/**
* 批量删除拣货车。已绑定任务或存在有效绑定记录的将被跳过。
*
* @param {Object} params 删除参数。
* @param {Array<number|string>} params.ids 拣货车ID列表。
* @return {Promise<Object>} { deleted_ids, skipped_ids, deleted_count, skipped_count }
*/
async pickCartBatchDelete(params = {}) {
const { ctx } = this;
const rawIds = Array.isArray(params && params.ids) ? params.ids : [];
const { warehouseId } = this.resolveOperatorContext();
if (!Array.isArray(rawIds) || rawIds.length === 0) {
throw this.createBusinessError('ids 必填且必须为非空数组', 400);
}
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少当前用户仓库上下文 store_id', 400);
}
// 去重并转为数字,过滤非法值
const idSet = new Set();
for (const id of rawIds) {
const num = Number(id);
if (Number.isInteger(num) && num > 0) {
idSet.add(num);
}
}
const ids = Array.from(idSet);
if (ids.length === 0) {
throw this.createBusinessError('ids 中没有合法的拣货车ID', 400);
}
// 1) 查出当前仓库下这些拣货车的 current_task_id
const cartRows = await ctx.model.query(`
SELECT id, cart_code, current_task_id
FROM wms_pick_cart
WHERE id IN (:ids)
AND warehouse_id = :warehouseId
`, {
replacements: { ids, warehouseId },
type: ctx.model.QueryTypes.SELECT,
});
// 2) 查出有效绑定记录
const bindingRows = await ctx.model.query(`
SELECT cart_id
FROM wms_pick_task_cart_binding
WHERE cart_id IN (:ids)
AND warehouse_id = :warehouseId
AND is_active = 1
`, {
replacements: { ids, warehouseId },
type: ctx.model.QueryTypes.SELECT,
});
const bindingCartIds = new Set(
(Array.isArray(bindingRows) ? bindingRows : []).map(r => Number(r.cart_id || 0)).filter(id => id > 0)
);
// 3) 分类:已绑定任务 / 有效绑定记录 → skip;其余 → delete
const skipIds = [];
const deleteIds = [];
for (const row of (Array.isArray(cartRows) ? cartRows : [])) {
const cartId = Number(row.id || 0);
if (Number(row.current_task_id || 0) > 0 || bindingCartIds.has(cartId)) {
skipIds.push(cartId);
} else {
deleteIds.push(cartId);
}
}
// ids 中存在但 cartRows 中不存在的(不属于该仓库或已不存在),也归入 skip
const foundIds = new Set((Array.isArray(cartRows) ? cartRows : []).map(r => Number(r.id || 0)));
for (const id of ids) {
if (!foundIds.has(id) && !skipIds.includes(id)) {
skipIds.push(id);
}
}
// 4) 执行删除
if (deleteIds.length > 0) {
await ctx.model.query(`
DELETE FROM wms_pick_cart
WHERE id IN (:deleteIds)
AND warehouse_id = :warehouseId
`, {
replacements: { deleteIds, warehouseId },
});
}
return {
deleted_ids: deleteIds,
skipped_ids: skipIds,
deleted_count: deleteIds.length,
skipped_count: skipIds.length,
};
}
/**
* 查询拣货车详情。
*

View File

@ -54,6 +54,17 @@ class PickCartSystemService extends Service {
return await this.service.systems.pick.pickCartDelete(params);
}
/**
* 批量删除拣货车。已绑定任务的将被跳过。
*
* @param {Object} params 删除参数。
* @param {Array<number|string>} params.ids 拣货车ID列表。
* @return {Promise<Object>} 批量删除结果。
*/
async batchDelete(params = {}) {
return await this.service.systems.pick.pickCartBatchDelete(params);
}
/**
* 查询拣货车详情。
*

View File

@ -59,6 +59,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
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: '默认快递编码',
@ -228,6 +236,55 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
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: INTERNAL_WAVE_STRATEGY_VERSION_KEY,
name: '仓库波次策略版本号',

View File

@ -193,7 +193,7 @@ class StockTransactionService extends Service {
return ctx.model.StockTransaction.create(payload, options);
}
async list(pageParams = {}, sortParams = {}, groupByBatch = false) {
async list(pageParams = {}, sortParams = {}, groupByBatch = false, keyword = '') {
const { ctx, app } = this;
const { Op, fn, col, literal } = app.Sequelize;
@ -208,6 +208,21 @@ class StockTransactionService extends Service {
],
};
// keyword 快捷搜索:按 item_code + barcode 匹配,解析为 stock_id IN 条件
const normalizedKeyword = String(keyword || '').trim();
if (normalizedKeyword) {
const stockIds = await this._resolveKeywordToStockIds(normalizedKeyword, 'warehouse_id', warehouseId);
if (stockIds.length > 0) {
baseWhere[Op.and].push({ stock_id: { [Op.in]: stockIds } });
} else {
// keyword 无匹配结果,直接返回空列表
return {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0 },
};
}
}
// 动态 where 条件
const parsed = ctx.whereParsed;
if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) {

View File

@ -2689,9 +2689,14 @@ class ReceivingService extends Service {
}),
};
// 判断是否为改绑(明细之前已绑定过其他商品)
const isRebind = receivingDetail.system_product_id
&& Number(receivingDetail.system_product_id) !== systemProductId;
// 如果收货明细有条码且商品尚未包含该条码,则自动为商品新增条码
// 但改绑操作不写入条码(条码属于旧商品上下文,不应污染新商品)
const detailBarcode = String(receivingDetail.barcode || '').trim();
if (detailBarcode && !barcodes.includes(detailBarcode)) {
if (!isRebind && detailBarcode && !barcodes.includes(detailBarcode)) {
try {
await app.model.StockBarcode.create({
stock_id: systemProductId,
@ -4620,6 +4625,28 @@ class ReceivingService extends Service {
return { code: 0, message: '该入库单尚未关联收货单', data: null };
}
// 校验所有 receiving 属于当前仓库
const validReceivings = await ctx.model.Receiving.findAll({
where: { id: { [Op.in]: receivingIds }, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
const validReceivingIds = validReceivings.map(r => r.id);
if (validReceivingIds.length === 0) {
return { code: 1, message: '收货单不存在或不属于当前仓库', list: [], total: 0 };
}
// 2.5 获取入库单的所有合法 stock_id(用于校验收货明细的 system_product_id)
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: normalizedEntryOrderId },
attributes: [ 'stock_id' ],
raw: true,
});
const validStockIds = [ ...new Set(entryItems.map(ei => ei.stock_id).filter(Boolean)) ];
if (validStockIds.length === 0) {
return { code: 0, message: '入库单无明细,无法匹配收货明细', data: null };
}
// 排除已绑定的收货明细(wms_inbound_direct_log 中有记录且未软删除)
const notBoundCondition = app.Sequelize.literal(
'NOT EXISTS (SELECT 1 FROM wms_inbound_direct_log erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)'
@ -4629,7 +4656,8 @@ class ReceivingService extends Service {
const details = await ctx.model.ReceivingDetail.findAll({
where: {
[Op.and]: [
{ receiving_id: { [Op.in]: receivingIds } },
{ receiving_id: { [Op.in]: validReceivingIds } },
{ system_product_id: { [Op.in]: validStockIds } },
notBoundCondition,
],
},
@ -4667,7 +4695,10 @@ class ReceivingService extends Service {
for (const detail of details) {
// 优先按明细 ID 精确匹配(托盘唛头场景)
if (isNumericBarcode && detail.id === Number(normalizedBarcode)) {
matchedDetails.push(detail);
const sd = stockDetailMap.get(Number(detail.system_product_id));
if (sd) {
matchedDetails.push(detail);
}
continue;
}
@ -4687,15 +4718,21 @@ class ReceivingService extends Service {
return { code: 0, message: '未找到匹配的收货明细', data: null };
}
const list = matchedDetails.map(matchedDetail => ({
detail_id: matchedDetail.id,
receiving_id: matchedDetail.receiving_id,
barcode: matchedDetail.barcode || '',
product_name: matchedDetail.product_name || '',
actual_quantity: matchedDetail.actual_quantity || 0,
receiving_status: matchedDetail.receiving_status || '',
stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null,
}));
const list = matchedDetails.map(matchedDetail => {
const sd = stockDetailMap.get(Number(matchedDetail.system_product_id));
const stockBarcode = (sd && Array.isArray(sd.barcodes) && sd.barcodes.length > 0)
? (sd.barcodes[0].barcode || '')
: '';
return {
detail_id: matchedDetail.id,
receiving_id: matchedDetail.receiving_id,
barcode: stockBarcode || matchedDetail.barcode || '',
product_name: matchedDetail.product_name || '',
actual_quantity: matchedDetail.actual_quantity || 0,
receiving_status: matchedDetail.receiving_status || '',
stock: sd || null,
};
});
return {
code: 200,

View File

@ -149,10 +149,27 @@ class WaybillService extends MainService {
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
*/
async list({ where = {}, pagination = {}, sort = {} } = {}) {
async list({ where: rawWhere = {}, pagination = {}, sort = {} } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 标准化 where 条件:将前端 operator/value 格式(如 {operator:"contains", value:"YT..."})统一转为标准条件对象
const where = this.normalizeWhereParams(rawWhere);
/**
* 从 where 条件中提取实际值。
* 标准化后的条件为 {operator, value} 对象,本函数提取 .value;
* 对于未标准化的原始值(string/number)直接返回。
* @param {*} c 条件值
* @param {*} defaultValue 默认值
* @return {*} 提取后的实际值
*/
const val = (c, defaultValue) => {
if (c === undefined || c === null) return defaultValue;
if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value;
return c;
};
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
@ -172,8 +189,9 @@ class WaybillService extends MainService {
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
const mainCode = String(where.mainWaybillCode).trim();
const mainWaybillCode = val(where.mainWaybillCode);
if (mainWaybillCode && String(mainWaybillCode).trim()) {
const mainCode = String(mainWaybillCode).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
@ -195,13 +213,15 @@ class WaybillService extends MainService {
}
// 运单号模糊搜索
if (where.waybillCode && String(where.waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
const waybillCode = val(where.waybillCode);
if (waybillCode && String(waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCode).trim()}%` };
}
// 订单ID等值
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
queryWhere.order_id = Number(where.orderId);
const orderId = val(where.orderId);
if (orderId !== undefined && orderId !== null && String(orderId).trim() !== '') {
queryWhere.order_id = Number(orderId);
}
// 订单号模糊搜索
@ -211,43 +231,51 @@ class WaybillService extends MainService {
// }
// 物流公司编码等值
if (where.logisticsCode && String(where.logisticsCode).trim()) {
queryWhere.logistics_code = String(where.logisticsCode).trim();
const logisticsCode = val(where.logisticsCode);
if (logisticsCode && String(logisticsCode).trim()) {
queryWhere.logistics_code = String(logisticsCode).trim();
}
// 物流接口ID等值
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
const logisticsInterfaceId = val(where.logisticsInterfaceId);
if (logisticsInterfaceId !== undefined && logisticsInterfaceId !== null && String(logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(logisticsInterfaceId);
}
// 平台编码等值
if (where.platformCode && String(where.platformCode).trim()) {
queryWhere.platform_code = String(where.platformCode).trim();
const platformCode = val(where.platformCode);
if (platformCode && String(platformCode).trim()) {
queryWhere.platform_code = String(platformCode).trim();
}
// 运单状态等值
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
queryWhere.status = Number(where.status);
const statusVal = val(where.status);
if (statusVal !== undefined && statusVal !== null && String(statusVal).trim() !== '') {
queryWhere.status = Number(statusVal);
}
// 是否退回
if (where.isBack && String(where.isBack).trim()) {
queryWhere.is_back = String(where.isBack).trim();
const isBack = val(where.isBack);
if (isBack && String(isBack).trim()) {
queryWhere.is_back = String(isBack).trim();
}
// 是否拦截
if (where.isIntercept && String(where.isIntercept).trim()) {
queryWhere.is_intercept = String(where.isIntercept).trim();
const isIntercept = val(where.isIntercept);
if (isIntercept && String(isIntercept).trim()) {
queryWhere.is_intercept = String(isIntercept).trim();
}
// 是否揽收
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
const isGalaxyReceive = val(where.isGalaxyReceive);
if (isGalaxyReceive && String(isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(isGalaxyReceive).trim();
}
// 运单类型:主单号 / 子单号
if (where.waybillType && String(where.waybillType).trim()) {
const type = String(where.waybillType).trim();
const waybillType = val(where.waybillType);
if (waybillType && String(waybillType).trim()) {
const type = String(waybillType).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
@ -256,18 +284,21 @@ class WaybillService extends MainService {
}
// 货主ID等值
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
queryWhere.store_id = Number(where.storeId);
const storeId = val(where.storeId);
if (storeId !== undefined && storeId !== null && String(storeId).trim() !== '') {
queryWhere.store_id = Number(storeId);
}
// 包材ID等值
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(where.packageMaterialId);
const packageMaterialId = val(where.packageMaterialId);
if (packageMaterialId !== undefined && packageMaterialId !== null && String(packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(packageMaterialId);
}
// 是否已称重
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
const hasWeight = String(where.hasWeighingWeight).trim();
const hasWeighingWeight = val(where.hasWeighingWeight);
if (hasWeighingWeight !== undefined && hasWeighingWeight !== null && String(hasWeighingWeight).trim() !== '') {
const hasWeight = String(hasWeighingWeight).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
@ -276,19 +307,22 @@ class WaybillService extends MainService {
}
// 关键词模糊搜索
if (where.keyword && String(where.keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
const keyword = val(where.keyword);
if (keyword && String(keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` };
}
// 创建时间范围
if (where.createdAtStart && String(where.createdAtStart).trim()) {
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
const createdAtStart = val(where.createdAtStart);
if (createdAtStart && String(createdAtStart).trim()) {
const startDate = this.normalizeDate(String(createdAtStart).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
const createdAtEnd = val(where.createdAtEnd);
if (createdAtEnd && String(createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(createdAtEnd).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
@ -302,6 +336,7 @@ class WaybillService extends MainService {
attributes: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'delivery_order_code', 'source_order_codes',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
@ -401,13 +436,11 @@ class WaybillService extends MainService {
main_waybill_code: mainCode,
waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号',
order_id: row.order_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code
order_no: '',
order_no: row.delivery_order_code || row.source_order_codes || '',
source_order_codes: row.source_order_codes || '',
warehouse_id: row.warehouse_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot
warehouse_name: '',
store_id: row.store_id || 0,
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot
store_name: '',
store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '',
business_key: row.business_key,
@ -636,10 +669,24 @@ class WaybillService extends MainService {
* @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。
* @return {Promise<Object>} 导出结果 { list, current_count, total_count, url }。
*/
async export({ where = {}, sort = {}, exportFields, onProgress } = {}) {
async export({ where: rawWhere = {}, sort = {}, exportFields, onProgress } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
// 标准化 where 条件
const where = this.normalizeWhereParams(rawWhere);
/**
* 从标准化后的 where 条件中提取实际值。
* @param {*} c 条件值
* @param {*} defaultValue 默认值
* @return {*} 提取后的实际值
*/
const val = (c, defaultValue) => {
if (c === undefined || c === null) return defaultValue;
if (typeof c === 'object' && !Array.isArray(c) && 'value' in c) return c.value;
return c;
};
// 仓库隔离
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
@ -655,8 +702,9 @@ class WaybillService extends MainService {
const queryWhere = { warehouse_id: warehouseId };
// 主单号查询
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
const mainCode = String(where.mainWaybillCode).trim();
const mainWaybillCodeExport = val(where.mainWaybillCode);
if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) {
const mainCode = String(mainWaybillCodeExport).trim();
const mainRecord = await ctx.model.OrderExpress.findOne({
where: {
waybill_code: mainCode,
@ -676,36 +724,46 @@ class WaybillService extends MainService {
}
}
if (where.waybillCode && String(where.waybillCode).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
const waybillCodeExport = val(where.waybillCode);
if (waybillCodeExport && String(waybillCodeExport).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillCodeExport).trim()}%` };
}
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
queryWhere.order_id = Number(where.orderId);
const orderIdExport = val(where.orderId);
if (orderIdExport !== undefined && orderIdExport !== null && String(orderIdExport).trim() !== '') {
queryWhere.order_id = Number(orderIdExport);
}
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
if (where.logisticsCode && String(where.logisticsCode).trim()) {
queryWhere.logistics_code = String(where.logisticsCode).trim();
const logisticsCodeExport = val(where.logisticsCode);
if (logisticsCodeExport && String(logisticsCodeExport).trim()) {
queryWhere.logistics_code = String(logisticsCodeExport).trim();
}
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
const logisticsInterfaceIdExport = val(where.logisticsInterfaceId);
if (logisticsInterfaceIdExport !== undefined && logisticsInterfaceIdExport !== null && String(logisticsInterfaceIdExport).trim() !== '') {
queryWhere.logistics_interface_id = Number(logisticsInterfaceIdExport);
}
if (where.platformCode && String(where.platformCode).trim()) {
queryWhere.platform_code = String(where.platformCode).trim();
const platformCodeExport = val(where.platformCode);
if (platformCodeExport && String(platformCodeExport).trim()) {
queryWhere.platform_code = String(platformCodeExport).trim();
}
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
queryWhere.status = Number(where.status);
const statusExport = val(where.status);
if (statusExport !== undefined && statusExport !== null && String(statusExport).trim() !== '') {
queryWhere.status = Number(statusExport);
}
if (where.isBack && String(where.isBack).trim()) {
queryWhere.is_back = String(where.isBack).trim();
const isBackExport = val(where.isBack);
if (isBackExport && String(isBackExport).trim()) {
queryWhere.is_back = String(isBackExport).trim();
}
if (where.isIntercept && String(where.isIntercept).trim()) {
queryWhere.is_intercept = String(where.isIntercept).trim();
const isInterceptExport = val(where.isIntercept);
if (isInterceptExport && String(isInterceptExport).trim()) {
queryWhere.is_intercept = String(isInterceptExport).trim();
}
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
const isGalaxyReceiveExport = val(where.isGalaxyReceive);
if (isGalaxyReceiveExport && String(isGalaxyReceiveExport).trim()) {
queryWhere.is_galaxy_receive = String(isGalaxyReceiveExport).trim();
}
if (where.waybillType && String(where.waybillType).trim()) {
const type = String(where.waybillType).trim();
const waybillTypeExport = val(where.waybillType);
if (waybillTypeExport && String(waybillTypeExport).trim()) {
const type = String(waybillTypeExport).trim();
if (type === 'main' || type === '1') {
queryWhere.business_key = 1;
} else if (type === 'child' || type === '2') {
@ -713,31 +771,37 @@ class WaybillService extends MainService {
}
}
// 货主ID等值
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
queryWhere.store_id = Number(where.storeId);
const storeIdExport = val(where.storeId);
if (storeIdExport !== undefined && storeIdExport !== null && String(storeIdExport).trim() !== '') {
queryWhere.store_id = Number(storeIdExport);
}
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
queryWhere.package_material_id = Number(where.packageMaterialId);
const packageMaterialIdExport = val(where.packageMaterialId);
if (packageMaterialIdExport !== undefined && packageMaterialIdExport !== null && String(packageMaterialIdExport).trim() !== '') {
queryWhere.package_material_id = Number(packageMaterialIdExport);
}
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
const hasWeight = String(where.hasWeighingWeight).trim();
const hasWeighingWeightExport = val(where.hasWeighingWeight);
if (hasWeighingWeightExport !== undefined && hasWeighingWeightExport !== null && String(hasWeighingWeightExport).trim() !== '') {
const hasWeight = String(hasWeighingWeightExport).trim();
if (hasWeight === 'true') {
queryWhere.weighing_weight = { [Op.gt]: 0 };
} else if (hasWeight === 'false') {
queryWhere.weighing_weight = { [Op.eq]: 0 };
}
}
if (where.keyword && String(where.keyword).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
const keywordExport = val(where.keyword);
if (keywordExport && String(keywordExport).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` };
}
if (where.createdAtStart && String(where.createdAtStart).trim()) {
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
const createdAtStartExport = val(where.createdAtStart);
if (createdAtStartExport && String(createdAtStartExport).trim()) {
const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false);
if (startDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
}
}
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
const createdAtEndExport = val(where.createdAtEnd);
if (createdAtEndExport && String(createdAtEndExport).trim()) {
const endDate = this.normalizeDate(String(createdAtEndExport).trim(), true);
if (endDate) {
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
}
@ -768,10 +832,10 @@ class WaybillService extends MainService {
for (let page = 0; page < totalPages; page++) {
const pageRows = await ctx.model.OrderExpress.findAll({
where: queryWhere,
// TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充
attributes: [
'id', 'waybill_code', 'order_id', 'business_key', 'status',
'warehouse_id', 'store_id',
'delivery_order_code', 'source_order_codes',
'logistics_code', 'logistics_name',
'logistics_interface_id', 'logistics_interface_name',
'platform_code',
@ -826,8 +890,8 @@ class WaybillService extends MainService {
main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '',
waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'),
order_id: r => r.order_id,
// TODO: 快照列未落库,暂时填空;快照就绪后替换
order_no: () => '',
order_no: r => r.delivery_order_code || r.source_order_codes || '',
source_order_codes: r => r.source_order_codes || '',
warehouse_id: r => r.warehouse_id,
warehouse_name: () => '',
store_id: r => r.store_id || 0,
@ -915,6 +979,7 @@ class WaybillService extends MainService {
waybill_type: '运单类型',
order_id: '订单ID',
order_no: '订单号',
source_order_codes: '原始订单号',
warehouse_id: '仓库ID',
warehouse_name: '仓库名称',
store_id: '货主ID',

View File

@ -93,7 +93,7 @@ erDiagram
wms_after_sale_detail {
BIGINT id PK "主键"
BIGINT after_sale_id FK "关联售后主表"
TINYINT step_status "步骤状态"
VARCHAR step_status "步骤记录时主表状态"
BIGINT operator_id "操作人ID"
TEXT operator_snapshot "操作人信息快照"
VARCHAR action "操作动作"
@ -277,6 +277,7 @@ const AFTER_SALE_TYPES = [
|----|------|
| `pending` | 待处理 |
| `processing` | 处理中 |
| `pending_feedback` | 等待外部反馈(内部处理完成,等待外部反馈后再决定是否继续处理) |
| `completed` | 已完成 |
| `closed` | 已关闭 |
| `cancelled` | 已取消 |
@ -331,7 +332,7 @@ const AFTER_SALE_TYPES = [
|------|------|------|--------|------|
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
| `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) |
| `step_status` | `TINYINT UNSIGNED` | ✅ | 0 | 步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过 |
| `step_status` | `VARCHAR(20)` | ✅ | `processing` | 步骤记录时售后主表的状态,与 `wms_after_sale.status` 完全一致: pending / processing / completed / closed / cancelled。每次写入步骤时取主表当前 status 快照 |
| `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 |
| `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 |
| `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" |
@ -342,18 +343,19 @@ const AFTER_SALE_TYPES = [
| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 |
#### 3.2.2 步骤状态 `step_status` 枚举
#### 3.2.2 步骤状态 `step_status` 说明
| 值 | 说明 | 典型场景 |
|----|------|---------|
| `0` | 待开始 | 步骤尚未触发,等待前置步骤完成 |
| `1` | 进行中 | 步骤正在处理中 |
| `2` | 已完成 | 步骤处理完毕 |
| `3` | 已跳过 | 因条件不满足或审批豁免而跳过此步骤 |
`step_status` 与 `wms_after_sale.status` 完全一致(类型、枚举均相同),每次写入步骤时记录步骤发生时主表的当前状态快照。枚举值:
> **设计考量**:`step_status` 决定步骤的当前状态。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容。后续步骤在前置步骤全部 `completed` 或 `skipped` 后才能开始。步骤可在创建售后单时预置(如按 `type` 生成一套标准步骤),也可在处理过程中动态追加。
>
> **外部系统触发说明**:当步骤由外部系统触发(如快递签收回调、支付平台退款回调、ERP 同步等)时,`operator_id` 为 NULL,`action` 记录触发来源(如"快递签收回调"、"支付宝退款通知")。这确保自动触发的步骤可追溯来源,同时与人工操作步骤明确区分。
| 值 | 说明 |
|----|------|
| `pending` | 待处理 |
| `processing` | 处理中 |
| `completed` | 已完成 |
| `closed` | 已关闭 |
| `cancelled` | 已取消 |
> **设计考量**:`step_status` 记录的是"该步骤发生时,售后主表处于什么状态",而非步骤本身的"进行中/已完成"标记。这使得每条步骤都能直接追溯到该步骤执行时的工单状态上下文,无需 JOIN 主表查阅历史状态。步骤按 `created_at` 自然时间排序。
### 3.2.3 附件关联
@ -426,8 +428,11 @@ stateDiagram-v2
[*] --> pending: 创建售后单
pending --> processing: 指派处理人 / 开始处理
pending --> cancelled: 取消
processing --> pending_feedback: 内部处理完毕,等待外部反馈
processing --> completed: 处理完成
processing --> closed: 强制关闭
pending_feedback --> processing: 收到外部反馈,继续处理
pending_feedback --> completed: 外部反馈确认完成
completed --> [*]
closed --> [*]
cancelled --> [*]
@ -437,9 +442,11 @@ stateDiagram-v2
|------|---------|------|
| `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 |
| `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 |
| `processing` → `pending_feedback` | 内部处理完毕,等待外部反馈 | 如已将拦截信息发给运方,等待运方反馈拦截结果 |
| `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` |
| `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 |
| 转单(跨角色组) | 客服转仓库 / 仓库转财务等 | 更新 `role_group` 为目标角色组,如 `customer_service` → `warehouse`;同时可在 `wms_after_sale_detail` 记录转单步骤 |
| `pending_feedback` → `processing` | 收到外部反馈,继续处理 | 如运方反馈已拦截/未拦截,回到内部通知客户 |
| `pending_feedback` → `completed` | 外部反馈确认完成 | 如平台退款回调确认到账 |
**理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。
@ -457,9 +464,9 @@ stateDiagram-v2
├─ waybill_id / waybill_no: 客户寄回的快递单号
├─ receiving_id / receiving_no: 仓库收货单
└─ 进度步骤:
├─ step_status=2(已完成), operator_id=1001, action=客服接单-受理退货申请
├─ step_status=2(已完成), operator_id=2001, action=仓库收货-确认收货入库
└─ step_status=0(待开始), action=退款打款
├─ step_status=processing, operator_id=1001, action=客服接单-受理退货申请
├─ step_status=processing, operator_id=2001, action=仓库收货-确认收货入库
└─ step_status=processing, action=退款打款
```
> **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。
@ -471,9 +478,9 @@ stateDiagram-v2
├─ waybill_id / waybill_no: 客户寄回的快递单号
├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单
└─ 进度步骤:
├─ step_status=2(已完成), action=客服接单-确认换货申请
├─ step_status=2(已完成), action=退回入库-客户退回商品已入库
└─ step_status=1(进行中), action=补发换货-仓库补发新商品
├─ step_status=processing, action=客服接单-确认换货申请
├─ step_status=processing, action=退回入库-客户退回商品已入库
└─ step_status=processing, action=补发换货-仓库补发新商品
```
### 场景3:订单售后(仓库理赔)
@ -482,9 +489,9 @@ stateDiagram-v2
售后单 type=order, sub_type=damage
├─ claim_needed=1, claim_amount=50.00, claim_status=pending
└─ 进度步骤:
├─ step_status=2(已完成), action=客服接单-受理仓库理赔
├─ step_status=2(已完成), action=核实定损, remark=仓库出库破损, 核定赔偿50元
└─ step_status=1(进行中), action=审批打款
├─ step_status=processing, action=客服接单-受理仓库理赔
├─ step_status=processing, action=核实定损, remark=仓库出库破损, 核定赔偿50元
└─ step_status=processing, action=审批打款
```
### 场景3b:订单售后(运方理赔)
@ -494,9 +501,9 @@ stateDiagram-v2
├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending
├─ waybill_id / waybill_no: 涉损运单
└─ 进度步骤:
├─ step_status=2(已完成), action=客服接单-受理运方理赔
├─ step_status=2(已完成), action=核实定损, remark=运输途中破损, 核定赔偿200元
└─ step_status=1(进行中), action=快递审批
├─ step_status=processing, action=客服接单-受理运方理赔
├─ step_status=processing, action=核实定损, remark=运输途中破损, 核定赔偿200元
└─ step_status=processing, action=快递审批
```
> **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。
@ -509,10 +516,10 @@ stateDiagram-v2
├─ receiving_id / receiving_no: 仓库收货单
├─ order_stockout_id / order_stockout_no: 退货出库单
└─ 进度步骤:
├─ step_status=2(已完成), action=客服接单-批量退货受理
├─ step_status=2(已完成), operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2)
├─ step_status=2(已完成), action=退货入库
└─ step_status=0(待开始), action=退款打款
├─ step_status=processing, action=客服接单-批量退货受理
├─ step_status=processing, operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2)
├─ step_status=processing, action=退货入库
└─ step_status=processing, action=退款打款
```
> **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。
@ -601,13 +608,16 @@ app/model/after_sale_detail.js → wms_after_sale_detail
| 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 |
| 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 |
| 财务 | 518 | 519, 520, 521 | 522, 508 |
| 经理 | — | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 |
> - 客服:全部权限(创建、更新、转单、查理赔)
> - 仓库:只读查询 + 更新处理结果
> - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。
> - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS)
> - 经理:全部售后权限
> **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。
> **财务组角色**:role_code=`finance`,role_name=`财务组`,自动创建并授权。
---
@ -750,14 +760,13 @@ app/model/after_sale_detail.js → wms_after_sale_detail
```json
{
"method": "afterSale.handleWorkOrder",
"description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。非客服组处理完成后自动转回客服组继续跟进。",
"description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。步骤 action 由服务端固定为\"处理工单\",前端无需传入。status 不填或填错默认 processing。非客服组处理完成后自动转回客服组继续跟进。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" },
{ "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态(pending/processing/completed/closed),不传则保持当前状态" },
{ "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"客服接单"、"仓库验货"、"确认收货入库"、"退款打款"" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注/消息主体" },
{ "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态: processing | completed | closed | cancelled。不填或填错默认 processing。注意:pending 不适用于处理操作" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" },
{ "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" }
],
"response": [
@ -766,7 +775,6 @@ app/model/after_sale_detail.js → wms_after_sale_detail
],
"errors": [
{ "code": 400, "message": "工单不存在或参数缺失" },
{ "code": 403, "message": "无权限处理该工单(role_group 不匹配)" },
{ "code": 500, "message": "处理失败" }
]
}
@ -777,8 +785,8 @@ app/model/after_sale_detail.js → wms_after_sale_detail
1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403)
2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot`
3. 写入 `wms_after_sale_detail`:
- `step_status = 2`(已完成)
- `action` = 入参 `action`
- `step_status` = 主表当前 status(由 safeStatus 决定,不填或填错默认 processing)
- `action` = 服务端固定 `"处理工单"`
- `remark` = 入参 `remark`
- `operator_id` / `operator_snapshot` = 当前用户
- `started_at = now`, `completed_at = now`
@ -786,9 +794,9 @@ app/model/after_sale_detail.js → wms_after_sale_detail
- `business_type = 'after_sale_detail'`
- `business_id` = 刚写入的 `detail.id`
- `file_id = attachment_id`
5. 若传入了 `status`,更新 `wms_after_sale.status`
6. 若当前 `role_group` ≠ `'customer_service'` 且 `status` ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进)
7. 若 `status = 'completed'`,同时写入 `resolution` 和 `resolved_at`
5. 更新 `wms_after_sale.status`:始终写入 safeStatus(默认 processing,白名单校验,不含 pending)
6. 若当前 `role_group` ≠ `'customer_service'` 且 status ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进)
7. 若 status = `'completed'`,同时写入 `resolution` 和 `resolved_at`
### 10.8 理赔登记 `afterSale.registerClaim`
@ -826,7 +834,7 @@ app/model/after_sale_detail.js → wms_after_sale_detail
1. 校验工单 `id` 存在
2. 从登录上下文提取操作人信息
3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`)
4. 写入 `wms_after_sale_detail`(step_status=2,action/remark/operator)
4. 写入 `wms_after_sale_detail`(step_status=主表当前 status,action/remark/operator)
5. 若有 `attachment_ids`,绑定到本次步骤
**使用场景:**

View File

@ -0,0 +1,42 @@
'use strict';
/**
* 新增售后模块页面权限(售后工单 + 工单列表)。
*
* 新增:
* Web Pages:
* 524 — afterSale.workOrder 售后工单(根菜单)
* 525 — afterSale.workOrder.list 工单列表(子页面,parent_id=524)
*
* 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。
*/
const TABLE = 'wms_permission';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const pages = [
[524, 'afterSale.workOrder', null, 'afterSale.workOrder', null, '售后工单', null, 0, 0, null, 'web_pages', 15, 1],
[525, 'afterSale.workOrder.list', null, 'afterSale.workOrder.list', null, '工单列表', null, 0, 0, 524, 'web_pages', 0, 1],
];
for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] }
);
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
const ids = [524, 525];
const placeholders = ids.map(() => '?').join(', ');
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`,
{ replacements: ids }
);
},
};

View File

@ -0,0 +1,103 @@
'use strict';
/**
* 为售后模块新增页面权限授权,并创建财务组角色。
*
* 操作:
* 1. 新建财务组角色(role_code='finance')
* 2. 为以下角色追加页面权限 524 (afterSale.workOrder)、525 (afterSale.workOrder.list):
* - 经理 (role_code=2)
* - 客服组-主管 (role_code=05)
* - 客服组-员工 (role_code=04)
* - 仓库组-主管 (role_code=warehouse)
* - 仓库组-员工 (role_code=warehouse_role)
* - 生产组-主管 (role_code=03)
* - 生产组-拣货 (role_code=021)
*
* 幂等设计:
* - 财务组角色使用 INSERT IGNORE,已存在则跳过
* - 权限追加使用 JSON_ARRAY_APPEND,不重复添加
*/
const NEW_PAGE_IDS = [524, 525];
// 财务组基础权限:block(518) + 所有web_pages(519,520,521,524,525) + 只读API(522,508)
const FINANCE_PERMISSIONS = [518, 519, 520, 521, 524, 525, 522, 508];
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { sequelize } = queryInterface;
// ── 1. 创建财务组角色(如果不存在)──
await sequelize.query(`
INSERT IGNORE INTO wms_role (role_code, role_name, description, role_type, scope, is_system, status, pid, created_by, permissions, created_at, updated_at)
VALUES ('finance', '财务组', '售后模块财务审核角色', 1, 1, 1, 1, 8, 1, ?, NOW(), NOW())
`, {
replacements: [JSON.stringify(FINANCE_PERMISSIONS)],
});
// ── 2. 为已有角色追加页面权限 ──
const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021'];
for (const roleCode of targetRoleCodes) {
for (const permId of NEW_PAGE_IDS) {
// 仅当该角色的 permissions 数组中不包含此权限ID时才追加
// JSON_CONTAINS 检查是否已存在
// 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST
// 安全守卫:permissions 必须是合法 JSON 数组(以 [ 开头且非 NULL),
// 避免在非法 JSON(如旧版范围格式 [4-121])或 NULL 上执行 JSON_ARRAY_APPEND 导致权限被清空。
await sequelize.query(
`UPDATE wms_role
SET permissions = JSON_ARRAY_APPEND(CAST(permissions AS JSON), '$', CAST(? AS UNSIGNED)),
updated_at = NOW()
WHERE role_code = ?
AND permissions IS NOT NULL
AND permissions != ''
AND permissions != '*'
AND JSON_VALID(permissions) = 1
AND LEFT(permissions, 1) = '['
AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 0`,
{ replacements: [permId, roleCode, String(permId)] }
);
}
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
const { sequelize } = queryInterface;
// ── 1. 移除财务组角色 ──
await sequelize.query(
"DELETE FROM wms_role WHERE role_code = 'finance'"
);
// ── 2. 从各角色移除页面权限 ──
const targetRoleCodes = ['2', '05', '04', 'warehouse', 'warehouse_role', '03', '021'];
for (const roleCode of targetRoleCodes) {
for (const permId of NEW_PAGE_IDS) {
// 从 JSON 数组中移除指定值(MySQL 5.7+ 无直接 JSON_REMOVE_BY_VALUE,用 JSON_SEARCH)
// 注意:permissions 列为 LONGTEXT,JSON 函数需显式 CAST
// 安全守卫:同 up(),防止在非法 JSON 上操作
await sequelize.query(
`UPDATE wms_role
SET permissions = JSON_REMOVE(
CAST(permissions AS JSON),
REPLACE(JSON_UNQUOTE(JSON_SEARCH(CAST(permissions AS JSON), 'one', CAST(? AS CHAR), NULL, '$')), '', '')
),
updated_at = NOW()
WHERE role_code = ?
AND permissions IS NOT NULL
AND permissions != ''
AND permissions != '*'
AND JSON_VALID(permissions) = 1
AND LEFT(permissions, 1) = '['
AND JSON_CONTAINS(CAST(permissions AS JSON), CAST(? AS JSON), '$') = 1`,
{ replacements: [permId, roleCode, String(permId)] }
);
}
}
},
};

View File

@ -0,0 +1,27 @@
'use strict';
const TABLE_NAME = 'wms_after_sale_detail';
module.exports = {
up: async queryInterface => {
// 将 step_status 从 TINYINT 改为 VARCHAR(20),与 wms_after_sale.status 枚举保持一致
// 使用原生 SQL 一步完成:改类型 + 更新已有数据为 processing
await queryInterface.sequelize.query(
`ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status VARCHAR(20) NOT NULL DEFAULT 'processing' COMMENT '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled'`
);
// 已有数据(原 TINYINT 值)统一回填为 processing
await queryInterface.sequelize.query(
`UPDATE \`${TABLE_NAME}\` SET step_status = 'processing'`
);
},
down: async queryInterface => {
// 回退:先更新数据,再改回 TINYINT
await queryInterface.sequelize.query(
`UPDATE \`${TABLE_NAME}\` SET step_status = '2'`
);
await queryInterface.sequelize.query(
`ALTER TABLE \`${TABLE_NAME}\` MODIFY COLUMN step_status TINYINT(3) UNSIGNED NOT NULL DEFAULT 2 COMMENT '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过'`
);
},
};

View File

@ -0,0 +1,17 @@
'use strict';
const TABLE_NAME = 'wms_after_sale';
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(
`ALTER TABLE \`${TABLE_NAME}\` ADD COLUMN followup_at DATETIME NULL DEFAULT NULL COMMENT '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进' AFTER resolved_at`
);
},
down: async queryInterface => {
await queryInterface.sequelize.query(
`ALTER TABLE \`${TABLE_NAME}\` DROP COLUMN followup_at`
);
},
};

View File

@ -0,0 +1,20 @@
'use strict';
const TABLE_NAME = 'wms_inbox_group';
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.ext_data) return;
await queryInterface.addColumn(TABLE_NAME, 'ext_data', {
type: Sequelize.JSON,
allowNull: true,
comment: '群扩展数据(IM平台信息等)',
});
},
down: async queryInterface => {
await queryInterface.removeColumn(TABLE_NAME, 'ext_data');
},
};

View File

@ -0,0 +1,16 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('wms_after_sale', 'order_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入',
after: 'waybill_no',
});
},
async down(queryInterface) {
await queryInterface.removeColumn('wms_after_sale', 'order_id');
},
};

View File

@ -1,4 +1,99 @@
[
{
"version": "2026.08.12-confirmIntercept-doc",
"date": "2026-08-12",
"type": "updated",
"summary": "order.recheckOrder.confirmIntercept 文档描述补全:补充释放储位分配、释放订单锁等副作用说明,明确各副作用失败不阻断主流程的容错语义",
"methods": [
"order.recheckOrder.confirmIntercept"
],
"notes": [
"description 补充:拦截成功后会释放储位分配(cancelAllocateStorage)与订单锁(lock_status=none)",
"description 补充:储位释放、锁释放、日志写入失败均不影响主流程(try/catch 容错)",
"仅文档变更,不修改业务代码"
],
"module": "order"
},
{
"version": "2026.08.12-interceptScan",
"date": "2026-08-12",
"type": "added",
"summary": "order.recheckOrder.interceptScan 新增拦截扫描接口:通过运单号查找运单,标记退回+拦截(is_back='Y', is_intercept='Y');运单记录不存在时自动创建补充;处理关联售后工单(写入「库内拦截成功」并完结);订单级拦截覆盖所有面单含子面单(与 confirmIntercept 一致)",
"methods": [
"order.recheckOrder.interceptScan"
],
"notes": [
"入参:waybill_code(string, required),运单号",
"运单记录不存在时自动创建(INSERT wms_order_express),而非抛 404,确保缺失快递被补充",
"同时设置 is_back='Y' 和 is_intercept='Y'",
"查 wms_after_sale 表(未完结工单),命中则调用 handleWorkOrder 写入「库内拦截成功」步骤并置 status=completed;工单处理失败不阻断主流程",
"订单拦截与 confirmIntercept 一致:只要有 order_id 即更新 wms_order_delivery.intercept_status = intercepted_at_warehouse,并释放储位分配与订单锁,写入 ORDER_INTERCEPT_CONFIRM 操作日志;不再区分 business_key,子面单同样会触发订单级拦截",
"免权限/免日志/免鉴权(与 confirmIntercept 同级)",
"代码变更:recheckOrder.js 构造函数 + interceptScan 方法(~180行);methods/system.json 新增 API 文档"
],
"module": "order"
},
{
"version": "2026.08.10-storageTransaction-keyword",
"date": "2026-08-10",
"type": "updated",
"summary": "storage.transaction.list 新增 keyword 快捷搜索参数,支持按 item_code(商品编码) 和 barcode(条码) 模糊匹配,内部解析为 stock_id 列表后以 IN 条件合并到查询中",
"methods": [
"storage.transaction.list"
],
"notes": [
"新增 keyword 参数(string, optional),搜索范围为 stock_warehouse.item_code + stock_barcodes.barcode",
"keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 的 keyword 解析逻辑一致",
"keyword 可与 where 条件叠加使用(交集),无匹配结果时直接返回空列表",
"代码变更:stock_transaction.js list() 增加 keyword 参数并在 baseWhere 中注入 stock_id IN 条件;systemMethods/storage/transaction.js 透传 keyword"
],
"module": "storage"
},
{
"version": "2026.08.10-stockTransaction-keyword-doc",
"date": "2026-08-10",
"type": "updated",
"summary": "stock.transaction.list 补全 keyword 快捷搜索参数文档。代码层已支持 keyword(通过 queryList → _resolveKeywordToStockIds),本次仅补文档",
"methods": [
"stock.transaction.list"
],
"notes": [
"新增 where.keyword 参数文档(string, optional),搜索范围为 stock_warehouse.item_code/item_name/goods_code + stock_barcodes.barcode + SKU ID",
"keyword 解析复用已有 _resolveKeywordToStockIds 方法,与 stock.report.search 逻辑一致",
"keyword 与 stock_ids 互斥(keyword 优先),无匹配结果时返回空列表",
"仅文档变更,不修改业务代码"
],
"module": "stock"
},
{
"version": "2026.08.09-afterSale-doc",
"date": "2026-08-09",
"type": "updated",
"summary": "补全 afterSale 组全部 11 个 method 的文档:workList/auditList/detail/create/transfer/handleWorkOrder/registerClaim/export/exportTaskProgress/workCount 的 params 与 response 补全 description,移除 create 中冗余 warehouse_id 参数(后端自动注入),明确各枚举值、关联表、业务语义。",
"methods": [
"afterSale.workList",
"afterSale.auditList",
"afterSale.detail",
"afterSale.create",
"afterSale.transfer",
"afterSale.handleWorkOrder",
"afterSale.registerClaim",
"afterSale.export",
"afterSale.exportTaskProgress",
"afterSale.workCount"
],
"notes": [
"afterSale.create:移除 warehouse_id 参数(后端从 ctx.user.store_id 自动注入),补全所有 12 个参数的 description(含 type/sub_type 枚举值),response 新增 status 和 role_group 字段。",
"afterSale.transfer:补全 id/role_group/remark 的 description,response 新增 role_group 字段。",
"afterSale.handleWorkOrder:补全 action/status/attachment_ids 的 description,明确 action 示例和 status 枚举。",
"afterSale.registerClaim:补全 10 个参数的 description,明确 claim_status/carrier_claim_status 枚举值(pending/reviewing/approved/paid/monthly/rejected)。",
"afterSale.workList/auditList:补全 pagination/where/sort 与 response 的 description。",
"afterSale.export/exportTaskProgress:补全参数和响应的 description,明确 task_id 用途。",
"afterSale.workCount:已有完整 description,本次未修改。",
"仅文档变更,不修改任何业务代码或接口语义。"
],
"module": "afterSale"
},
{
"version": "2026.08.07-stockout-express",
"date": "2026-08-07",
@ -5415,5 +5510,248 @@
"apiApp.update: sign_method 字段改为不可修改,传入即报错",
"apiApp.list / apiApp.detail: sign_method 响应描述更新为「当前仅支持 md5」"
]
},
{
"version": "2026.08.10-afterSale-handleWorkOrder-remove-action",
"date": "2026-08-10",
"type": "changed",
"summary": "afterSale.handleWorkOrder 移除 action 参数:action 不再由前端传入,改为服务端固定写入\"处理工单\";处理说明统一使用 remark 字段。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"移除 action 参数(原为必填 string,前端传入操作动作描述),前端不再需要也不接受此参数。",
"步骤记录的 action 字段由服务端在 systems/afterSale.js handleWorkOrder 中硬编码为\"处理工单\"。",
"处理说明统一使用 remark 字段承载。",
"代码变更:systemMethods/afterSale.js handleWorkOrder 移除 action 解构与必填校验;systems/afterSale.js handleWorkOrder 移除 message 参数,addStep action 固定为\"处理工单\"。"
],
"module": "afterSale"
},
{
"version": "2026.08.10-afterSale-handleWorkOrder-status-whitelist",
"date": "2026-08-10",
"type": "changed",
"summary": "afterSale.handleWorkOrder 新增 status 枚举白名单校验:status 必须与 wms_after_sale 主表 AFTER_SALE_STATUS 枚举一致(pending/processing/completed/closed/cancelled),补全 cancelled 枚举值文档。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"status 参数新增枚举白名单校验:从 AfterSale.AFTER_SALE_STATUS 取 key 列表,不在白名单内返回 400。",
"文档 status 枚举值补全 cancelled,与主表模型保持一致(pending | processing | completed | closed | cancelled)。",
"校验同时在 systemMethods/afterSale.js(方法层)和 systems/afterSale.js(业务层)两层生效。",
"仅代码校验增强 + 文档修正,不改变业务语义。"
],
"module": "afterSale"
},
{
"version": "2026.08.10-afterSale-handleWorkOrder-status-default-processing",
"date": "2026-08-10",
"type": "changed",
"summary": "afterSale.handleWorkOrder status 参数改为容错模式:不填或填错时默认 processing(处理中),不再返回 400 错误。status 始终写入主表。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"status 参数行为变更:原来不传时保持当前状态(有 if 判断),现在不填或填错默认 processing,始终写入主表。",
"校验方式从白名单拒绝改为容错兜底:safeStatus = (targetStatus 合法) ? targetStatus : 'processing'。",
"updateFields.status 从条件写入改为始终写入 safeStatus。",
"role_group 回退判断同步从 targetStatus 改为 safeStatus。",
"代码变更:systemMethods/afterSale.js + systems/afterSale.js 两层均改为容错逻辑。"
],
"module": "afterSale"
},
{
"version": "2026.08.10-afterSale-handleWorkOrder-exclude-pending",
"date": "2026-08-10",
"type": "changed",
"summary": "afterSale.handleWorkOrder status 白名单排除 pending:pending 是创建默认值(表示尚未处理),处理工单时不允许回退到此状态。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"handleWorkOrder 允许的 status 从全部 AFTER_SALE_STATUS 中排除 pending,剩余:processing | completed | closed | cancelled。",
"若前端传 status=pending 视为填错,容错兜底为 processing。",
"代码变更:两处 ALLOWED_STATUSES 增加 .filter(s => s !== 'pending')。"
],
"module": "afterSale"
},
{
"version": "2026.08.10-afterSale-step-status-align-main-table",
"date": "2026-08-10",
"type": "changed",
"summary": "wms_after_sale_detail.step_status 改为与 wms_after_sale.status 完全一致:字段类型从 TINYINT 改为 VARCHAR(20),每次写入步骤时记录主表当前 status 快照。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"DB 迁移:20260810140000-alter-wms-after-sale-detail-step-status-to-varchar.js — step_status 从 TINYINT UNSIGNED 改为 STRING(20),已有数据回填 processing。",
"Model:after_sale_detail.js 移除 TINYINT 引用,step_status 改为 STRING(20),STEP_STATUS 枚举对齐主表 AFTER_SALE_STATUS。",
"addStep 默认值从 2 改为 'processing'。",
"transfer:step_status 取 update() 返回的 updated.status。",
"handleWorkOrder:step_status 取 safeStatus(与写入主表的 status 完全一致)。",
"registerClaim:step_status 取 afterSale.status(主表当前状态)。"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-add-waiting-status",
"date": "2026-08-11",
"type": "added",
"summary": "新增 waiting(等待外部处理)状态:用于内部处理完成后等待外部第三方(快递、客户、平台)响应的场景。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"Model:after_sale.js AFTER_SALE_STATUS 新增 waiting: '等待外部处理'。",
"Model:after_sale_detail.js STEP_STATUS 同步新增 waiting。",
"handleWorkOrder 白名单自动包含 waiting(从 AFTER_SALE_STATUS 派生,仅排除 pending)。",
"状态流转:processing → waiting → processing/completed。",
"设计文档同步更新 ER 图、状态流转图、枚举表。"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-rename-pending-feedback",
"date": "2026-08-11",
"type": "changed",
"summary": "waiting 重命名为 pending_feedback(等待外部反馈):语义更精确——内部已处理完并将信息发给外部,等待反馈后再决定是否继续处理,等待期间不需要内部介入。",
"methods": [
"afterSale.handleWorkOrder"
],
"notes": [
"Model/DB/文档中 waiting 全部替换为 pending_feedback",
"workList/workCount 排除列表新增 pending_feedback(等待反馈期间不需要内部处理)",
"典型场景:客服收到拦截工单 → 发信息给运方 → 设为 pending_feedback 等待运方反馈 → 收到反馈后回到 processing 通知客户"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-batchSetPendingFeedback",
"date": "2026-08-11",
"type": "added",
"summary": "新增 afterSale.batchSetPendingFeedback 批量设为待反馈接口:传入 ids 列表,按仓库 policy_config.after_sale_followup_hours 配置自动计算 followup_at,事务内批量更新状态并写入步骤记录。",
"methods": [
"afterSale.batchSetPendingFeedback"
],
"notes": [
"新增 method:afterSale.batchSetPendingFeedback,入参 ids(number[])和 remark(string, optional)",
"业务层 systems/afterSale.js 新增 batchSetPendingFeedback:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status=pending_feedback + followup_at=NOW()+INTERVAL hours HOUR + 步骤记录",
"方法层 systemMethods/afterSale.js 新增 batchSetPendingFeedback:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行",
"followup_at 时长复用现有 _resolveFollowupHours 三级查找:仓库 policy_config → 内置 DEFAULTS 映射 → 兜底 24h",
"终态工单(completed/closed/cancelled)不可设为待反馈,跨仓库工单被拒绝,均返回在 failed 列表中",
"已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-batchClose",
"date": "2026-08-11",
"type": "added",
"summary": "新增 afterSale.batchClose 批量完结/关闭接口:传入 ids + status(completed|closed),事务内批量更新状态、写入步骤记录,completed 时自动写入 resolved_at 并清除 followup_at。",
"methods": [
"afterSale.batchClose"
],
"notes": [
"新增 method:afterSale.batchClose,入参 ids(number[])、status(completed|closed)、resolution(string, optional)、remark(string, optional)",
"业务层 systems/afterSale.js 新增 batchClose:预校验 ids 有效性/终态/跨仓库,事务内逐条更新 status + resolved_at + followup_at 清除 + 步骤记录",
"方法层 systemMethods/afterSale.js 新增 batchClose:从 ctx.user 提取 operator 信息和 warehouseId,委托 systems 层执行",
"终态工单(completed/closed/cancelled)不可重复完结/关闭,跨仓库工单被拒绝,均返回在 failed 列表中",
"已在 _noNeedRight 和 _noNeedAuth 中注册,写入操作会记录日志"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-detail-enrich",
"date": "2026-08-11",
"type": "enhanced",
"summary": "enhance: afterSale.detail 响应新增 related 字段,自动补充关联订单详情(收件人/发件人/商品明细/打包视频)和货主合约备注(store_remask)。",
"methods": [
"afterSale.detail"
],
"notes": [
"响应新增 related 对象:含 related.order(订单详情)和 related.store_contract(货主合约备注),仅在售后单有关联单据时有值",
"related.order.recipient:从 wms_order_delivery 提取收件人姓名/电话/手机/邮箱/省市区/详细地址",
"related.order.sender:从货主 store.subject_config 提取发件人信息(sender_name/sender_tel/地址)",
"related.order.current_table:根据 dispatch_status/outbound_status/status 判断订单当前所在表(main/dispatch/history)",
"related.order.items:从 order_delivery.items JSON 字段解析商品明细数组",
"related.order.pack_videos:通过 PackTask → PackTaskVideo 关联查询打包视频列表(含 video_url/camera_id)",
"related.store_contract:从 wms_store_warehouse 查询 store_remask(商家备注)/warehouse_remask(仓库备注)/使用状态",
"所有关联查询使用 try-catch 兜底,查询失败时仅打 warn 日志,不影响主流程",
"systems/afterSale.js 新增 _enrichAfterSaleDetail / _resolveOrderDetail / _resolveStoreContractNote 三个私有方法"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-detail-waybill",
"date": "2026-08-11",
"type": "enhanced",
"summary": "enhance: afterSale.detail 响应 related 新增 waybill 字段,自动补充运单详情(快递公司名称 + 使用的物流接口)。",
"methods": [
"afterSale.detail"
],
"notes": [
"响应 related 新增 related.waybill 字段(waybill_id 不为空时自动返回)",
"related.waybill.logistics_name:快递公司名称(如 圆通/中通/顺丰),来源 wms_order_express.logistics_name",
"related.waybill.logistics_interface_name:使用的物流接口名称,来源 wms_order_express.logistics_interface_name",
"related.waybill.logistics_code:物流编码,来源 wms_order_express.logistics_code",
"related.waybill 同时返回 waybill_code/status/is_back/is_intercept/create_at 等基础字段",
"systems/afterSale.js 新增 _resolveWaybillDetail 私有方法,查询失败仅打 warn 日志不影响主流程",
"仅文档 + 代码变更,不涉及数据库变更"
],
"module": "afterSale"
},
{
"version": "2026.08.11-afterSale-create-order-id-alias",
"date": "2026-08-11",
"type": "enhanced",
"summary": "enhance: afterSale.create 入参新增 order_id 别名,与 order_delivery_id 等效,优先取 order_delivery_id,为空时回退到 order_id。",
"methods": [
"afterSale.create"
],
"notes": [
"create 方法解构时新增 order_id 别名读取;优先使用 order_delivery_id,为空时取 order_id",
"仅方法层变更(systemMethods/afterSale.js),业务层无改动",
"同时更新 JSDoc 注释,标注 order_delivery_id 兼容别名 order_id"
],
"module": "afterSale"
},
{
"version": "2026.08.11-inbox-group-update-subtype-enum",
"date": "2026-08-11",
"summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述",
"type": "enhance",
"methods": [
"inbox.group.update"
],
"notes": [
"subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源",
"后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中"
]
},
{
"version": "2026.08.11-inbox-group-update-subtype-enum-v2",
"date": "2026-08-11",
"summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述",
"type": "enhance",
"methods": [
"inbox.group.update"
],
"notes": [
"subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源",
"后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中"
]
},
{
"version": "2026.08.11-inbox-group-update-subtype-enum-v3",
"date": "2026-08-11",
"summary": "enhance: inbox.group.update 子类型枚举补全三层约束。groupType=store 可用 after_sales/finance/receiving,groupType=warehouse 新增 production/stockout/all/exception,groupType=express 补全 pickup/after_sales。同步更新 subType description 和 400 错误码描述",
"type": "enhance",
"methods": [
"inbox.group.update"
],
"notes": [
"subType 枚举由 GROUP_TYPES 统一定义,与 AI 函数分组同源",
"后端已新增两层类型校验:subType 必须在对应 groupType 的合法子类型列表中"
]
}
]

File diff suppressed because it is too large Load Diff