Compare commits

...

8 Commits

Author SHA1 Message Date
liufumingren
e61efbb66a feat(inbox): 站内信模块完整实现 - AI智能助手、群管理、消息列表增强、灰度开关
新增功能:
- AI智能助手: DeepSeek多轮推理、函数调用(searchStock/createOrder等)
- silent动作: AI识别无需回复的消息(好的/谢谢/再见)自动跳过回执
- ai_enabled灰度开关: 群级别控制AI启停,支持逐群放量
- 消息列表增强: storeId/groupId/groupName/userName/content/sourceType多条件筛选,时间格式化

代码优化:
- processWithAI: 多轮推理循环(MAX_ROUNDS=5)、对话历史不含[#N]前缀防AI污染
- 回执记录补齐group_id/user_id/group_name/user_name上下文
- 移除未使用的target_channel字段及迁移
- bindCode文档修正: store_warehouse → store

接口文档:
- system.json v0.3.18→0.3.19: 新增aiEnabled参数、消息列表响应扩充
- changes/system.json: 新增bindCode变更记录

杂项:
- store_warehouse.js JSDoc补全
- wave.js waveBatchSource修复
2026-08-06 17:40:36 +08:00
liufumingren
c25dffe884 feat(pick): 先拣后分散单拣货模式支持 - box_no按库位排序并按stock_id分组创建框 - picking_details和scanOrder按stock_id映射box_no - singleFetchByIds波次默认先拣后分模式 2026-08-06 17:38:49 +08:00
liufumingren
11167434ac feat: 仓库设置新增 string_array 类型及自动分配快递排除备注配置
新增字段 auto_allocate_express_exclude_remarks,类型 string_array,默认 [],用于控制订单备注命中关键字时跳过自动分配快递。

修改文件: WAREHOUSE_SETTING_FIELDS 新增元数据定义; Store model DEFAULT_SUBJECT_CONFIG 补默认值 + normalizeSubjectConfig 补校验。
2026-08-05 22:54:25 +08:00
liufumingren
4f41e735a9 feat(pick): wavePickTaskDetail 响应 task 对象新增 wave_no 字段
从 wms_wave_pick_task_wave JOIN wms_wave_batch 查询波次号,查询失败时降级为空字符串。同步更新 methods/system.json 文档与 changes 记录。
2026-08-05 22:52:53 +08:00
liufumingren
7ab67b239a feat: 订单列表新增 stock_query 商品模糊查询条件
所有订单列表接口支持通过 where.stock_query 进行商品维度的模糊筛选:
- 模糊匹配 stock_warehouse 的 item_code(商品编码)、item_name(商品名称)、id(主键)
- 模糊匹配 stock_barcodes 的 barcode(条码)
- 通过 order_items 关联查找匹配的订单 ID 并过滤订单列表

涉及方法:
- base.js: listByModule(覆盖 9 个订单列表入口)
- wave.js: groupOrderFetchList / singleOrderFetchList / waveStrategyFallbackOrderList
- recheckOrder.js: queryRecheckOrderSingleList / queryRecheckOrderGroupList
2026-08-05 22:46:58 +08:00
liufumingren
b00e320262 fix(db): expand item_snapshot_key to VARCHAR(1024) to prevent Data too long error
- wave_batch.item_snapshot_key: 255 -> 1024, full index -> prefix index(191)

- inbox-menu-permissions: INSERT -> INSERT IGNORE for idempotent production rerun
2026-08-05 22:46:22 +08:00
liufumingren
f00b4be1fb 小红书快递取号渠道补充mobile字段入参 2026-08-05 14:55:29 +08:00
liufumingren
807fddccc5 fix(express_platform): package_info 增加 id 作为唯一业务键支持拆单 -- story=sym:package_info 2026-08-04 21:28:26 +08:00
44 changed files with 4546 additions and 915 deletions

View File

@ -1,127 +0,0 @@
'use strict';
const { Controller } = require('egg');
const { toSuccess, toFailure } = require('../lib/api_response');
/**
* 站内信内部管理接口控制器。
* 提供消息列表、详情、对话链、回信、重推、统计等管理功能。
*/
class InboxController extends Controller {
/**
* 获取当前仓库上下文。
* @return {{ warehouseId: number }} 仓库上下文。
*/
getWarehouseContext() {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('缺少仓库信息');
}
return { warehouseId };
}
/**
* 内部管理统一入口,分发到对应 service 方法。
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
*/
async index() {
const { ctx } = this;
try {
const method = String(ctx.request.body && ctx.request.body.method || '').trim();
if (!method || !method.startsWith('inbox.')) {
ctx.status = 400;
ctx.body = toFailure({ message: 'method 参数无效' });
ctx.type = 'application/json';
return;
}
const action = method.replace('inbox.', '');
const data = (ctx.request.body && ctx.request.body.data) || {};
let result;
switch (action) {
case 'list': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.list({
warehouseId,
...data,
});
break;
}
case 'detail': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.detail({
warehouseId,
id: data.id,
});
break;
}
case 'thread': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.thread({
warehouseId,
id: data.id,
});
break;
}
case 'reply': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.reply({
warehouseId,
parentId: data.parentId,
targetChannel: data.targetChannel,
targetUrl: data.targetUrl,
targetType: data.targetType,
refCode: data.refCode,
extData: data.extData,
flags: data.flags,
});
break;
}
case 'retry': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.retry({
warehouseId,
id: data.id,
});
break;
}
case 'stats': {
const { warehouseId } = this.getWarehouseContext();
result = await ctx.service.inbox.index.stats({
warehouseId,
direction: data.direction,
});
break;
}
default:
ctx.status = 400;
ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` });
ctx.type = 'application/json';
return;
}
ctx.status = 200;
ctx.body = toSuccess(result, 'ok');
ctx.type = 'application/json';
} catch (error) {
const message = String(error && error.message || '请求失败');
ctx.status = 500;
ctx.body = toFailure({ message: `站内信错误: ${message}` });
ctx.type = 'application/json';
}
}
}
module.exports = InboxController;

45
app/model/inbox_block.js Normal file
View File

@ -0,0 +1,45 @@
'use strict';
/**
* 站内信屏蔽表 Model。
* 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。
* group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。
*
* @param {Object} app Egg.js Application 实例。
* @return {Object} Sequelize Model 定义。
*/
module.exports = app => {
const { BIGINT, STRING, DATE } = app.Sequelize;
const InboxBlock = app.model.define('inbox_block', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
group_name: {
type: STRING(100),
allowNull: true,
comment: '群名称',
},
user_name: {
type: STRING(100),
allowNull: true,
comment: '用户名称',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
}, {
tableName: 'wms_inbox_block',
timestamps: false,
comment: '站内信屏蔽表',
});
return InboxBlock;
};

106
app/model/inbox_group.js Normal file
View File

@ -0,0 +1,106 @@
'use strict';
/**
* 站内信群表 Model。
* 记录与 WMS 交互的群信息,支持按仓库屏蔽。
*
* @param {Object} app Egg.js Application 实例。
* @return {Object} Sequelize Model 定义。
*/
module.exports = app => {
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
const InboxGroup = app.model.define('inbox_group', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
group_name: {
type: STRING(100),
allowNull: false,
comment: '群名称',
},
group_id: {
type: STRING(100),
allowNull: true,
comment: '外部群ID',
},
warehouse_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '所属仓库ID',
},
store_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '关联货主ID',
},
group_type: {
type: app.Sequelize.ENUM('store', 'warehouse', 'express'),
allowNull: true,
comment: '群类型: store=货主 warehouse=仓库 express=快递',
},
sub_type: {
type: STRING(20),
allowNull: true,
comment: '群子类型: 货主(售后/财务/收货) 仓库(收货/普通/生产) 快递(揽收/售后)',
},
source_type: {
type: STRING(20),
allowNull: true,
comment: '来源类型:im / api / system',
},
source_extra: {
type: STRING(100),
allowNull: true,
comment: '来源附加信息',
},
is_blocked: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否屏蔽 0=否 1=是',
},
ai_enabled: {
type: TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用AI自动回复: 0=关闭 1=开启',
},
express_interfaces: {
type: STRING(500),
allowNull: true,
comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)',
},
system_express_code: {
type: STRING(50),
allowNull: true,
comment: '系统快递编码(仅群类型为 express 时必填)',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
}, {
tableName: 'wms_inbox_group',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
deletedAt: 'deleted_at',
paranoid: true,
comment: '站内信群表',
});
return InboxGroup;
};

View File

@ -77,34 +77,30 @@ module.exports = app => {
},
comment: '目标类型:im / api / webhook',
},
target_channel: {
type: STRING(50),
allowNull: false,
validate: {
notEmpty: {
msg: 'target_channel 不能为空',
},
},
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
},
target_url: {
type: STRING(500),
allowNull: false,
validate: {
notEmpty: {
msg: 'target_url 不能为空',
},
len: {
args: [ 1, 500 ],
msg: 'target_url 长度应在1-500个字符之间',
},
},
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
},
ref_code: {
group_name: {
type: STRING(100),
allowNull: true,
comment: '外部引用编码,推送/回执时原样携带',
comment: '群名称(外部传入)',
},
user_name: {
type: STRING(100),
allowNull: true,
comment: '用户名称(外部传入)',
},
group_id: {
type: STRING(100),
allowNull: true,
comment: '外部群ID',
},
user_id: {
type: STRING(100),
allowNull: true,
comment: '外部用户ID',
},
content: {
type: app.Sequelize.TEXT,
allowNull: true,
comment: '消息正文/摘要,用于列表展示和关键词搜索',
},
ext_data: {
type: JSON_TYPE,
@ -116,6 +112,11 @@ module.exports = app => {
allowNull: true,
comment: '处理标记,外部传入控制WMS处理行为',
},
ai_thoughts: {
type: JSON_TYPE,
allowNull: true,
comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]',
},
push_status: {
type: TINYINT(4),
allowNull: false,

View File

@ -46,6 +46,7 @@ module.exports = app => {
max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT,
max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY,
min_group_order_fetch_quantity: 13,
auto_allocate_express_exclude_remarks: [],
default_express_code: 'STO',
default_platform_code: 'TB',
sender_name: '',
@ -240,6 +241,27 @@ module.exports = app => {
normalized.min_group_order_fetch_quantity = minGroupOrderFetchQuantity;
}
const rawExcludeRemarks = parsed.auto_allocate_express_exclude_remarks;
if (rawExcludeRemarks === undefined || rawExcludeRemarks === null || rawExcludeRemarks === '') {
normalized.auto_allocate_express_exclude_remarks = [];
} else {
if (!Array.isArray(rawExcludeRemarks)) {
throw new Error('subject_config.auto_allocate_express_exclude_remarks 必须是字符串数组');
}
normalized.auto_allocate_express_exclude_remarks = rawExcludeRemarks
.map((item, index) => {
if (item === undefined || item === null || item === '') {
return null;
}
const trimmed = String(item).trim();
if (trimmed === '') {
throw new Error(`subject_config.auto_allocate_express_exclude_remarks[${index}] 不能为空字符串`);
}
return trimmed;
})
.filter(Boolean);
}
normalized.default_express_code = normalizeSubjectConfigText(
parsed.default_express_code,
DEFAULT_SUBJECT_CONFIG.default_express_code

View File

@ -734,7 +734,14 @@ module.exports = app => {
return normalizePolicyConfig(value, options);
};
// 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
/**
* 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
* @param {Object} options 配置项
* @param {number} [options.warehouseId] 仓库ID
* @param {number} [options.storeId] 货主ID
* @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约
* @return {Object} 组装后的 where 条件对象
*/
StoreWarehouse.buildScopedWhere = function(options = {}) {
const {
warehouseId,
@ -757,7 +764,16 @@ module.exports = app => {
return where;
};
// 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
/**
* 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
* @param {Object} options 配置项
* @param {number} [options.warehouseId] 仓库ID
* @param {number} [options.storeId] 货主ID
* @param {boolean} [options.required=false] 是否使用 INNER JOIN
* @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约
* @param {Array<string>} [options.attributes] 需要查询的字段
* @return {Object} Sequelize include 对象
*/
StoreWarehouse.buildStoreStockInclude = function(options = {}) {
const {
warehouseId,

View File

@ -141,9 +141,9 @@ module.exports = app => {
comment: '快递名称(区分快递时参与匹配)',
},
item_snapshot_key: {
type: STRING(255),
type: STRING(1024),
allowNull: true,
comment: '结构快照键',
comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)',
},
}, {
tableName: 'wms_wave_batch',
@ -172,7 +172,7 @@ module.exports = app => {
},
{
name: 'idx_wave_snapshot_key',
fields: [ 'item_snapshot_key' ],
fields: [{ name: 'item_snapshot_key', length: 191 }],
},
{
name: 'idx_wave_item_machine_prefix',

View File

@ -67,7 +67,4 @@ module.exports = app => {
router.get('/testSendData', controller.home.testSendData);
// IM交互入口
router.post('/im', controller.im.index);
// 站内信内部管理接口
router.post('/inbox', controller.inbox.index);
};

View File

@ -1,118 +0,0 @@
'use strict';
const Service = require('egg').Service;
const apiSignLib = require('../../../lib/api_sign');
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时
/**
* 统一出站基类,所有渠道 dispatch 继承此类。
* 统一处理:查密钥、签名、发 HTTP。
* 子类只需实现 push(record) 方法,关注消息格式转换。
*/
class OutboundBase extends Service {
/**
* 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。
*/
async getApiApp(warehouseId) {
const { ctx } = this;
try {
// 通过仓库ID查找该仓库的 warehouse 类型 ApiApp
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
raw: true,
});
if (!apiApp || !apiApp.self_app_secret) {
return null;
}
return {
appKey: apiApp.self_app_key,
selfAppSecret: apiApp.self_app_secret,
warehouseId: Number(apiApp.warehouse_id),
};
} catch (error) {
ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`);
return null;
}
}
/**
* 生成 MD5 签名,返回带签名后的完整 URL。
* @param {string} url 原始目标URL。
* @param {*} body 请求体。
* @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。
* @return {string} 带签名的完整URL。
*/
signRequest(url, body, secret) {
const timestamp = Math.floor(Date.now() / 1000);
const query = {
app_key: secret.appKey,
timestamp,
};
const { sign } = apiSignLib.signRequest({
query,
body,
selfAppSecret: secret.selfAppSecret,
});
const separator = url.includes('?') ? '&' : '?';
return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}&timestamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
}
/**
* 统一 HTTP POST 发送。
* @param {string} url 目标URL。
* @param {*} body 请求体。
* @param {Object} [options] 额外选项。
* @param {Object} [options.headers] 自定义请求头。
* @return {Promise<{status: number, data: *}>} 响应结果。
*/
async post(url, body, options = {}) {
const { ctx } = this;
const headers = {
'Content-Type': 'application/json',
...(options.headers || {}),
};
try {
const response = await ctx.curl(url, {
method: 'POST',
dataType: 'json',
contentType: 'json',
data: body,
headers,
timeout: DISPATCH_TIMEOUT_MS,
});
return {
status: response.status,
data: response.data,
};
} catch (error) {
throw new Error(`HTTP 推送失败: ${error.message}`);
}
}
/**
* 子类必须实现的推送方法。
* @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。
* @throws {Error} 子类未实现时抛出。
*/
async push(record) {
const id = record && record.id;
throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`);
}
}
module.exports = OutboundBase;

View File

@ -1,35 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 钉钉 Bot 渠道出站实现。
* 推送 Markdown 消息到钉钉机器人 webhook。
*/
class DingtalkDispatch extends OutboundBase {
/**
* 通过钉钉 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const title = extData.title || '新消息通知';
const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
const body = {
msgtype: 'markdown',
markdown: {
title,
text: typeof text === 'string' ? text : JSON.stringify(text),
},
};
ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = DingtalkDispatch;

View File

@ -1,60 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 飞书 Bot 渠道出站实现。
* 推送交互式卡片消息到飞书机器人 webhook。
*/
class FeishuDispatch extends OutboundBase {
/**
* 通过飞书 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const title = extData.title || '新消息通知';
const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
const body = {
msg_type: 'interactive',
card: {
header: {
title: {
tag: 'plain_text',
content: title,
},
},
elements: [
{
tag: 'div',
text: {
tag: 'lark_md',
content: typeof content === 'string' ? content : JSON.stringify(content),
},
},
{
tag: 'hr',
},
{
tag: 'note',
elements: [
{
tag: 'plain_text',
content: `编号: ${record.ref_code || record.ext_id}`,
},
],
},
],
},
};
ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = FeishuDispatch;

View File

@ -1,44 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* Webhook 渠道出站实现。
* 直接 HTTP POST 推送 JSON 到目标 webhook URL。
*/
class WebhookDispatch extends OutboundBase {
/**
* 通过 webhook 渠道推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const body = {
ref_code: record.ref_code,
ext_data: record.ext_data,
message_id: record.ext_id,
direction: record.direction,
source_type: record.source_type,
created_at: record.created_at,
};
let targetUrl = record.target_url;
// API 类型需要签名
if (record.target_type === 'api') {
const apiApp = await this.getApiApp(record.warehouse_id);
if (apiApp) {
targetUrl = this.signRequest(targetUrl, body, apiApp);
} else {
ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`);
}
}
ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`);
return await this.post(targetUrl, body);
}
}
module.exports = WebhookDispatch;

View File

@ -1,33 +0,0 @@
'use strict';
const OutboundBase = require('./base');
/**
* 企微 Bot 渠道出站实现。
* 推送 Markdown 消息到企业微信机器人 webhook。
*/
class WecomDispatch extends OutboundBase {
/**
* 通过企微 Bot 推送消息。
* @param {Object} record 消息记录(Sequelize Model 实例)。
* @return {Promise<{status: number, data: *}>} 推送响应。
*/
async push(record) {
const { ctx } = this;
const extData = record.ext_data || {};
const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`;
const body = {
msgtype: 'markdown',
markdown: {
content: typeof content === 'string' ? content : JSON.stringify(content),
},
};
ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
return await this.post(record.target_url, body);
}
}
module.exports = WecomDispatch;

File diff suppressed because it is too large Load Diff

View File

@ -9,13 +9,14 @@ const crypto = require('crypto');
*/
class InboxService extends Service {
/**
* 消息列表(按仓库/状态/方向筛选,分页)。
* 消息列表(按仓库/状态/方向/群筛选,分页)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {string} [params.groupId] 按群ID筛选(精确匹配,用于群消息列表)。
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
* @param {string} [params.targetChannel] 目标渠道筛选。
* @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。
* @param {string} [params.keyword] 关键词搜索(ext_id / content)。
* @param {number} [params.page=1] 页码。
* @param {number} [params.pageSize=20] 每页数量。
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
@ -38,6 +39,12 @@ class InboxService extends Service {
deleted_at: null,
};
// 按群ID筛选
if (params.groupId && typeof params.groupId === 'string') {
const gid = params.groupId.trim();
if (gid) where.group_id = gid;
}
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
@ -49,15 +56,11 @@ class InboxService extends Service {
}
}
if (params.targetChannel && typeof params.targetChannel === 'string') {
where.target_channel = params.targetChannel.trim();
}
if (params.keyword && typeof params.keyword === 'string') {
const keyword = `%${params.keyword.trim()}%`;
where[Op.or] = [
{ ext_id: { [Op.like]: keyword } },
{ content: { [Op.like]: keyword } },
];
}
@ -188,13 +191,11 @@ class InboxService extends Service {
}
/**
* 系统回信:写入 outbound 记录 + 异步推送。
* 系统回信:写入 outbound 记录。
* @param {Object} data 回信数据。
* @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} data.parentId 原消息ID。
* @param {string} data.targetChannel 目标渠道。
* @param {string} data.targetUrl 推送目标URL。
* @param {string} [data.refCode] 引用编码。
* @param {string} [data.content] 消息正文。
* @param {Object} [data.extData] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @return {Promise<Object>} 回信结果。
@ -232,10 +233,7 @@ class InboxService extends Service {
parent_id: parentId,
source_type: 'system',
source_extra: null,
target_type: data.targetType || parent.target_type,
target_channel: data.targetChannel,
target_url: data.targetUrl,
ref_code: data.refCode || parent.ref_code,
content: data.content || null,
ext_data: data.extData || parent.ext_data,
flags: data.flags || {},
});
@ -244,61 +242,7 @@ class InboxService extends Service {
}
/**
* 手动重推。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 重推结果。
*/
async retry(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
if (![ 3 ].includes(record.push_status)) {
throw new Error('仅失败状态的消息可以手动重推');
}
// 重置为待推送状态,由异步推送接管
await record.update({
push_status: 0,
push_started_at: null,
});
// 触发异步推送
setImmediate(() => {
ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => {
ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`);
});
});
return {
ok: true,
id: record.id,
ext_id: record.ext_id,
message: '已触发重推',
};
}
/**
* 推送统计(按仓库 + 状态汇总)。
* 推送统计(按仓库 + 方向汇总)。
* @param {Object} params 统计参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {string} [params.direction] 消息方向筛选。

View File

@ -0,0 +1,335 @@
'use strict';
const Service = require('egg').Service;
/**
* 站内信消息查询/管理服务。
* 提供消息列表、详情、对话链、回复、统计等管理功能。
*/
class InboxMessageService extends Service {
/**
* 消息列表(多条件筛选,分页)。
* 时间字段使用 app.formatDate 统一格式化输出。
*
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。
* @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。
* @param {string} [params.groupName] 群名称模糊搜索。
* @param {string} [params.userName] 用户名模糊搜索。
* @param {string} [params.content] 正文模糊搜索。
* @param {string} [params.sourceType] 来源类型:im / api / system。
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
* @param {number} [params.page=1] 页码。
* @param {number} [params.pageSize=20] 每页数量。
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
*/
async list(params = {}) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const page = Math.max(1, Number(params.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
const where = {
warehouse_id: warehouseId,
deleted_at: null,
};
// 货主ID:支持多选(逗号分隔字符串或数组)
const storeIds = this._normalizeIds(params.storeId);
if (storeIds.length > 0) {
where.store_id = { [Op.in]: storeIds };
}
// 群ID:支持多选(逗号分隔字符串或数组)
const groupIds = this._normalizeStrings(params.groupId);
if (groupIds.length > 0) {
where.group_id = { [Op.in]: groupIds };
}
// 群名称模糊搜索
const groupName = String(params.groupName || '').trim();
if (groupName) {
where.group_name = { [Op.like]: `%${groupName}%` };
}
// 用户名模糊搜索
const userName = String(params.userName || '').trim();
if (userName) {
where.user_name = { [Op.like]: `%${userName}%` };
}
// 正文模糊搜索
const content = String(params.content || '').trim();
if (content) {
where.content = { [Op.like]: `%${content}%` };
}
// 来源类型筛选
const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ];
const sourceType = String(params.sourceType || '').trim();
if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) {
where.source_type = sourceType;
}
// 方向筛选
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
// 推送状态筛选
if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') {
const status = Number(params.pushStatus);
if ([ 0, 1, 2, 3 ].includes(status)) {
where.push_status = status;
}
}
const { count: total, rows } = await InboxMessage.findAndCountAll({
attributes: {
exclude: [ 'ext_data', 'push_response', 'target_channel' ],
},
where,
order: [[ 'created_at', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
});
// 批量查货主名称
const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ];
const storeNameMap = {};
if (storeIdsInResult.length > 0) {
const stores = await ctx.model.Store.findAll({
attributes: [ 'id', 'company_name' ],
where: { id: { [Op.in]: storeIdsInResult } },
raw: true,
});
for (const s of stores) {
storeNameMap[s.id] = s.company_name || '';
}
}
const formatDate = ctx.app.formatDate;
const list = rows.map(row => {
const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row;
return {
...obj,
store_name: storeNameMap[obj.store_id] || '',
created_at: obj.created_at ? formatDate(obj.created_at) : '',
updated_at: obj.updated_at ? formatDate(obj.updated_at) : '',
pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '',
};
});
return {
list,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasPrevious: page > 1,
hasNext: page * pageSize < total,
},
};
}
/**
* 将入参统一为数字ID数组。
* 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。
* @param {string|string[]|number[]|undefined} val 入参。
* @return {number[]} 去重后的数字数组。
*/
_normalizeIds(val) {
if (val === undefined || val === null) return [];
const arr = Array.isArray(val) ? val : String(val).split(',');
return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ];
}
/**
* 将入参统一为字符串数组(去重去空)。
* @param {string|string[]|undefined} val 入参。
* @return {string[]} 去重后的非空字符串数组。
*/
_normalizeStrings(val) {
if (val === undefined || val === null) return [];
const arr = Array.isArray(val) ? val : String(val).split(',');
return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ];
}
/**
* 消息详情(含 push_response)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 消息详情。
*/
async detail(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
return record;
}
/**
* 对话链查询(原消息 + 所有回信),按 parent_id 递归。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Array>} 对话链列表。
*/
async thread(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
// 查找根消息
const root = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId },
});
if (!root) {
throw new Error('消息不存在或无权访问');
}
// 收集对话链:从根到叶
const MAX_THREAD_DEPTH = 50;
const thread = [ root ];
const visited = new Set([ root.id ]);
// 查找所有回信(以 root.id 为 parent_id)
const replies = await InboxMessage.findAll({
where: {
warehouse_id: warehouseId,
parent_id: root.id,
deleted_at: null,
},
order: [[ 'created_at', 'ASC' ]],
});
for (const reply of replies) {
if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) {
visited.add(reply.id);
thread.push(reply);
}
}
// 如果当前消息不是根(有 parent_id),也向上查找原消息
if (root.parent_id) {
const parent = await InboxMessage.findOne({
where: {
id: root.parent_id,
warehouse_id: warehouseId,
deleted_at: null,
},
});
if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) {
visited.add(parent.id);
thread.unshift(parent);
}
}
return thread;
}
/**
* 推送统计(按仓库 + 方向汇总)。
* @param {Object} params 统计参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @return {Promise<Object>} 统计结果。
*/
async stats(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const where = {
warehouse_id: warehouseId,
};
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
// 按方向统计
const directionStats = await InboxMessage.findAll({
attributes: [
'direction',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'direction' ],
raw: true,
});
// 按推送状态统计
const statusStats = await InboxMessage.findAll({
attributes: [
'push_status',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'push_status' ],
raw: true,
});
// 最近24小时统计
const recentWhere = {
...where,
created_at: {
[Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
},
};
const recentCount = await InboxMessage.count({ where: recentWhere });
return {
total_by_direction: directionStats,
total_by_status: statusStats,
recent_24h_count: recentCount,
};
}
}
module.exports = InboxMessageService;

View File

@ -0,0 +1,570 @@
'use strict';
const Service = require('egg').Service;
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s
/**
* 站内信内容处理器。
* 负责解析入站消息正文,按 source_type 分流处理,
* 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。
*/
class InboxProcessorService extends Service {
/**
* 处理入站消息内容。
* 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。
*
* @param {Object} data 入站消息数据。
* @param {string} data.content 消息正文。
* @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。
* @param {number} [data.store_id] 货主ID(优先使用显式传入值)。
* @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。
*/
async process(data = {}) {
const { ctx } = this;
const content = String(data.content || '').trim();
if (!content) {
throw new Error('消息正文 content 不能为空');
}
// warehouse_id:优先取显式传入,否则尝试从 content 中解析
let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null;
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext();
}
// store_id:优先取显式传入,否则尝试从 content 中解析
let storeId = data.store_id != null ? Number(data.store_id) : null;
if (!Number.isFinite(storeId) || storeId <= 0) {
storeId = this.extractStoreId(content) || this.getStoreIdFromContext();
}
// 写入 ctx 上下文,供下游使用
if (!ctx.inboxContext) {
ctx.inboxContext = {};
}
ctx.inboxContext.warehouse_id = warehouseId || null;
ctx.inboxContext.store_id = storeId || null;
ctx.inboxContext.group_name = data.group_name || null;
ctx.inboxContext.user_name = data.user_name || null;
ctx.inboxContext.group_id = data.group_id || null;
ctx.inboxContext.user_id = data.user_id || null;
ctx.logger.info(
'[inbox processor] 内容处理完成 ' +
`warehouse_id=${ctx.inboxContext.warehouse_id} ` +
`store_id=${ctx.inboxContext.store_id} ` +
`content_length=${content.length}`
);
return {
warehouse_id: ctx.inboxContext.warehouse_id,
store_id: ctx.inboxContext.store_id,
content,
};
}
/**
* API 来源消息异步回执。
* 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。
* 回执内容为"收到",ext_data 原路带回。
* 异步执行,不阻塞入站响应。
*
* @param {Object} data 入站消息数据。
* @param {number} data.warehouse_id 仓库ID。
* @param {number} [data.store_id] 货主ID。
* @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。
* @param {Object} [data.ext_data] 原始透传数据。
* @param {string} [data.ext_id] 外部消息ID。
* @param {string} [data.content] 消息正文。
* @return {Promise<void>} 无返回值,异常仅记日志不抛出。
*/
async handleApiMessage(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(data.warehouse_id) || 0;
const extId = String(data.ext_id || '');
const parentId = Number(data.parent_id) || null;
try {
// 1. 处理消息正文,挂载上下文
await this.process(data);
// 2. 屏蔽检查
const isBlocked = await this.isBlocked();
if (isBlocked) {
ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`);
return;
}
// 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群
const bindHandled = await this.tryBindGroup(data);
if (bindHandled) return;
// 4. 群未绑定货主则跳过 AI 解析
const storeId = Number(ctx.inboxContext?.store_id || 0);
if (!storeId) {
ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`);
return;
}
// 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文
if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || 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,
});
if (group) {
ctx.inboxContext.group_type = group.group_type || '';
ctx.inboxContext.sub_type = group.sub_type || '';
ctx.inboxContext.ai_enabled = group.ai_enabled;
ctx.logger.info(
`[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}`
);
}
}
} catch (e) {
ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`);
}
}
// 4.2 群未启用AI → 跳过 AI 解析(灰度开关)
if (ctx.inboxContext.ai_enabled === 0) {
ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`);
return;
}
// 5. DeepSeek 两步交互
const aiResult = await ctx.service.inbox.functions.processWithAI({
content: data.content || '',
ext_data: data.ext_data || null,
parentId: data.parent_id || null,
});
// 无回复且无函数调用 → 跳过,节约资源
// AI 显式指示跳过(silent 动作)→ 同上
if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) {
ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`);
return;
}
const replyContent = aiResult.reply || '已处理完成';
ctx.logger.info(
`[inbox processor] AI 处理完成 ext_id=${extId} ` +
`function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}`
);
// 6. 写入 outbound 回执记录
const ackExtId = `sys:ack:${extId}`;
try {
const existAck = await InboxMessage.findOne({
where: { ext_id: ackExtId },
attributes: [ 'id' ],
paranoid: false,
});
if (!existAck) {
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: {},
});
ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`);
}
} catch (writeError) {
ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`);
}
// 7. 查回调地址并发送
const callbackUrl = await this.getApiAppCallbackUrl(warehouseId);
if (!callbackUrl) {
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`);
return;
}
const ackBody = {
content: replyContent,
ext_data: data.ext_data || null,
ext_id: extId || null,
};
ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`);
const response = await ctx.curl(callbackUrl, {
method: 'POST',
dataType: 'json',
contentType: 'json',
data: ackBody,
headers: { 'Content-Type': 'application/json' },
timeout: CALLBACK_TIMEOUT_MS,
});
ctx.logger.info(
`[inbox processor] API 回执完成 ext_id=${extId} ` +
`http_status=${response.status}`
);
} catch (error) {
ctx.logger.error(
`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`
);
}
}
/**
* 尝试识别并执行绑群操作。
* 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。
*
* @param {Object} data 消息数据。
* @return {Promise<boolean>} 是否已处理绑群。
*/
async tryBindGroup(data = {}) {
const { ctx } = this;
const content = String(data.content || '').trim();
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupId = String(ctx.inboxContext?.group_id || '').trim();
const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i);
if (!bindMatch || !groupId || !warehouseId) return false;
const code = bindMatch[1].toUpperCase();
// 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染)
try {
const existingGroup = await ctx.model.InboxGroup.findOne({
attributes: [ 'store_id' ],
where: { group_id: groupId, warehouse_id: warehouseId },
raw: true,
});
if (existingGroup && existingGroup.store_id) {
await this.writeOutboundReply(data, '已在绑定状态,无需重复操作');
return true;
}
} catch (e) {
ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`);
}
const cacheKey = `chat:bind:${warehouseId}:${code}`;
try {
const cacheValue = await ctx.app.getCacheAsync(cacheKey);
if (!cacheValue || !cacheValue.store_id) {
await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成');
return true;
}
let storeName = `货主${cacheValue.store_id}`;
try {
const store = await ctx.model.Store.findOne({
attributes: [ 'store_name' ],
where: { id: cacheValue.store_id },
raw: true,
});
if (store && store.store_name) storeName = store.store_name;
} catch (e) { /* ignore */ }
await ctx.model.InboxGroup.update(
{
store_id: cacheValue.store_id,
group_type: cacheValue.group_type || 'store',
sub_type: cacheValue.sub_type || null,
},
{ where: { group_id: groupId, warehouse_id: warehouseId } }
);
ctx.inboxContext.store_id = cacheValue.store_id;
ctx.inboxContext.group_type = cacheValue.group_type || 'store';
ctx.inboxContext.sub_type = cacheValue.sub_type || null;
await ctx.app.setCacheAsync(cacheKey, null, 0);
ctx.logger.info(
`[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}`
);
await this.writeOutboundReply(data, `绑定「${storeName}」成功`);
// 绑定成功后自动查询面单余额
try {
const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {});
const balanceMsg = balanceResult?.success
? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}`
: `面单余额查询失败:${balanceResult?.error || '未知错误'}`;
// 使用独立 ext_id 避免与绑定成功回执冲突
await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg);
} catch (balanceErr) {
ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`);
}
return true;
} catch (error) {
ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`);
return false;
}
}
/**
* 写入 outbound 回执并发送 HTTP 回调。
* group_id / user_id / group_name / user_name 为强制入参,
* 缺失任一将抛出异常。
*
* @param {Object} data 消息数据。
* @param {string} data.group_id 群ID(必填)。
* @param {string} data.user_id 用户ID(必填)。
* @param {string} data.group_name 群名称(必填)。
* @param {string} data.user_name 用户名称(必填)。
* @param {string} replyContent 回复内容。
* @return {Promise<void>}
*/
async writeOutboundReply(data, replyContent) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(data.warehouse_id || 0);
const extId = String(data.ext_id || '');
const parentId = Number(data.parent_id || 0);
// 强制入参校验
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 || '?'}`
);
}
try {
const ackExtId = `sys:ack:${extId}`;
const existAck = await InboxMessage.findOne({
where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false,
});
if (!existAck) {
await InboxMessage.create({
ext_id: ackExtId, warehouse_id: warehouseId,
store_id: ctx.inboxContext?.store_id || null,
direction: 'outbound', parent_id: parentId || null,
source_type: 'system', source_extra: null,
target_type: 'api',
group_id: groupId,
user_id: userId,
group_name: groupName,
user_name: userName,
content: replyContent,
ext_data: data.ext_data || null, flags: {},
});
}
const callbackUrl = await this.getApiAppCallbackUrl(warehouseId);
if (callbackUrl) {
const curlResult = await ctx.curl(callbackUrl, {
method: 'POST', dataType: 'json', contentType: 'json',
data: {
content: replyContent,
ext_data: data.ext_data || null,
ext_id: extId,
group_id: groupId,
user_id: userId,
group_name: groupName,
user_name: userName,
},
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
});
// HTTP 200 → 更新回执消息推送状态为已送达
if (curlResult && curlResult.status === 200) {
await InboxMessage.update(
{
push_status: 2,
push_response: { http_status: curlResult.status, body: curlResult.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 } }
);
}
}
}
} catch (error) {
ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`);
}
}
/**
* 检查当前消息的群/用户是否在屏蔽列表中。
*
* @return {Promise<boolean>} 是否已屏蔽。
*/
async isBlocked() {
const { ctx } = this;
const app = ctx.app;
const groupName = String(ctx.inboxContext?.group_name || '').trim();
const userName = String(ctx.inboxContext?.user_name || '').trim();
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
if (!groupName && !userName) return false;
try {
// 1. 尝试从缓存读取屏蔽列表
const cacheKey = `inbox:block:${warehouseId}`;
let blockedSet = await app.getCacheAsync(cacheKey);
if (!blockedSet || !(blockedSet instanceof Set)) {
// 2. 缓存未命中,查库并填入缓存
const { InboxBlock } = ctx.model;
const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true });
blockedSet = new Set();
for (const row of rows) {
const g = String(row.group_name || '').trim();
const u = String(row.user_name || '').trim();
if (g && u) blockedSet.add(`${g}:${u}`);
if (g) blockedSet.add(`${g}:*`);
if (u) blockedSet.add(`*:${u}`);
}
// TTL 5 分钟
await app.setCacheAsync(cacheKey, blockedSet, 300);
}
// 3. 检查当前消息是否命中屏蔽规则
if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true;
if (groupName && blockedSet.has(`${groupName}:*`)) return true;
if (userName && blockedSet.has(`*:${userName}`)) return true;
return false;
} catch (error) {
ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`);
return false;
}
}
/**
* 失效屏蔽缓存,在新增屏蔽记录后调用。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async invalidateBlockCache(warehouseId) {
const { ctx } = this;
try {
await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0);
} catch (error) {
ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`);
}
}
/**
* 获取仓库 ApiApp 回调地址。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<string|null>} 回调 URL,未配置时返回 null。
*/
async getApiAppCallbackUrl(warehouseId) {
const { ctx } = this;
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
return null;
}
try {
const apiApp = await ctx.model.ApiApp.findOne({
attributes: [ 'callback_url' ],
where: {
warehouse_id: warehouseId,
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
is_enabled: 1,
},
raw: true,
});
return (apiApp && apiApp.callback_url) || null;
} catch (error) {
ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`);
return null;
}
}
/**
* 尝试从消息正文中提取仓库ID。
* 子类或业务方可覆盖此方法以实现自定义解析逻辑。
*
* @param {string} content 消息正文。
* @return {number|null} 仓库ID,无法解析时返回 null。
*/
extractWarehouseId(content) {
// 默认不解析,由业务方覆盖
void content;
return null;
}
/**
* 尝试从消息正文中提取货主ID。
* 子类或业务方可覆盖此方法以实现自定义解析逻辑。
*
* @param {string} content 消息正文。
* @return {number|null} 货主ID,无法解析时返回 null。
*/
extractStoreId(content) {
// 默认不解析,由业务方覆盖
void content;
return null;
}
/**
* 从 Egg.js 请求上下文中获取仓库ID。
*
* @return {number|null} 仓库ID。
*/
getWarehouseIdFromContext() {
const { ctx } = this;
const user = ctx.user || ctx.state?.user || {};
const warehouseId = Number(user.store_id || user.warehouse_id) || null;
return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null;
}
/**
* 从 Egg.js 请求上下文中获取货主ID。
*
* @return {number|null} 货主ID。
*/
getStoreIdFromContext() {
const { ctx } = this;
const user = ctx.user || ctx.state?.user || {};
const storeId = Number(user.store_id) || null;
return Number.isFinite(storeId) && storeId > 0 ? storeId : null;
}
}
module.exports = InboxProcessorService;

View File

@ -2,157 +2,45 @@
const Service = require('egg').Service;
const { URL } = require('url');
const { networkInterfaces } = require('os');
/** 推<>?body 大小上限<E4B88A>?4KB */
const MAX_PUSH_BODY_SIZE = 64 * 1024;
/** 最大重试次<E8AF95>?*/
const MAX_RETRY_COUNT = 3;
/** 僵尸恢复阈值:5分钟 */
const ZOMBIE_RECOVERY_MINUTES = 5;
/** 消息体大小上限 64KB */
const MAX_BODY_SIZE = 64 * 1024;
/**
* 收集本机所有内<EFBFBD>?IPv4 地址<EFBFBD>?
* @return {string[]} 内网IP地址列表<EFBFBD>?
*/
function getLocalInternalIps() {
const ips = new Set();
const nets = networkInterfaces();
for (const interfaces of Object.values(nets)) {
for (const iface of interfaces) {
if (iface.family === 'IPv4' && !iface.internal) {
ips.add(iface.address);
}
}
}
return Array.from(ips);
}
/** 内网 IP 前缀集合 */
const INTERNAL_IP_PREFIXES = [
'127.',
'10.',
'192.168.',
'0.',
];
/**
* 判断给定 IP 是否属于本机内网IP<EFBFBD>?
* @param {string} ip IP地址<EFBFBD>?
* @return {boolean} 是否为内网IP<EFBFBD>?
*/
function isInternalIp(ip) {
if (!ip || ip === 'localhost') return true;
// 检查已知内网前缀
for (const prefix of INTERNAL_IP_PREFIXES) {
if (ip.startsWith(prefix)) return true;
}
// 检<>?172.16.0.0 ~ 172.31.255.255
const parts = ip.split('.').map(Number);
if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) {
return true;
}
// 检查本机实际内网IP
const localIps = getLocalInternalIps();
if (localIps.includes(ip)) return true;
return false;
}
/**
* 校验 target_url 安全性:仅允<EFBFBD>?https://,禁止内网IP<49>?
* @param {string} urlStr 目标URL<EFBFBD>?
* @throws {Error} URL 不合法时抛出<EFBFBD>?
*/
// eslint-disable-next-line no-unused-vars
function validateTargetUrl(urlStr) {
if (!urlStr || typeof urlStr !== 'string') {
throw new Error('target_url 不能为空');
}
let parsed;
try {
parsed = new URL(urlStr);
} catch (e) {
throw new Error(`target_url 格式不合<E4B88D>? ${urlStr}`);
}
if (parsed.protocol !== 'https:') {
throw new Error('target_url 仅允<E4BB85>?https:// 协议');
}
const hostname = parsed.hostname || '';
if (isInternalIp(hostname)) {
throw new Error('target_url 不允许指向内网地址');
}
}
/**
* 站内信接收服务<EFBFBD>?
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复<EFBFBD>?
* 站内信接收服务。
* 统一处理消息入站:幂等去重、写库。
* 暂不包含出站转发逻辑,纯入库管理。
*/
class InboxReceiverService extends Service {
/**
* 获取支持的目标渠道集合<EFBFBD>?
* @return {Set<string>} 支持的目标渠道<EFBFBD>?
*/
static get SUPPORTED_CHANNELS() {
return new Set([
'webhook',
'wecom',
'dingtalk',
'feishu',
'warehouse_api',
]);
}
/**
* 初始化时执行僵尸恢复<EFBFBD>?
* @param {Object} ctx Egg.js 上下文<EFBFBD>?
*/
constructor(ctx) {
super(ctx);
// 异步执行僵尸恢复,不阻塞服务启动
setImmediate(() => {
this.recoverZombieMessages().catch(err => {
ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`);
});
});
}
/**
* 统一接收入口:幂等去重、写库、异步推送<EFBFBD>?
* @param {Object} data 消息数据<EFBFBD>?
* @param {string} data.ext_id 外部唯一消息主键<EFBFBD>?
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)<EFBFBD>?
* @param {number} [data.store_id] 关联货主ID<EFBFBD>?
* @param {string} [data.direction='inbound'] 消息方向<EFBFBD>?
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)<EFBFBD>?
* @param {string} data.source_type 来源类型:im / api / system<EFBFBD>?
* @param {string} [data.source_extra] 来源附加信息<EFBFBD>?
* @param {string} data.target_type 目标类型:im / api / webhook<EFBFBD>?
* @param {string} data.target_channel 目标渠道<EFBFBD>?
* @param {string} data.target_url 推送目标URL<EFBFBD>?
* @param {string} [data.ref_code] 引用编码<EFBFBD>?
* @param {Object} [data.ext_data] 透传数据<EFBFBD>?
* @param {Object} [data.flags] 处理标记<EFBFBD>?
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果<EFBFBD>?
* 统一接收入口:幂等去重、写库。
* @param {Object} data 消息数据。
* @param {string} data.ext_id 外部唯一消息主键。
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。
* @param {string} [data.direction='inbound'] 消息方向。
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。
* @param {string} data.source_type 来源类型:im / api / system。
* @param {string} [data.source_extra] 来源附加信息。
* @param {string} data.target_type 目标类型:im / api / webhook。
* @param {string} [data.group_name] 群名称(外部传入)。
* @param {string} [data.user_name] 用户名称(外部传入)。
* @param {string} [data.group_id] 外部群ID。
* @param {string} [data.user_id] 外部用户ID。
* @param {string} [data.content] 消息正文/摘要。
* @param {Object} [data.ext_data] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。
*/
async receive(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
// 安全边界:校<EFBFBD>?ext_id 不能为空
// 安全边界:校验 ext_id 不能为空
const extId = String(data.ext_id || '').trim();
if (!extId) {
throw new Error('ext_id 不能为空');
}
// 安全边界:warehouse_id 必须由服务端上下文提<EFBFBD>?
// 安全边界:warehouse_id 必须由服务端上下文提供
const warehouseId = Number(data.warehouse_id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouse_id 无效');
@ -182,19 +70,10 @@ class InboxReceiverService extends Service {
}
}
// 校验 target_channel 是否存在
const targetChannel = String(data.target_channel || '').trim();
if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) {
throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`);
}
// 安全边界:校<EFBC9A>?target_url
// 幂等检查:ext_id 已存在则直接返回
const exist = await InboxMessage.findOne({
where: { ext_id: extId },
attributes: [ 'id', 'ext_id', 'push_status' ],
attributes: [ 'id', 'ext_id' ],
paranoid: false,
});
@ -207,69 +86,92 @@ class InboxReceiverService extends Service {
};
}
// 推<>?body 大小限制(序列化后检查)
const pushBody = {
// 消息体大小限制
const checkBody = {
content: data.content || null,
ext_data: data.ext_data || null,
};
const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8');
if (bodySize > MAX_PUSH_BODY_SIZE) {
throw new Error(`推<EFBFBD>?body 超过 64KB 限制(当<EFBC88>?${Math.round(bodySize / 1024)}KB)`);
const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8');
if (bodySize > MAX_BODY_SIZE) {
throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`);
}
// 写库
// store_id 签约校验,若传入 store_id,必须存在有效合约关系
const storeId = data.store_id ? Number(data.store_id) : null;
if (storeId && Number.isFinite(storeId) && storeId > 0) {
const contract = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
attributes: [ 'id' ],
});
if (!contract) {
throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`);
// 从群绑定查询货主ID(外部不再直接传入 store_id)
let storeId = null;
const extGroupId = String(data.group_id || '').trim();
if (extGroupId && warehouseId) {
try {
const group = await ctx.model.InboxGroup.findOne({
attributes: [ 'store_id' ],
where: { group_id: extGroupId, warehouse_id: warehouseId },
raw: true,
});
if (group && group.store_id) {
storeId = Number(group.store_id);
}
} catch (groupErr) {
ctx.logger.warn(`[inbox] 查找群货主失败: ${groupErr.message}`);
}
}
// 写库(暂不触发异步转发)
const record = await InboxMessage.create({
ext_id: extId,
warehouse_id: warehouseId,
store_id: data.store_id || null,
store_id: storeId || null,
direction,
parent_id: parentId,
source_type: sourceType,
source_extra: data.source_extra || null,
target_type: targetType,
target_channel: targetChannel,
group_name: data.group_name || null,
user_name: data.user_name || null,
group_id: data.group_id || null,
user_id: data.user_id || null,
content: data.content || null,
ext_data: data.ext_data || null,
flags: data.flags || {},
push_status: 0,
});
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
// 异步后台推送(不阻塞响应)
setImmediate(() => {
this.asyncPush(record).catch(err => {
ctx.logger.error(`[inbox] setImmediate 异步推送异<E98081>?ext_id=${extId}: ${err.message}`);
// 异常已由 asyncPush 内部 try/catch,这里作为兜<E4B8BA>?
try {
InboxMessage.update(
{
push_status: 3,
push_response: { error: `setImmediate 异常: ${err.message}` },
pushed_at: new Date(),
},
{ where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } }
);
} catch (updateErr) {
ctx.logger.error(`[inbox] 兜底更新推送状态失<E68081>?ext_id=${extId}: ${updateErr.message}`);
}
// 自动登记群(幂等 upsert)
const groupName = String(data.group_name || '').trim();
if (groupName) {
try {
await ctx.model.InboxGroup.findOrCreate({
where: { group_name: groupName, warehouse_id: warehouseId },
defaults: {
group_id: extGroupId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
},
});
} catch (groupErr) {
ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`);
}
}
// source_type 分流:API 来源异步回执
if (sourceType === 'api') {
setImmediate(() => {
ctx.service.inbox.processor.handleApiMessage({
warehouse_id: warehouseId,
store_id: storeId,
parent_id: record.id,
ext_data: data.ext_data || null,
ext_id: extId,
content: data.content || '',
group_name: data.group_name || null,
user_name: data.user_name || null,
group_id: data.group_id || null,
user_id: data.user_id || null,
}).catch(err => {
ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`);
});
});
});
}
return {
ok: true,
@ -277,133 +179,6 @@ class InboxReceiverService extends Service {
ext_id: extId,
};
}
/**
* 异步推<EFBFBD>?+ 指数退避重试<EFBFBD>?
* @param {Object} record 消息记录(Sequelize Model 实例)<EFBFBD>?
* @param {number} [attempt=0] 当前重试次数<EFBFBD>?
* @return {Promise<void>} 推送结果<EFBFBD>?
*/
async asyncPush(record, attempt = 0) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
try {
// 乐观锁:<E99481>?push_status=0 或(重试<E9878D>?push_status=3)时可取<E58FAF>?
const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ];
const [ updatedCount ] = await InboxMessage.update(
{
push_status: 1,
push_started_at: new Date(),
},
{
where: {
id: record.id,
push_status: { [Op.in]: allowedStatuses },
},
}
);
if (updatedCount === 0) {
ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推<E8BF87>?ext_id=${record.ext_id} id=${record.id}`);
return;
}
// 获取 dispatch 服务
const channel = record.target_channel;
if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) {
throw new Error(`不支持的目标渠道: ${channel}`);
}
// 统一渠道映射:warehouse_api <20>?webhook
const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel;
const dispatchService = ctx.service.inbox.dispatch[dispatchChannel];
if (!dispatchService || typeof dispatchService.push !== 'function') {
throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`);
}
// 执行推<E8A18C>?
const response = await dispatchService.push(record);
// 推送成<E98081>?
await InboxMessage.update(
{
push_status: 2,
push_response: {
http_status: response.status,
body: response.data,
},
pushed_at: new Date(),
},
{ where: { id: record.id, push_status: 1 } }
);
ctx.logger.info(`[inbox] 推送成<E98081>?ext_id=${record.ext_id} channel=${channel}`);
} catch (error) {
const next = attempt + 1;
ctx.logger.warn(`[inbox] 推送失<E98081>?ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
// 更新失败状<E8B4A5>?
await InboxMessage.update(
{
push_status: next >= MAX_RETRY_COUNT ? 3 : 3,
retry_count: next,
push_response: { error: error.message },
...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}),
},
{ where: { id: record.id, push_status: 1 } }
);
// 指数退避重试:30s <20>?60s <20>?120s
if (next < MAX_RETRY_COUNT) {
const delay = 30000 * Math.pow(2, attempt);
ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重<E5908E>?ext_id=${record.ext_id} attempt=${next}`);
setTimeout(() => {
this.asyncPush(record, next).catch(err => {
ctx.logger.error(`[inbox] 重试推送异<E98081>?ext_id=${record.ext_id}: ${err.message}`);
});
}, delay);
} else {
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失<E68081>?ext_id=${record.ext_id}`);
}
}
}
/**
* 僵尸恢复:重置卡<EFBFBD>?推送中"超过5分钟的消息为"待推<EFBFBD>?<EFBFBD>?
* 在服务启动时及定时任务中调用<EFBFBD>?
* @return {Promise<number>} 恢复的消息数量<EFBFBD>?
*/
async recoverZombieMessages() {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000);
const [ updatedCount ] = await InboxMessage.update(
{
push_status: 0,
push_started_at: null,
},
{
where: {
push_status: 1,
push_started_at: {
[Op.lt]: threshold,
},
},
}
);
if (updatedCount > 0) {
ctx.logger.info(`[inbox] 僵尸恢复完成,重<EFBC8C>?${updatedCount} 条消息为待推送`);
}
return updatedCount;
}
}
module.exports = InboxReceiverService;

View File

@ -0,0 +1,189 @@
'use strict';
const MainService = require('../main');
/**
* 站内信系统方法层。
* 提供需要用户权限的内部管理接口。
*/
class InboxSystemService extends MainService {
/**
* 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。
* @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}}
*/
get group() {
return {
list: data => this.groupList(data),
disable: data => this.groupDisable(data),
update: data => this.groupUpdate(data),
messages: data => this.groupMessages(data),
checkAuth: (...args) => this.checkAuth(...args),
};
}
/**
* 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}}
*/
get message() {
const { ctx } = this;
return {
list: data => {
const warehouseId = Number(ctx.user?.store_id || 0);
return ctx.service.inbox.message.list({ warehouseId, ...data });
},
detail: data => {
const warehouseId = Number(ctx.user?.store_id || 0);
return ctx.service.inbox.message.detail({ warehouseId, id: data.id });
},
thread: data => {
const warehouseId = Number(ctx.user?.store_id || 0);
return ctx.service.inbox.message.thread({ warehouseId, id: data.id });
},
stats: data => {
const warehouseId = Number(ctx.user?.store_id || 0);
return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction });
},
checkAuth: (...args) => this.checkAuth(...args),
};
}
/**
* 生成货主绑群码。
* 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。
* warehouseId 从 ctx.user.store_id 自动注入,绑群码缓存 key 为 chat:bind:{warehouseId}:{code}。
*
* @param {Object} data 请求数据。
* @param {number} data.storeId 货主ID。
* @param {string} [data.subType] 群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)。
* @return {Promise<Object>} { code: 绑群码 }。
*/
async bindCode(data = {}) {
const { ctx } = this;
const { storeId, subType } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
return await ctx.service.systems.store.bindCode({
storeId,
warehouseId,
subType,
});
}
/**
* 拉取当前仓库的群列表。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {string} [data.keyword] 群名称模糊搜索。
* @param {number} [data.page] 页码。
* @param {number} [data.pageSize] 每页条数。
* @return {Promise<Object>} { total, list }。
*/
async groupList(data = {}) {
const { ctx } = this;
const { groupType, keyword, page, pageSize } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
return await ctx.service.systems.inbox.group.list({
warehouseId,
groupType,
keyword,
page,
pageSize,
});
}
/**
* 禁用 / 解禁群。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} [data.isBlocked=1] 是否禁用 1=是 0=否。
* @return {Promise<Object>} { message: 操作结果 }。
*/
async groupDisable(data = {}) {
const { ctx } = this;
const { id, isBlocked } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
await ctx.service.systems.inbox.group.disable({
id,
warehouseId,
isBlocked: isBlocked === 0 ? 0 : 1,
});
return { message: isBlocked === 0 ? '群已启用' : '群已禁用' };
}
/**
* 修改群信息。
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {string} [data.groupType] 群类型:store / warehouse / express。
* @param {string} [data.subType] 群子类型。
* @param {number} [data.storeId] 关联货主ID。
* @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。
* @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。
* @return {Promise<Object>} { message: 操作结果 }。
*/
async groupUpdate(data = {}) {
const { ctx } = this;
const {
id, groupType, subType, storeId,
expressInterfaces, systemExpressCode, aiEnabled,
} = data;
const warehouseId = Number(ctx.user?.store_id || 0);
await ctx.service.systems.inbox.group.update({
id,
warehouseId,
groupType,
subType,
storeId,
expressInterfaces,
systemExpressCode,
aiEnabled,
});
return { message: '群信息修改成功' };
}
/**
* 拉取指定群的消息列表。
* warehouseId 从 ctx.user.store_id 自动注入。
*
* @param {Object} data 请求数据。
* @param {string} data.groupId 群ID(必填)。
* @param {string} [data.direction] 消息方向筛选:inbound / outbound。
* @param {string} [data.keyword] 关键词搜索(ext_id / content)。
* @param {number} [data.page] 页码。
* @param {number} [data.pageSize] 每页条数。
* @return {Promise<Object>} { list, pagination }。
*/
async groupMessages(data = {}) {
const { ctx } = this;
const { groupId, direction, keyword, page, pageSize } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
if (!groupId || typeof groupId !== 'string' || !groupId.trim()) {
throw new Error('groupId 不能为空');
}
return await ctx.service.inbox.message.list({
warehouseId,
groupId: groupId.trim(),
direction,
keyword,
page,
pageSize,
});
}
}
module.exports = InboxSystemService;

View File

@ -946,6 +946,34 @@ class OrderBaseService extends MainService {
return { where: normalizedWhere, buyerMessageHas: null };
}
/**
* 提取 stock_query 虚拟筛选条件。
* 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。
* @param {Object} whereInput 标准化后的 where 条件。
* @return {{ where: Object, stockQuery: string }} 清洗后的 where 与 stock_query 值。
*/
extractStockQueryVirtualFilter(whereInput = {}) {
const normalizedWhere = this.isPlainObject(whereInput)
? { ...whereInput }
: {};
const stockQueryCondition = normalizedWhere.stock_query;
delete normalizedWhere.stock_query;
if (!stockQueryCondition) {
return { where: normalizedWhere, stockQuery: '' };
}
const rawValue = this.isPlainObject(stockQueryCondition)
&& Object.prototype.hasOwnProperty.call(stockQueryCondition, 'value')
? stockQueryCondition.value
: stockQueryCondition;
const stockQuery = typeof rawValue === 'string' ? rawValue.trim() : '';
return { where: normalizedWhere, stockQuery };
}
/**
* 构建 buyer_message_has 虚拟字段的 Sequelize where 条件。
* 覆盖三个留言/备注字段:buyer_message、seller_message、remark。
@ -1080,6 +1108,105 @@ class OrderBaseService extends MainService {
.filter(orderId => Number.isFinite(orderId) && orderId > 0)));
}
/**
* 根据 stock_query 模糊查询 stock_warehouse(商品编码、商品名称、主键ID)和 stock_barcodes(条码),
* 找到匹配的 stock_id,再通过 order_items 查找关联的订单 ID。
* 若未匹配到任何 stock 则返回空数组,下游会将订单列表结果置空。
* @param {string} stockQuery 模糊查询关键词。
* @param {string} moduleName 模块名称(用于确定 order_items 表类型)。
* @param {number|string} [warehouseId] 仓库ID。
* @return {Promise<number[]>} 命中的订单ID列表。
*/
async findOrderIdsByStockQuery(stockQuery = '', moduleName = 'order', warehouseId = null) {
const contextWarehouseId = this.getWarehouseId();
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
throw new Error('缺少当前用户仓库上下文 store_id');
}
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
&& String(warehouseId) !== String(contextWarehouseId)) {
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
}
if (!stockQuery || typeof stockQuery !== 'string') {
return [];
}
const trimmedQuery = stockQuery.trim();
if (!trimmedQuery) {
return [];
}
const { Op } = this.app.Sequelize;
const likePattern = `%${trimmedQuery}%`;
// 第一步:从 stock_warehouse 模糊查询 item_code、item_name 和 id
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
const stockIdsFromWarehouse = [];
if (stockWarehouseModel) {
const stockRows = await stockWarehouseModel.findAll({
where: {
warehouse_id: contextWarehouseId,
is_valid: 'Y',
[Op.or]: [
{ item_code: { [Op.like]: likePattern } },
{ item_name: { [Op.like]: likePattern } },
{ id: { [Op.like]: likePattern } },
],
},
attributes: [ 'id' ],
raw: true,
});
for (const row of stockRows) {
stockIdsFromWarehouse.push(Number(row.id));
}
}
// 第二步:从 stock_barcodes 模糊查询 barcode
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
const stockIdsFromBarcodes = [];
if (stockBarcodeModel) {
const barcodeRows = await stockBarcodeModel.findAll({
where: {
warehouse_id: contextWarehouseId,
barcode: { [Op.like]: likePattern },
},
attributes: [ 'stock_id' ],
raw: true,
});
for (const row of barcodeRows) {
stockIdsFromBarcodes.push(Number(row.stock_id));
}
}
// 第三步:合并去重所有匹配的 stock_id
const allStockIds = Array.from(new Set([ ...stockIdsFromWarehouse, ...stockIdsFromBarcodes ]))
.filter(id => Number.isFinite(id) && id > 0);
if (allStockIds.length === 0) {
return [];
}
// 第四步:通过 order_items 查找关联的 order_id
const moduleConfig = this.getModuleConfig(moduleName);
const tableType = moduleConfig.modelType || 'current';
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, contextWarehouseId);
const orderItemRows = await orderItemsModel.findAll({
where: {
stock_id: { [Op.in]: allStockIds },
},
attributes: [ 'order_id' ],
raw: true,
});
return Array.from(new Set(
(Array.isArray(orderItemRows) ? orderItemRows : [])
.map(row => Number(row && row.order_id))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
));
}
/**
* 将命中的订单ID并入 Sequelize where 条件。
* @param {Object} queryWhere 原始 where 条件。
@ -1247,7 +1374,8 @@ class OrderBaseService extends MainService {
});
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(where);
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterBuyerMessage);
const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage);
const mergedWhere = this.mergeWhereObjects(this.getDefaultWhere(moduleName), whereAfterStockQuery);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: {
quickWhere: {
@ -1266,6 +1394,11 @@ class OrderBaseService extends MainService {
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
}
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, moduleName, contextWarehouseId);
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds);
}
const model = await this.getOrderModel(moduleName, contextWarehouseId);
const order = this.buildListOrder(requestData.sort, moduleName);
const offset = (page - 1) * pageSize;

View File

@ -517,11 +517,41 @@ class RecheckOrderService extends OrderBaseService {
// 批量查询包材推荐
const packageMaterialMap = await this.batchQueryPackageMaterialRecommendation(orders, warehouseId);
// 为每个订单附加 items_weight 和包材推荐
// 查询任务框的 stock_id → box_no 映射(用于先拣后分等散单模式)
const taskId = pickerInfo.task_id;
const boxNoByStockId = new Map();
if (taskId > 0) {
const { ctx } = this;
const boxRows = await ctx.model.query(
`SELECT ref_id, box_no
FROM wms_wave_pick_task_box
WHERE task_id = :taskId`,
{
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
}
);
for (const row of (Array.isArray(boxRows) ? boxRows : [])) {
const sid = Number(row.ref_id || 0);
const bno = Number(row.box_no || 0);
if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) {
boxNoByStockId.set(sid, bno);
}
}
}
// 为每个订单附加 items_weight、包材推荐和 stock 中的 box_no
const enrichedOrders = orders.map(order => {
const itemsHash = String(order.items_hash || '').trim();
const enrichedStock = Array.isArray(order.stock)
? order.stock.map(stockItem => ({
...stockItem,
box_no: boxNoByStockId.get(Number(stockItem.stock_id || 0)) || 0,
}))
: [];
return {
...order,
stock: enrichedStock,
items_weight: order.items_weight != null ? Number(order.items_weight) : 0,
suggested_package_material: itemsHash ? (packageMaterialMap.get(itemsHash) || null) : null,
};
@ -3237,6 +3267,29 @@ class RecheckOrderService extends OrderBaseService {
replacements.pickStatus = pickStatus;
}
// stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id
const stockQuery = String(where.stock_query || '').trim();
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId);
if (stockOrderIds.length > 0) {
conditions.push('o.id IN (:stockOrderIds)');
replacements.stockOrderIds = stockOrderIds;
} else {
// 未匹配到任何商品,直接返回空列表
return this.success('ok', {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
});
}
}
const whereClause = conditions.length > 0
? `WHERE ${conditions.join('\n AND ')}`
: '';
@ -3365,6 +3418,29 @@ class RecheckOrderService extends OrderBaseService {
replacements.waveStatus = waveStatus;
}
// stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → order_id 过滤波次
const stockQuery = String(where.stock_query || '').trim();
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId);
if (stockOrderIds.length > 0) {
conditions.push('o.id IN (:stockOrderIds)');
replacements.stockOrderIds = stockOrderIds;
} else {
// 未匹配到任何商品,直接返回空列表
return this.success('ok', {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
});
}
}
const whereClause = conditions.length > 0
? `WHERE ${conditions.join('\n AND ')}`
: '';

View File

@ -2145,6 +2145,7 @@ class WaveService extends OrderBaseService {
const shopName = this.normalizeShopName(requestData.shop_name);
const includeSku = this.normalizeSkuText(requestData.include_sku);
const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false);
const stockQuery = String(requestData.stock_query || '').trim();
const { page, pageSize } = this.normalizePagination(requestData);
const where = {
@ -2164,6 +2165,20 @@ class WaveService extends OrderBaseService {
where.shop_nick = { [Op.like]: `%${shopName}%` };
}
// stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId);
if (stockOrderIds.length > 0) {
where.id = { [Op.in]: stockOrderIds };
} else {
// 未匹配到任何商品,直接返回空列表
return {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
};
}
}
// Phase 1: 主表全量查询,用 items_hash 做分组基准
const rawOrders = await model.findAll({
where,
@ -2383,6 +2398,7 @@ class WaveService extends OrderBaseService {
const shopName = this.normalizeShopName(requestData.shop_name);
const includeSku = this.normalizeSkuText(requestData.include_sku);
const returnOrderIds = this.normalizeBoolean(requestData.return_order_ids, false);
const stockQuery = String(requestData.stock_query || '').trim();
const { page, pageSize } = this.normalizePagination(requestData);
const where = {
@ -2402,6 +2418,20 @@ class WaveService extends OrderBaseService {
where.shop_nick = { [Op.like]: `%${shopName}%` };
}
// stock_query 商品模糊筛选:通过 stock_warehouse / stock_barcodes → order_items → 限定候选订单范围
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId);
if (stockOrderIds.length > 0) {
where.id = { [Op.in]: stockOrderIds };
} else {
// 未匹配到任何商品,直接返回空列表
return {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
};
}
}
// Phase 1: 主表全量查询,用 items_hash 做分组基准
const rawOrders = await model.findAll({
where,
@ -4000,8 +4030,9 @@ class WaveService extends OrderBaseService {
);
const { where: sanitizedWhere, expressNumbers } = this.extractOrderListExpressVirtualFilter(ctxWhere);
const { where: whereAfterBuyerMessage, buyerMessageHas } = this.extractBuyerMessageHasVirtualFilter(sanitizedWhere);
const { where: whereAfterStockQuery, stockQuery } = this.extractStockQueryVirtualFilter(whereAfterBuyerMessage);
const defaultWhere = this.getDefaultWhere('waveStrategyFallbackOrder');
const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterBuyerMessage);
const mergedWhere = this.mergeWhereObjects(defaultWhere, whereAfterStockQuery);
let queryWhere = this.buildWhere(mergedWhere, contextWarehouseId, {
specialFieldMap: { quickWhere: { bucket: 'quick' } },
});
@ -4017,6 +4048,12 @@ class WaveService extends OrderBaseService {
queryWhere = this.appendConditionToWhere(queryWhere, buyerMessageCondition);
}
// 处理 stock_query 虚拟筛选
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'waveStrategyFallbackOrder', contextWarehouseId);
queryWhere = this.appendOrderIdsFilterToWhere(queryWhere, stockOrderIds);
}
// 追加 OR 条件:未匹配策略(wave_scan_result=2) 或 已完全打印被排除(print_status='fin')
const { Sequelize } = this.app;
queryWhere = {
@ -12695,7 +12732,7 @@ class WaveService extends OrderBaseService {
try {
const directFetchResult = await this.executeWaveStrategyDirectFetch({
plan,
waveBatchSource: 1,
waveBatchSource: 0,
});
this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', {

View File

@ -258,46 +258,112 @@ class PickService extends MainService {
);
if (normalizedOrderIds.length > 0) {
// 查询波次索引(wave_index),使 box_no 与 wms_order_wave_index.wave_index 一致
const waveIndexMap = new Map();
try {
const waveIndexRows = await ctx.model.query(
`SELECT order_id, wave_index
FROM wms_order_wave_index
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
AND order_id IN (:orderIds)`,
// 按库位排序并按 stock_id 分组,同 stock_id 的订单共享同一篮号
const stockGroups = await this.resolveLocationSortedOrderIds(
normalizedOrderIds,
warehouseId,
transaction
);
// 写入 wms_wave_pick_task_box:每个 stock_id 一个框,记录 stock_id → box_no 映射
const boxValuesSql = [];
const boxReplacements = {};
let boxNo = 0;
let boxIndex = 0;
for (const group of stockGroups) {
boxNo += 1;
const stockId = group.stock_id > 0 ? group.stock_id : 0;
const boxNoKey = `boxNo${boxIndex}`;
const stockIdKey = `stockId${boxIndex}`;
const boxCodeKey = `boxCode${boxIndex}`;
boxValuesSql.push(`(
:taskId,
NULL,
:${boxCodeKey},
:${boxNoKey},
1,
:${stockIdKey},
NULL,
0,
0,
0,
NULL,
NULL,
NULL,
:warehouseId,
NOW(),
NOW()
)`);
boxReplacements[boxNoKey] = boxNo;
boxReplacements[stockIdKey] = stockId;
boxReplacements[boxCodeKey] = `${taskNo}-S${boxNo}`;
boxIndex += 1;
}
if (boxValuesSql.length > 0) {
await ctx.model.query(
`
INSERT INTO wms_wave_pick_task_box (
task_id,
order_id,
box_code,
box_no,
box_type,
ref_id,
ref_label,
required_qty,
picked_qty,
box_status,
review_result,
review_user_id,
review_time,
warehouse_id,
create_time,
update_time
) VALUES ${boxValuesSql.join(',\n')}
`,
{
replacements: {
taskId,
warehouseId,
waveId,
orderIds: normalizedOrderIds,
...boxReplacements,
},
type: ctx.model.QueryTypes.SELECT,
transaction,
}
);
for (const wr of (Array.isArray(waveIndexRows) ? waveIndexRows : [])) {
const wrOrderId = Number(wr && wr.order_id || 0);
if (wrOrderId > 0) {
waveIndexMap.set(wrOrderId, Number(wr.wave_index || 0));
// 更新任务主表的 box_count
await ctx.model.query(
`UPDATE wms_wave_pick_task
SET box_count = :boxCount,
update_time = NOW()
WHERE id = :taskId`,
{
replacements: { taskId, boxCount: boxValuesSql.length },
transaction,
}
);
}
// 写入 wms_wave_pick_task_order:每个订单写入一次(取该订单所属的最小 box_no)
const orderBoxMap = new Map();
boxNo = 0;
for (const group of stockGroups) {
boxNo += 1;
for (const orderId of group.order_ids) {
if (!orderBoxMap.has(orderId) || orderBoxMap.get(orderId) > boxNo) {
orderBoxMap.set(orderId, boxNo);
}
}
} catch (e) {
ctx.logger.warn('[pick.createWavePickTask] 查询波次索引失败,box_no 将退化为任务内序号', {
error: e && e.message,
warehouseId,
waveId,
});
}
const orderValuesSql = [];
const orderReplacements = {};
normalizedOrderIds.forEach((orderId, index) => {
const orderIdKey = `orderId${index}`;
const orderNoKey = `orderNo${index}`;
const boxNoKey = `boxNo${index}`;
const waveIndex = waveIndexMap.get(orderId);
let paramIndex = 0;
for (const [ orderId, orderBoxNo ] of orderBoxMap) {
const orderIdKey = `orderId${paramIndex}`;
const orderNoKey = `orderNo${paramIndex}`;
const boxNoKey = `oBoxNo${paramIndex}`;
orderValuesSql.push(`(
:taskId,
:waveId,
@ -312,8 +378,9 @@ class PickService extends MainService {
)`);
orderReplacements[orderIdKey] = orderId;
orderReplacements[orderNoKey] = orderNoMap.get(orderId) || '';
orderReplacements[boxNoKey] = Number.isFinite(waveIndex) && waveIndex > 0 ? waveIndex : (index + 1);
});
orderReplacements[boxNoKey] = orderBoxNo;
paramIndex += 1;
}
await ctx.model.query(
`
@ -362,7 +429,7 @@ class PickService extends MainService {
extras: {
message: `订单${orderId}抓取波次成功`,
warehouseId,
externalLogType: 'PDA',
externalLogType: 'API',
},
}));
await operationLogService.createOperationLogs(logPayloads);
@ -384,6 +451,144 @@ class PickService extends MainService {
}
}
/**
* 按库位排序并按 stock_id 分组订单,使 box_no 按拣货路径顺序分配。
*
* 同 stock_id 的订单归入同一组(同一篮号),组间按 pick_sequence ASC 排序。
* 若某订单无拣货数据(未分配储位),排到末尾保持原顺序。
*
* @param {Array<number>} orderIds 订单ID列表。
* @param {number} warehouseId 仓库ID。
* @param {Object} [transaction] Sequelize 事务。
* @return {Promise<Array<{ stock_id: number, order_ids: number[] }>>} 按库位排序后的分组列表。
*/
async resolveLocationSortedOrderIds(orderIds, warehouseId, transaction) {
const { ctx } = this;
const normalizedOrderIds = [ ...new Set((Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (normalizedOrderIds.length === 0) {
return [];
}
if (normalizedOrderIds.length === 1) {
return [{ stock_id: 0, order_ids: normalizedOrderIds }];
}
try {
// 查询拣货明细获取 order_item_id 和 space_id
const pickingRows = await ctx.model.Picking.findAll({
where: {
order_id: { [this.app.Sequelize.Op.in]: normalizedOrderIds },
warehouse_id: warehouseId,
},
attributes: [ 'order_id', 'order_item_id', 'space_id' ],
raw: true,
transaction,
});
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
const orderSpaceMap = new Map();
const orderItemIds = [];
for (const row of normalizedPickingRows) {
const oid = Number(row && row.order_id || 0);
const sid = Number(row && row.space_id || 0);
const oiid = Number(row && row.order_item_id || 0);
if (oid > 0 && !orderSpaceMap.has(oid)) {
orderSpaceMap.set(oid, sid);
}
if (oiid > 0) {
orderItemIds.push(oiid);
}
}
// 查询订单商品明细获取 stock_id,收集每个订单的所有 stock_id
const orderStockIdSet = new Map();
if (orderItemIds.length > 0) {
const factory = ctx.model && ctx.model.OrderItemsFactory;
if (factory && typeof factory.getCurrentModel === 'function') {
const orderItemModel = await factory.getCurrentModel(warehouseId);
if (orderItemModel && typeof orderItemModel.findAll === 'function') {
const itemRows = await orderItemModel.findAll({
where: {
id: { [this.app.Sequelize.Op.in]: [ ...new Set(orderItemIds) ] },
},
attributes: [ 'id', 'order_id', 'stock_id' ],
raw: true,
transaction,
});
for (const row of (Array.isArray(itemRows) ? itemRows : [])) {
const oid = Number(row && row.order_id || 0);
const stockId = Number(row && row.stock_id || 0);
if (oid > 0 && stockId > 0) {
if (!orderStockIdSet.has(oid)) {
orderStockIdSet.set(oid, new Set());
}
orderStockIdSet.get(oid).add(stockId);
}
}
}
}
}
// 按 stock_id 分组:每个 stock_id 一个组,订单可出现在多个组(多商品订单)
const groupMap = new Map();
for (const oid of normalizedOrderIds) {
const stockIds = orderStockIdSet.get(oid);
if (stockIds && stockIds.size > 0) {
for (const stockId of stockIds) {
if (!groupMap.has(stockId)) {
groupMap.set(stockId, { stock_id: stockId, order_ids: [] });
}
groupMap.get(stockId).order_ids.push(oid);
}
} else {
const key = -oid; // 无 stock_id 的订单各自成组
if (!groupMap.has(key)) {
groupMap.set(key, { stock_id: 0, order_ids: [] });
}
groupMap.get(key).order_ids.push(oid);
}
}
const spaceIds = [ ...new Set([ ...orderSpaceMap.values() ].filter(sid => sid > 0)) ];
const sequenceMap = new Map();
if (spaceIds.length > 0) {
const locationRows = await ctx.model.LocationSpace.findAll({
where: { id: { [this.app.Sequelize.Op.in]: spaceIds } },
attributes: [ 'id', 'pick_sequence' ],
raw: true,
transaction,
});
for (const row of (Array.isArray(locationRows) ? locationRows : [])) {
const lid = Number(row && row.id || 0);
if (lid > 0 && !sequenceMap.has(lid)) {
sequenceMap.set(lid, Number(row.pick_sequence || 0));
}
}
}
// 每组取最小 pick_sequence 排序
const groups = [ ...groupMap.values() ];
groups.sort((a, b) => {
const seqA = Math.min(...a.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER));
const seqB = Math.min(...b.order_ids.map(oid => sequenceMap.get(orderSpaceMap.get(oid)) ?? Number.MAX_SAFE_INTEGER));
if (seqA !== seqB) return seqA - seqB;
return a.order_ids[0] - b.order_ids[0];
});
return groups;
} catch (error) {
ctx.logger.warn('[pick.resolveLocationSortedOrderIds] 按库位排序失败,退回原顺序', {
error: error && error.message,
warehouseId,
orderCount: normalizedOrderIds.length,
});
return [{ stock_id: 0, order_ids: normalizedOrderIds }];
}
}
/**
* 按关键字获取或创建波次拣货任务。
*
@ -709,7 +914,25 @@ class PickService extends MainService {
const normalizedWaveType = Number(targetWaveType || 2);
const isGroupWave = normalizedWaveType === 1;
const pickMode = isGroupWave ? 1 : 2;
// 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式
let isManualIdsWave = false;
try {
const waveInfoRows = await ctx.model.query(
`SELECT item_part_type
FROM wms_wave_batch
WHERE wave_id = :waveId
LIMIT 1`,
{
replacements: { waveId: targetWaveId },
type: ctx.model.QueryTypes.SELECT,
}
);
const waveInfo = Array.isArray(waveInfoRows) && waveInfoRows.length > 0 ? waveInfoRows[0] : null;
isManualIdsWave = String(waveInfo && waveInfo.item_part_type || '').trim() === 'manual_ids';
} catch (e) {
// 查询失败不影响主流程,退回默认拣货模式
}
const pickMode = isGroupWave ? 1 : (isManualIdsWave ? 3 : 2);
if (selectedOrderIds.length === 0) {
let orderModel = null;
@ -1080,7 +1303,25 @@ class PickService extends MainService {
const normalizedWaveType = Number(targetWaveType || 2);
const isGroupWave = normalizedWaveType === 1;
const pickMode = isGroupWave ? 1 : 2;
// 检查是否为 singleFetchByIds 创建的波次(item_part_type='manual_ids'),使用先拣后分模式
let isManualIdsWaveWP = false;
try {
const waveInfoRowsWP = await ctx.model.query(
`SELECT item_part_type
FROM wms_wave_batch
WHERE wave_id = :waveId
LIMIT 1`,
{
replacements: { waveId: targetWaveId },
type: ctx.model.QueryTypes.SELECT,
}
);
const waveInfoWP = Array.isArray(waveInfoRowsWP) && waveInfoRowsWP.length > 0 ? waveInfoRowsWP[0] : null;
isManualIdsWaveWP = String(waveInfoWP && waveInfoWP.item_part_type || '').trim() === 'manual_ids';
} catch (e) {
// 查询失败不影响主流程,退回默认拣货模式
}
const pickMode = isGroupWave ? 1 : (isManualIdsWaveWP ? 3 : 2);
try {
const createdTask = await this.createWavePickTask({

View File

@ -746,6 +746,7 @@ class ExpressPlatformService extends MainService {
company: listByWarehousePlatformCode.shop_name || '',
name: listByWarehousePlatformCode.sender_name || '',
phone: listByWarehousePlatformCode.sender_tel || '',
mobile: order.sys_platform_code === 'XHS' ? listByWarehousePlatformCode.sender_tel : undefined,
country: 'CN',
city: listByWarehousePlatformCode.city_name || '',
province: listByWarehousePlatformCode.province_name || '',
@ -1776,6 +1777,7 @@ class ExpressPlatformService extends MainService {
count: item.plan_qty,
})) || [],
goods_description: '物品',
id:`${orderDelivery.warehouse_id}_${orderDelivery.id}_${order_tmp.business_key}`,
},
recipient: {
address: {
@ -2355,6 +2357,7 @@ class ExpressPlatformService extends MainService {
name: item.item_name || '商品',
count: item.plan_qty,
})) || [],
id:`${order_tmp.order_delivery.warehouse_id}_${order_tmp.order_delivery.id}_${order_tmp.business_key}`,
},
recipient: {
address: {

View File

@ -0,0 +1,250 @@
'use strict';
const Service = require('egg').Service;
/**
* 站内信群管理业务逻辑层。
* 提供群列表查询、禁用、修改等核心能力。
*/
class InboxGroupService extends Service {
/**
* 拉取当前仓库的群列表。
*
* @param {Object} data 请求数据。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {string} [data.keyword] 按群名称模糊搜索。
* @param {number} [data.page=1] 页码。
* @param {number} [data.pageSize=20] 每页条数。
* @return {Promise<Object>} { total, list }。
*/
async list(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(data.warehouseId);
const groupType = String(data.groupType || '').trim();
const keyword = String(data.keyword || '').trim();
const page = Math.max(1, Number(data.page) || 1);
const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20));
const offset = (page - 1) * pageSize;
if (!warehouseId) throw new Error('warehouseId 无效');
const where = { warehouse_id: warehouseId };
if (groupType) where.group_type = groupType;
if (keyword) where.group_name = { [Op.like]: `%${keyword}%` };
const { count, rows } = await InboxGroup.findAndCountAll({
attributes: [
'id', 'group_name', 'group_id', 'warehouse_id', 'store_id',
'group_type', 'sub_type', 'source_type', 'source_extra',
'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code',
'created_at', 'updated_at',
],
where,
order: [[ 'created_at', 'DESC' ]],
limit: pageSize,
offset,
raw: true,
});
// express_interfaces 输出为数组
const list = rows.map(row => ({
...row,
express_interfaces: row.express_interfaces
? row.express_interfaces.split(',').map(Number).filter(Boolean)
: [],
}));
return { total: count, list };
}
/**
* 禁用 / 解禁群。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。
* @return {Promise<void>}
*/
async disable(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
const isBlocked = data.isBlocked === 1 ? 1 : 0;
if (!id) throw new Error('群ID无效');
if (!warehouseId) throw new Error('warehouseId 无效');
const [ affected ] = await InboxGroup.update(
{ is_blocked: isBlocked },
{ where: { id, warehouse_id: warehouseId } }
);
if (!affected) {
throw new Error('群不存在或无权限操作');
}
ctx.logger.info(
`[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}`
);
}
/**
* 修改群信息。
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
* 群类型切为 express 时 system_express_code 必填,
* express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。
*
* @param {Object} data 请求数据。
* @param {number} data.id 群记录主键ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.groupType] 群类型:store / warehouse / express。
* @param {string} [data.subType] 群子类型。
* @param {number} [data.storeId] 关联货主ID。
* @param {number[]} [data.expressInterfaces] 快递接口ID数组。
* @param {string} [data.systemExpressCode] 系统快递编码。
* @return {Promise<void>}
*/
async update(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const id = Number(data.id);
const warehouseId = Number(data.warehouseId);
if (!id) throw new Error('群ID无效');
if (!warehouseId) throw new Error('warehouseId 无效');
// 查群是否存在
const group = await InboxGroup.findOne({
attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ],
where: { id, warehouse_id: warehouseId },
raw: true,
});
if (!group) throw new Error('群不存在或无权限操作');
// 目标群类型(优先新值,否则保留原值)
const targetGroupType = data.groupType !== undefined
? String(data.groupType).trim()
: group.group_type || '';
const isExpress = targetGroupType === 'express';
// express_interfaces 处理
let expressInterfaces = null;
if (data.expressInterfaces !== undefined) {
if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) {
// 校验快递接口ID有效性
await this.validateExpressInterfaces(data.expressInterfaces);
expressInterfaces = data.expressInterfaces.join(',');
} else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) {
// 空数组 = 清空 = 表示全部快递类型
expressInterfaces = '';
} else {
expressInterfaces = null; // 未传入 = 不修改
}
}
// system_express_code 校验
let systemExpressCode;
if (data.systemExpressCode !== undefined) {
const code = String(data.systemExpressCode).trim();
if (code) {
await this.validateSystemExpressCode(code);
systemExpressCode = code;
} else {
systemExpressCode = null;
}
}
// 切换为 express 类型时 system_express_code 不能为空
if (isExpress && data.groupType !== undefined) {
const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code;
if (!finalCode) {
throw new Error('群类型为快递群时,系统快递编码不能为空');
}
}
// 构建更新字段
const updateData = {};
if (data.groupType !== undefined) updateData.group_type = targetGroupType || null;
if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null;
if (data.storeId !== undefined) {
updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0
? Number(data.storeId) : null;
}
// 非 express 群类型时忽略 express 相关字段
if (isExpress && expressInterfaces !== null) {
updateData.express_interfaces = expressInterfaces || null;
}
if (isExpress && systemExpressCode !== undefined) {
updateData.system_express_code = systemExpressCode || null;
}
// AI 开关(所有群类型均支持)
if (data.aiEnabled !== undefined) {
updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0;
}
if (Object.keys(updateData).length === 0) {
throw new Error('未提供任何需要修改的字段');
}
await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } });
ctx.logger.info(
`[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}`
);
}
/**
* 校验快递接口ID数组的有效性。
* 所有ID必须在 wms_express_interface 表中存在。
*
* @param {number[]} ids 快递接口ID数组。
* @return {Promise<void>} 无效时抛出异常。
*/
async validateExpressInterfaces(ids) {
const { ctx } = this;
if (!Array.isArray(ids) || ids.length === 0) return;
const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0);
if (numericIds.length !== ids.length) {
throw new Error('快递接口ID包含无效值');
}
const count = await ctx.model.ExpressInterface.count({
where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } },
});
if (count !== numericIds.length) {
throw new Error('部分快递接口ID不存在');
}
}
/**
* 校验系统快递编码有效性。
* 必须在 wms_express 表中存在对应的 code。
*
* @param {string} code 系统快递编码。
* @return {Promise<void>} 无效时抛出异常。
*/
async validateSystemExpressCode(code) {
const { ctx } = this;
const trimmed = String(code).trim();
if (!trimmed) throw new Error('系统快递编码不能为空');
const exists = await ctx.model.Express.count({
where: { code: trimmed },
});
if (!exists) {
throw new Error(`系统快递编码 "${trimmed}" 不存在`);
}
}
}
module.exports = InboxGroupService;

View File

@ -973,6 +973,29 @@ class PickSystemService extends Service {
const warehouseId = Number(taskRow.warehouse_id || 0);
const pickMode = Number(taskRow.pick_mode || 0);
// 查询任务关联的波次号
let taskWaveNo = '';
try {
const taskWaveNoRows = await ctx.model.query(`
SELECT
wb.wave_no
FROM wms_wave_pick_task_wave ptw
INNER JOIN wms_wave_batch wb ON wb.wave_id = ptw.wave_id
WHERE ptw.task_id = :taskId
ORDER BY ptw.id ASC
LIMIT 1
`, {
replacements: { taskId },
type: ctx.model.QueryTypes.SELECT,
});
taskWaveNo = Array.isArray(taskWaveNoRows) && taskWaveNoRows.length > 0
? String(taskWaveNoRows[0].wave_no || '').trim()
: '';
} catch (error) {
ctx.logger.warn(`[pick.wavePickTaskDetail] 查询波次号失败,将降级为空: ${error.message}`);
}
const taskOrderColumnSet = await this.getTableColumnSet('wms_wave_pick_task_order');
const taskWaveColumnSet = await this.getTableColumnSet('wms_wave_pick_task_wave');
const boxColumnSet = await this.getTableColumnSet('wms_wave_pick_task_box');
@ -1238,6 +1261,16 @@ class PickSystemService extends Service {
.map(row => [ Number(row && row.box_no || 0), row ])
.filter(([ boxNo ]) => boxNo > 0));
// 构建 stock_id → box_no 映射(从 wms_wave_pick_task_box.ref_id),用于给每个拣货明细行标注篮号
const boxNoByStockId = new Map();
for (const row of normalizedBoxRows) {
const sid = Number(row && row.ref_id || 0);
const bno = Number(row && row.box_no || 0);
if (sid > 0 && bno > 0 && !boxNoByStockId.has(sid)) {
boxNoByStockId.set(sid, bno);
}
}
const pickingDetails = (Array.isArray(pickingRows) ? pickingRows : []).map(row => {
const orderItemId = Number(row && row.order_item_id || 0);
const currentSpaceId = Number(row && row.space_id || 0);
@ -1272,6 +1305,7 @@ class PickSystemService extends Service {
return {
order_id: Number(row && row.order_id || 0),
box_no: boxNoByStockId.get(stockId) || 0,
order_item_id: orderItemId,
quantity: Number(row && row.quantity || 0),
storage_id: Number(row && row.storage_id || 0),
@ -1297,6 +1331,17 @@ class PickSystemService extends Service {
};
});
// 排序 picking_details:box_no 已按库位顺序生成,直接按 box_no 升序即可
pickingDetails.sort((a, b) => {
const boxA = Number(a && a.box_no || 0);
const boxB = Number(b && b.box_no || 0);
if (boxA !== boxB) return boxA - boxB;
const codeA = String(a && a.item_code || '').trim();
const codeB = String(b && b.item_code || '').trim();
return codeA.localeCompare(codeB);
});
const pickingSummary = this.buildPickingSummary(pickingDetails);
const pickingView = await this.buildPickingView({
pickMode,
@ -1312,6 +1357,7 @@ class PickSystemService extends Service {
task: {
task_id: Number(taskRow.task_id || 0),
task_no: String(taskRow.task_no || '').trim(),
wave_no: taskWaveNo,
status: Number(taskRow.status || 0),
pick_mode: pickMode,
start_at: taskRow.start_at || null,

View File

@ -51,6 +51,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
required: false,
description: '是否启用订单创建后自动加入团购波次,默认 false(关闭)',
}),
Object.freeze({
key: 'auto_allocate_express_exclude_remarks',
name: '自动分配快递排除备注',
type: 'string_array',
default: [],
required: false,
description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)',
}),
Object.freeze({
key: 'default_express_code',
name: '默认快递编码',

View File

@ -1004,6 +1004,73 @@ class StoreService extends Service {
throw error;
}
}
/**
* 生成货主绑群码。
* 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。
*
* @param {Object} data 请求数据。
* @param {number} data.storeId 货主ID(必填)。
* @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。
* @param {string} [data.subType] 群子类型:after_sales / finance / receiving。
* @return {Promise<Object>} { code: 绑群码 }。
*/
async bindCode(data = {}) {
const { ctx } = this;
const storeId = Number(data.storeId);
const warehouseId = Number(data.warehouseId);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw new Error('storeId 无效');
}
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('缺少仓库信息,请确认已登录并选择了仓库');
}
const contract = await ctx.model.StoreWarehouse.findOne({
attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ],
where: {
store_id: storeId,
warehouse_id: warehouseId,
auth_status: 2,
warehouse_use_status: 1,
},
raw: true,
});
if (!contract) {
throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`);
}
const subType = String(data.subType || '').trim();
const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ];
if (subType && !VALID_SUB_TYPES.includes(subType)) {
throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`);
}
const code = Math.random().toString(36).slice(2, 8)
.toUpperCase()
+ Math.random().toString(36).slice(2, 8)
.toUpperCase();
const cacheKey = `chat:bind:${warehouseId}:${code}`;
const cacheValue = {
store_id: contract.store_id,
initiator_subject_id: contract.initiator_subject_id || null,
warehouse_id: contract.warehouse_id,
group_type: 'store',
sub_type: subType || null,
};
await ctx.app.setCacheAsync(cacheKey, cacheValue, 300);
ctx.logger.info(
`[store bindCode] 生成绑群码 code=${code} ` +
`store_id=${contract.store_id} warehouse_id=${warehouseId}`
);
return { code };
}
}
module.exports = StoreService;

View File

@ -29,10 +29,6 @@ class WarehouseInboxService extends MainService {
throw new Error('requestId 不能为空');
}
if (!body.targetChannel || !String(body.targetChannel).trim()) {
throw new Error('targetChannel 不能为空');
}
// 构造 ext_id
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
@ -40,13 +36,16 @@ class WarehouseInboxService extends MainService {
const result = await ctx.service.inbox.receiver.receive({
ext_id: extId,
warehouse_id: warehouseId,
store_id: body.storeId || null,
direction: 'inbound',
parent_id: body.parentId || null,
source_type: body.sourceType || 'api',
source_extra: String(appKey || ''),
target_type: body.targetType || 'im',
target_channel: body.targetChannel,
group_name: body.groupName || null,
user_name: body.userName || null,
group_id: body.groupId || null,
user_id: body.userId || null,
content: body.content || null,
ext_data: body.extData || null,
flags: body.flags || {},
});

View File

@ -65,18 +65,33 @@ module.exports = {
},
target_channel: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
allowNull: true,
comment: '目标渠道(仅供参考,出站路由由外部系统负责)',
},
target_url: {
type: Sequelize.STRING(500),
allowNull: false,
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
},
ref_code: {
group_name: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '外部引用编码,推送/回执时原样携带',
comment: '群名称(外部传入)',
},
user_name: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '用户名称(外部传入)',
},
group_id: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '外部群ID',
},
user_id: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '外部用户ID',
},
content: {
type: Sequelize.TEXT,
allowNull: true,
comment: '消息正文/摘要,用于列表展示和关键词搜索',
},
ext_data: {
type: Sequelize.JSON,

View File

@ -0,0 +1,33 @@
'use strict';
const TABLE_NAME = 'wms_inbox_message';
const COLUMN_NAME = 'content';
module.exports = {
/**
* 为站内信消息表添加消息正文字段。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns[COLUMN_NAME]) return;
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
type: Sequelize.TEXT,
allowNull: true,
comment: '消息正文/摘要,用于列表展示和关键词搜索',
after: 'target_channel',
});
},
/**
* 回滚:移除消息正文字段。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @return {Promise<void>} 迁移回滚结果。
*/
down: async queryInterface => {
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
},
};

View File

@ -0,0 +1,57 @@
'use strict';
const TABLE_NAME = 'wms_inbox_block';
module.exports = {
/**
* 创建站内信屏蔽表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @param {Object} Sequelize Sequelize 类。
* @return {Promise<void>} 迁移执行结果。
*/
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
group_name: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '群名称',
},
user_name: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '用户名称',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
});
await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'user_name' ], {
unique: true,
name: 'uk_group_user',
});
},
/**
* 回滚:删除站内信屏蔽表。
* @param {Object} queryInterface Sequelize QueryInterface 实例。
* @return {Promise<void>} 迁移回滚结果。
*/
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,92 @@
'use strict';
const TABLE_NAME = 'wms_inbox_group';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
if (tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME)) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
group_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '群名称',
},
group_id: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '外部群ID',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '所属仓库ID',
},
store_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联货主ID',
},
group_type: {
type: Sequelize.ENUM('store', 'warehouse', 'express'),
allowNull: true,
comment: '群类型: store=货主 warehouse=仓库 express=快递',
},
sub_type: {
type: Sequelize.STRING(20),
allowNull: true,
comment: '群子类型',
},
source_type: {
type: Sequelize.STRING(20),
allowNull: true,
comment: '来源类型:im / api / system',
},
source_extra: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '来源附加信息',
},
is_blocked: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否屏蔽 0=否 1=是',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'warehouse_id' ], {
unique: true,
name: 'uk_group_warehouse',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,42 @@
'use strict';
/**
* 为 wms_inbox_group 添加快递相关字段:
* - express_interfaces:快递接口ID列表(逗号分隔)
* - system_express_code:系统快递编码
*/
module.exports = {
up: async (queryInterface, Sequelize) => {
const { STRING } = Sequelize;
// 检查列是否已存在
const tableInfo = await queryInterface.describeTable('wms_inbox_group');
if (!tableInfo.express_interfaces) {
await queryInterface.addColumn('wms_inbox_group', 'express_interfaces', {
type: STRING(500),
allowNull: true,
comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)',
});
}
if (!tableInfo.system_express_code) {
await queryInterface.addColumn('wms_inbox_group', 'system_express_code', {
type: STRING(50),
allowNull: true,
comment: '系统快递编码(仅群类型为 express 时必填)',
});
}
},
down: async (queryInterface) => {
const tableInfo = await queryInterface.describeTable('wms_inbox_group');
if (tableInfo.express_interfaces) {
await queryInterface.removeColumn('wms_inbox_group', 'express_interfaces');
}
if (tableInfo.system_express_code) {
await queryInterface.removeColumn('wms_inbox_group', 'system_express_code');
}
},
};

View File

@ -0,0 +1,73 @@
'use strict';
/**
* 新增「消息和自动回复」根菜单及「群列表」「消息记录」子页面。
*
* 固定 ID(开发库 & 生产库 wms_permission 当前 max_id 均为 491):
* 492 — 父级菜单 "消息和自动回复"
* 493 — inbox.groups(群列表)
* 494 — inbox.messages(消息记录)
*
* 授权角色(permissions 不为 "*" 的 主管/经理 级角色):
* 8 — 经理
* 26 — 仓库组-主管
* 28 — 客服组-主管
* 29 — 生产组-主管
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 插入父级权限 (type=web_pages, sort=13) ──
// 使用 INSERT IGNORE 兼容生产环境已有数据(路径相同但名称可能略有差异)
await queryInterface.sequelize.query(`
INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (492, '/inbox', NULL, '消息和自动回复', NULL, '消息和自动回复', NULL, 0, 0, NULL, 'web_pages', 13, 1, NOW(), NOW())
`);
// ── 2. 插入子页面权限 ──
// 群列表
await queryInterface.sequelize.query(`
INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (493, '/inbox/groups', NULL, 'inbox.groups', NULL, '群列表', NULL, 0, 0, 492, 'web_pages', 0, 1, NOW(), NOW())
`);
// 消息记录
await queryInterface.sequelize.query(`
INSERT IGNORE INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (494, '/inbox/messages', NULL, 'inbox.messages', NULL, '消息记录', NULL, 0, 0, 492, 'web_pages', 1, 1, NOW(), NOW())
`);
// ── 3. 给 客服组-主管及以上角色 追加权限 ID(幂等:已包含则跳过)──
const newIdSuffix = ', 492, 493, 494';
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]')
WHERE id IN (8, 26, 28, 29)
AND permissions != '*'
AND permissions IS NOT NULL
AND LENGTH(permissions) > 2
AND permissions NOT LIKE '% 492,%'
`);
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
// ── 1. 从角色权限中移除新增的 ID ──
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = REPLACE(permissions, ', 492, 493, 494', '')
WHERE id IN (8, 26, 28, 29)
`);
// ── 2. 删除子页面权限 ──
await queryInterface.sequelize.query(
'DELETE FROM wms_permission WHERE id IN (493, 494)'
);
// ── 3. 删除父级权限 ──
await queryInterface.sequelize.query(
'DELETE FROM wms_permission WHERE id = 492'
);
},
};

View File

@ -0,0 +1,73 @@
'use strict';
/**
* 为站内信消息表和群表补充查询索引。
*
* wms_inbox_message:
* - idx_warehouse_group_created: (warehouse_id, group_id, created_at)
* 用于按群拉取消息列表(最常用查询)。
*
* wms_inbox_group:
* - idx_group_id: (group_id)
* 用于 receiver/processor 中按 group_id 查找群。
* - idx_warehouse_group_id: (warehouse_id, group_id)
* 用于按仓库+群ID定位群。
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
up: async (queryInterface, Sequelize) => {
// ── wms_inbox_message 索引 ──
const msgTableInfo = await queryInterface.describeTable('wms_inbox_message');
// 检查已有索引(通过尝试添加,重复则忽略)
try {
await queryInterface.addIndex('wms_inbox_message', {
fields: ['warehouse_id', 'group_id', 'created_at'],
name: 'idx_warehouse_group_created',
});
console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建');
} catch (e) {
if (e.message && e.message.includes('Duplicate')) {
console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已存在,跳过');
} else {
throw e;
}
}
// ── wms_inbox_group 索引 ──
try {
await queryInterface.addIndex('wms_inbox_group', {
fields: ['group_id'],
name: 'idx_group_id',
});
console.log('[idx] wms_inbox_group.idx_group_id 已创建');
} catch (e) {
if (e.message && e.message.includes('Duplicate')) {
console.log('[idx] wms_inbox_group.idx_group_id 已存在,跳过');
} else {
throw e;
}
}
try {
await queryInterface.addIndex('wms_inbox_group', {
fields: ['warehouse_id', 'group_id'],
name: 'idx_warehouse_group_id',
});
console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建');
} catch (e) {
if (e.message && e.message.includes('Duplicate')) {
console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已存在,跳过');
} else {
throw e;
}
}
},
// eslint-disable-next-line no-unused-vars
down: async (queryInterface, Sequelize) => {
await queryInterface.removeIndex('wms_inbox_message', 'idx_warehouse_group_created');
await queryInterface.removeIndex('wms_inbox_group', 'idx_group_id');
await queryInterface.removeIndex('wms_inbox_group', 'idx_warehouse_group_id');
},
};

View File

@ -0,0 +1,53 @@
'use strict';
/**
* 为 inbox.group.* 方法创建 API 权限记录。
*
* 固定 ID(当前 max_id=494):
* 495 — inbox.group.list
* 496 — inbox.group.disable
* 497 — inbox.group.update
* 498 — inbox.group.messages
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const methods = [
[495, 'inbox.group.list'],
[496, 'inbox.group.disable'],
[497, 'inbox.group.update'],
[498, 'inbox.group.messages'],
];
for (const [id, method] of methods) {
await queryInterface.sequelize.query(`
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${method}', type='api'
`);
}
// 授权给客服组-主管及以上角色
const newIdSuffix = ', 495, 496, 497, 498';
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]')
WHERE id IN (8, 26, 28, 29)
AND permissions != '*'
AND permissions IS NOT NULL
AND LENGTH(permissions) > 2
`);
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
'DELETE FROM wms_permission WHERE id IN (495, 496, 497, 498)'
);
await queryInterface.sequelize.query(`
UPDATE wms_role
SET permissions = REPLACE(permissions, ', 495, 496, 497, 498', '')
WHERE id IN (8, 26, 28, 29)
`);
},
};

View File

@ -0,0 +1,90 @@
'use strict';
/**
* 扩大 wms_wave_batch.item_snapshot_key 列容量以容纳多商品订单的快照键。
*
* 背景:
* buildItemSnapshotKey 将订单中每个商品的 stock_id、item_code、
* item_name、barcode、quantity 用 :: 拼接,多个商品再用 | 连接。
* 当订单包含较多商品或商品名较长时,快照键极易超过原 VARCHAR(255) 上限,
* 导致 INSERT 时报 "Data too long for column 'item_snapshot_key'"。
*
* 变更:
* 1. item_snapshot_key: VARCHAR(255) → VARCHAR(1024)
* (与 item_detail_machine 容量保持一致)
* 2. 索引 idx_wave_snapshot_key: 全列索引 → 前缀索引(191)
* (与 idx_wave_item_machine_prefix 前缀长度一致,
* 兼容 utf8mb4 下的 InnoDB 索引键长度限制)
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
up: async (queryInterface, Sequelize) => {
// ── 1. 先删旧全列索引(否则 changeColumn 1024 会触发 3072 字节限制)──
try {
await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key');
console.log('[migrate] 已移除旧全列索引 idx_wave_snapshot_key');
} catch (e) {
// 索引可能不存在(如全新库或已执行过),忽略
const msg = String(e.message || '');
if (!msg.includes('check that it exists') && !msg.includes('exist')) {
console.warn('[migrate] 移除索引 idx_wave_snapshot_key 时出现非预期错误:', msg);
}
}
// ── 2. 修改列容量 ──
await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', {
type: Sequelize.STRING(1024),
allowNull: true,
comment: '结构快照键(与 item_detail_machine 一致,1024 长度以容纳多商品订单的快照)',
});
console.log('[migrate] wms_wave_batch.item_snapshot_key VARCHAR(255) → VARCHAR(1024)');
// ── 3. 创建前缀索引 ──
try {
await queryInterface.sequelize.query(
'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key(191))'
);
console.log('[migrate] 已创建前缀索引 idx_wave_snapshot_key(item_snapshot_key(191))');
} catch (e) {
if (e.message && e.message.includes('Duplicate')) {
console.log('[migrate] 前缀索引 idx_wave_snapshot_key 已存在,跳过');
} else {
throw e;
}
}
},
// eslint-disable-next-line no-unused-vars
down: async (queryInterface, Sequelize) => {
// ── 还原索引为全列索引 ──
try {
await queryInterface.removeIndex('wms_wave_batch', 'idx_wave_snapshot_key');
console.log('[migrate:down] 已移除前缀索引 idx_wave_snapshot_key');
} catch (e) {
if (!(e.message && e.message.includes('check that it exists'))) {
console.warn('[migrate:down] 移除索引时出现非预期错误:', e.message);
}
}
try {
await queryInterface.sequelize.query(
'ALTER TABLE wms_wave_batch ADD INDEX idx_wave_snapshot_key (item_snapshot_key)'
);
console.log('[migrate:down] 已还原全列索引 idx_wave_snapshot_key');
} catch (e) {
if (e.message && e.message.includes('Duplicate')) {
console.log('[migrate:down] 全列索引 idx_wave_snapshot_key 已存在,跳过');
} else {
throw e;
}
}
// ── 还原列容量 ──
await queryInterface.changeColumn('wms_wave_batch', 'item_snapshot_key', {
type: Sequelize.STRING(255),
allowNull: true,
comment: '结构快照键',
});
console.log('[migrate:down] wms_wave_batch.item_snapshot_key VARCHAR(1024) → VARCHAR(255)');
},
};

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 为 wms_inbox_message 新增 ai_thoughts 字段。
* 存储 AI 多轮推理的思考过程数组。
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
up: async (queryInterface, Sequelize) => {
const tableInfo = await queryInterface.describeTable('wms_inbox_message');
if (!tableInfo.ai_thoughts) {
await queryInterface.addColumn('wms_inbox_message', 'ai_thoughts', {
type: Sequelize.JSON,
allowNull: true,
comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]',
});
}
},
// eslint-disable-next-line no-unused-vars
down: async (queryInterface) => {
const tableInfo = await queryInterface.describeTable('wms_inbox_message');
if (tableInfo.ai_thoughts) {
await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts');
}
},
};

View File

@ -0,0 +1,21 @@
'use strict';
const TABLE_NAME = 'wms_inbox_group';
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.ai_enabled) return;
await queryInterface.addColumn(TABLE_NAME, 'ai_enabled', {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '是否启用AI自动回复: 0=关闭 1=开启',
});
},
down: async queryInterface => {
await queryInterface.removeColumn(TABLE_NAME, 'ai_enabled');
},
};

View File

@ -0,0 +1,20 @@
'use strict';
const TABLE_NAME = 'wms_inbox_message';
module.exports = {
up: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns.target_channel) return;
await queryInterface.removeColumn(TABLE_NAME, 'target_channel');
},
down: async (queryInterface, Sequelize) => {
await queryInterface.addColumn(TABLE_NAME, 'target_channel', {
type: Sequelize.STRING(50),
allowNull: true,
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
});
},
};

View File

@ -1,4 +1,41 @@
[
{
"version": "2026.08.06-inbox-bindCode",
"date": "2026-08-06",
"type": "added",
"summary": "新增货主绑群码生成接口。校验 StoreWarehouse 合约有效性后生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。实现位于 systems/store.js → bindCode(),由 systemMethods/inbox.js → bindCode() 委托调用。",
"methods": [
"inbox.bindCode"
],
"notes": [
"调用链:/system → systemMethods/inbox.bindCode → systems/store.bindCode。",
"前置校验:StoreWarehouse 合约 auth_status=2 AND warehouse_use_status=1,不满足则返回500。",
"缓存策略:app.setCacheAsync('chat:bind:{warehouseId}:{code}', { store_id, initiator_subject_id, warehouse_id, group_type, sub_type }, 300)。",
"绑定时消费:processor.tryBindGroup 匹配 '授权:CODE' 模式,读取缓存执行绑定,成功即清缓存。",
"warehouseId:从 ctx.user.store_id 自动注入,前端无需传递。"
],
"module": "inbox"
},
{
"version": "2026.08.05-inbox-group",
"date": "2026-08-05",
"type": "added",
"summary": "站内信模块新增群管理接口:群列表拉取、群禁用/解禁、群信息修改(支持群类型/子类型/货主/快递接口/系统快递编码)、按群查询消息列表。仓库ID由服务端自动注入。express_interfaces输出为数组,systemExpressCode在express类型时必填校验。",
"methods": [
"inbox.group.list",
"inbox.group.disable",
"inbox.group.update",
"inbox.group.messages"
],
"notes": [
"inbox.group.list:按群类型/关键词筛选,分页返回。express_interfaces 存储逗号分隔输出数组。",
"inbox.group.disable:通过群主键ID禁用/解禁(isBlocked=1禁用/0启用)。",
"inbox.group.update:支持修改groupType/subType/storeId/expressInterfaces/systemExpressCode。切换为express类型时systemExpressCode必填且需校验wms_express.code存在,expressInterfaces需校验wms_express_interface.id存在。非express类型忽略express相关字段。",
"inbox.group.messages:按groupId拉取消息列表,支持direction/keyword筛选,仓库隔离,查询命中idx_warehouse_group_created索引。",
"公共:所有方法warehouseId均从ctx.user.store_id自动注入,前端无需传递。"
],
"module": "inbox"
},
{
"version": "2026.08.01-system-01",
"date": "2026-08-01",
@ -5299,5 +5336,17 @@
"新增store_ids限定货主ID"
],
"module": "storeExpressBindingPolicy"
},
{
"version": "2026-08-05-wavePickTaskDetail-waveNo",
"date": "2026-08-05",
"summary": "pick.wavePickTaskDetail 响应 task 对象新增 wave_no 字段,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取波次号",
"methods": [
"pick.wavePickTaskDetail"
],
"notes": [
"task 对象新增 wave_no(string)字段,位于 task_no 之后;查询失败时降级为空字符串。",
"数据来源:wms_wave_pick_task_wave INNER JOIN wms_wave_batch ON wave_id。"
]
}
]

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.17",
"updatedAt": "2026-08-04",
"version": "0.3.19",
"updatedAt": "2026-08-05",
"headers": [
{
"name": "platform",
@ -17757,6 +17757,12 @@
"description": "任务编号",
"required": false
},
{
"name": "wave_no",
"type": "string",
"description": "波次号,从 wms_wave_pick_task_wave 关联 wms_wave_batch 获取;无关联波次时为空字符串",
"required": false
},
{
"name": "status",
"type": "number",
@ -31873,8 +31879,8 @@
"module": "inbox",
"list": [
{
"method": "inbox.list",
"description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)",
"method": "inbox.message.list",
"description": "站内信消息列表,支持货主/群/用户名/正文/来源等多条件筛选,时间字段使用统一格式化输出,分页返回(默认20条/页,最大200条)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -31886,6 +31892,48 @@
}
],
"params": [
{
"name": "storeId",
"type": "string",
"required": false,
"source": "body",
"description": "货主ID筛选,支持逗号分隔多选,如 \"1000000,1000001\""
},
{
"name": "groupId",
"type": "string",
"required": false,
"source": "body",
"description": "群ID筛选,支持逗号分隔多选"
},
{
"name": "groupName",
"type": "string",
"required": false,
"source": "body",
"description": "群名称模糊搜索"
},
{
"name": "userName",
"type": "string",
"required": false,
"source": "body",
"description": "用户名模糊搜索"
},
{
"name": "content",
"type": "string",
"required": false,
"source": "body",
"description": "正文模糊搜索"
},
{
"name": "sourceType",
"type": "string",
"required": false,
"source": "body",
"description": "来源类型筛选:im / api / system"
},
{
"name": "direction",
"type": "string",
@ -31900,20 +31948,6 @@
"source": "body",
"description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败"
},
{
"name": "targetChannel",
"type": "string",
"required": false,
"source": "body",
"description": "目标渠道筛选:wecom / dingtalk / feishu / warehouse_api / webhook"
},
{
"name": "keyword",
"type": "string",
"required": false,
"source": "body",
"description": "关键词搜索,模糊匹配 ext_id 和 ref_code"
},
{
"name": "page",
"type": "number",
@ -31936,7 +31970,7 @@
"name": "list",
"type": "array",
"required": true,
"description": "消息列表(不含 ext_data 和 push_response 大字段)",
"description": "消息列表(不含 ext_data、push_response、target_channel 字段,时间已格式化)",
"children": [
{
"name": "id",
@ -31956,6 +31990,18 @@
"required": true,
"description": "所属仓库ID"
},
{
"name": "store_id",
"type": "number",
"required": false,
"description": "关联货主ID"
},
{
"name": "store_name",
"type": "string",
"required": false,
"description": "货主名称(批量回填)"
},
{
"name": "direction",
"type": "string",
@ -31975,10 +32021,34 @@
"description": "目标类型:im / api / webhook"
},
{
"name": "target_channel",
"name": "group_id",
"type": "string",
"required": true,
"description": "目标渠道"
"required": false,
"description": "外部群ID"
},
{
"name": "group_name",
"type": "string",
"required": false,
"description": "群名称"
},
{
"name": "user_id",
"type": "string",
"required": false,
"description": "外部用户ID"
},
{
"name": "user_name",
"type": "string",
"required": false,
"description": "用户名称"
},
{
"name": "content",
"type": "string",
"required": false,
"description": "消息正文/摘要"
},
{
"name": "push_status",
@ -31996,7 +32066,19 @@
"name": "created_at",
"type": "string",
"required": true,
"description": "创建时间"
"description": "创建时间(YYYY-MM-DD HH:mm:ss 格式化)"
},
{
"name": "updated_at",
"type": "string",
"required": true,
"description": "更新时间(YYYY-MM-DD HH:mm:ss 格式化)"
},
{
"name": "pushed_at",
"type": "string",
"required": false,
"description": "推送完成时间(YYYY-MM-DD HH:mm:ss 格式化)"
}
]
},
@ -32057,7 +32139,7 @@
]
},
{
"method": "inbox.detail",
"method": "inbox.message.detail",
"description": "站内信消息详情,含完整 push_response 推送响应信息",
"isNeedAuth": false,
"isNeedLogin": true,
@ -32180,7 +32262,7 @@
]
},
{
"method": "inbox.thread",
"method": "inbox.message.thread",
"description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列",
"isNeedAuth": false,
"isNeedLogin": true,
@ -32225,7 +32307,7 @@
]
},
{
"method": "inbox.reply",
"method": "inbox.message.reply",
"description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段",
"isNeedAuth": false,
"isNeedLogin": true,
@ -32310,7 +32392,7 @@
]
},
{
"method": "inbox.retry",
"method": "inbox.message.retry",
"description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送",
"isNeedAuth": false,
"isNeedLogin": true,
@ -32373,7 +32455,7 @@
]
},
{
"method": "inbox.stats",
"method": "inbox.message.stats",
"description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量",
"isNeedAuth": false,
"isNeedLogin": true,
@ -32452,6 +32534,320 @@
"message": "warehouseId 无效"
}
]
},
{
"method": "inbox.bindCode",
"description": "生成货主绑群码。校验 StoreWarehouse 合约有效后,生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。warehouseId 从 token 自动注入",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "storeId",
"type": "number",
"required": true,
"source": "body",
"description": "货主ID(需在目标仓库有有效合约 auth_status=2 warehouse_use_status=1)"
},
{
"name": "subType",
"type": "string",
"required": false,
"source": "body",
"description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)"
}
],
"response": [
{
"name": "code",
"type": "string",
"required": true,
"description": "12位绑群随机码(大写字母+数字),5分钟有效"
}
],
"errors": [
{
"code": "400",
"message": "storeId 无效 / 缺少仓库信息 / 子类型无效"
},
{
"code": "500",
"message": "货主在仓库无有效合约"
}
]
},
{
"method": "inbox.group.list",
"description": "拉取当前仓库的群列表,支持按群类型筛选和关键词搜索,express_interfaces 逗号分隔存储输出为数组",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "groupType",
"type": "string",
"required": false,
"source": "body",
"description": "群类型筛选:store(货主) / warehouse(仓库) / express(快递)"
},
{
"name": "keyword",
"type": "string",
"required": false,
"source": "body",
"description": "群名称模糊搜索"
},
{
"name": "page",
"type": "number",
"required": false,
"source": "body",
"description": "页码,默认1"
},
{
"name": "pageSize",
"type": "number",
"required": false,
"source": "body",
"description": "每页条数,默认20,最大100"
}
],
"response": [
{
"name": "total",
"type": "number",
"required": true,
"description": "总记录数"
},
{
"name": "list",
"type": "array",
"required": true,
"description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/ai_enabled/express_interfaces(数组)/system_express_code/created_at"
}
],
"errors": [
{
"code": "400",
"message": "warehouseId 无效"
}
]
},
{
"method": "inbox.group.disable",
"description": "禁用或解禁群,通过群主键ID操作",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "群记录主键ID"
},
{
"name": "isBlocked",
"type": "number",
"required": false,
"source": "body",
"description": "是否禁用:1=禁用 0=启用,默认1"
}
],
"response": [
{
"name": "message",
"type": "string",
"required": true,
"description": "操作结果提示:群已禁用 / 群已启用"
}
],
"errors": [
{
"code": "400",
"message": "群ID无效 / warehouseId 无效"
},
{
"code": "500",
"message": "群不存在或无权限操作"
}
]
},
{
"method": "inbox.group.update",
"description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "群记录主键ID"
},
{
"name": "groupType",
"type": "string",
"required": false,
"source": "body",
"description": "群类型:store(货主) / warehouse(仓库) / express(快递)"
},
{
"name": "subType",
"type": "string",
"required": false,
"source": "body",
"description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)"
},
{
"name": "storeId",
"type": "number",
"required": false,
"source": "body",
"description": "关联货主ID"
},
{
"name": "expressInterfaces",
"type": "array",
"required": false,
"source": "body",
"description": "快递接口ID数组,仅groupType=express时生效。空数组表示全部快递类型。需校验wms_express_interface.id存在"
},
{
"name": "systemExpressCode",
"type": "string",
"required": false,
"source": "body",
"description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在"
},
{
"name": "aiEnabled",
"type": "number",
"required": false,
"source": "body",
"description": "是否启用AI自动回复: 0=关闭 1=开启,默认1(所有群类型均支持,用于灰度测试)"
}
],
"response": [
{
"name": "message",
"type": "string",
"required": true,
"description": "操作结果提示:群信息修改成功"
}
],
"errors": [
{
"code": "400",
"message": "群ID无效 / 系统快递编码不能为空(express类型时)"
},
{
"code": "500",
"message": "群不存在 / 系统快递编码不存在 / 快递接口ID无效"
}
]
},
{
"method": "inbox.group.messages",
"description": "按群拉取消息列表,支持方向/关键词筛选,分页返回。warehouseId服务端自动注入,查询命中idx_warehouse_group_created索引",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
}
],
"params": [
{
"name": "groupId",
"type": "string",
"required": true,
"source": "body",
"description": "群ID(必填)"
},
{
"name": "direction",
"type": "string",
"required": false,
"source": "body",
"description": "消息方向筛选:inbound(入站) / outbound(出站)"
},
{
"name": "keyword",
"type": "string",
"required": false,
"source": "body",
"description": "关键词搜索(ext_id / content)"
},
{
"name": "page",
"type": "number",
"required": false,
"source": "body",
"description": "页码,默认1"
},
{
"name": "pageSize",
"type": "number",
"required": false,
"source": "body",
"description": "每页条数,默认20,最大200"
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "消息记录列表"
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息:page/pageSize/total/totalPages/hasPrevious/hasNext"
}
],
"errors": [
{
"code": "400",
"message": "groupId 不能为空 / warehouseId 无效"
}
]
}
]
},

View File

@ -0,0 +1,87 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const Sequelize = require('sequelize');
const ROOT = path.resolve(__dirname, '..');
const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations');
async function main() {
// 1. 收集本地所有迁移文件
const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort();
console.log(`[本地] 迁移文件总数: ${allFiles.length}`);
// 2. 连接生产数据库
const dbConfig = {
host: '112.124.21.102',
port: 3306,
user: 'wms',
password: 'P6j3YTHTpirepYWz',
database: 'wms',
};
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
port: dbConfig.port,
dialect: 'mysql',
logging: false,
});
try {
await sequelize.authenticate();
console.log('[DB] 生产数据库连接成功');
} catch (e) {
console.error('[DB] 生产数据库连接失败:', e.message);
process.exit(2);
}
// 3. 检查 SequelizeMeta 表是否存在
let appliedNames = [];
try {
const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name');
appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean);
} catch (e) {
console.error('[DB] 读取 SequelizeMeta 失败:', e.message);
await sequelize.close();
process.exit(2);
}
console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`);
// 4. 找出未执行的迁移
const appliedSet = new Set(appliedNames);
const pending = allFiles.filter(f => !appliedSet.has(f));
const archived = allFiles.filter(f => f.startsWith('archive/'));
console.log(`\n========== 结果汇总 ==========`);
console.log(`本地迁移文件总数: ${allFiles.length}`);
console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`);
console.log(`未执行 (pending): ${pending.length}`);
console.log(`===============================\n`);
if (pending.length === 0) {
console.log('✅ 所有迁移脚本均已执行,无 pending migration。');
} else {
console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`);
pending.forEach((f, i) => {
console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`);
});
// 额外检查:有没有本地没有但 DB 已记录的(可能被删除了)
const localSet = new Set(allFiles);
const orphanInDb = appliedNames.filter(n => !localSet.has(n));
if (orphanInDb.length > 0) {
console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`);
orphanInDb.forEach(n => console.log(` - ${n}`));
}
}
await sequelize.close();
console.log('\n[DONE] 检查完成');
}
main().catch(err => {
console.error('脚本执行异常:', err);
process.exit(1);
});