Compare commits

...

6 Commits

Author SHA1 Message Date
liufumingren
b436b6dd9e feat: 拦截链路全流程完善 — 新增interceptScan + 运单表同步 + 工单通知
新增:
- order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态
- afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群

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

文档:
- methods/system.json: interceptScan + confirmIntercept 完整API文档
- methods/changes/system.json: 变更记录
2026-08-12 20:47:19 +08:00
liufumingren
4c5807dbbc fix: 修复detail返回结构和transfer参数名
- detail返回{after_sale,steps}包装结构

- transfer入参名target_role_group改为role_group

- 集成测试8/8全部通过
2026-08-09 21:30:52 +08:00
liufumingren
296536c83e feat: 售后模块V2全面落地
数据库:

- 创建 wms_after_sale 主表 (36字段/16索引)

- 创建 wms_after_sale_detail 步骤表 (11字段/3索引)

- 插入售后权限 16条 (ID 508-523)

- 绑定6个角色权限 (客服/仓库/生产主管/拣货组长)

代码:

- Model: after_sale.js + after_sale_detail.js (含常量枚举)

- Service: systemMethods/afterSale.js + systems/afterSale.js (19方法)

文档:

- API定义: methods/system.json (+9 methods)

- 设计文档: database/designs/after-sale-v2-design.md

- 开发/生产环境均已执行迁移,权限ID完全一致
2026-08-09 21:17:34 +08:00
liufumingren
0c2b062658 chore: 移除售后工单模块 (after_sale_work_order)
- 删除 model: after_sale_work_order.js, after_sale_work_order_step.js

- 删除旧迁移: 20260728120000, 20260728130000

- 删除设计文档: after-sale-work-order-design.md, after-sale-api-design.md

- 新增 DROP TABLE 迁移: 20260809120000

- 开发/生产环境均已执行 DROP 迁移,两表已删除
2026-08-09 16:21:04 +08:00
liufumingren
3e7c9a7a10 fix: 修复 docs 页面 JS 失效 + 入库 locked_quantity 流水补全 + stock_store 查询条件补全 is_valid
1. docs.js: 修复模板字面量中 '\n' 被服务端解释为换行符导致客户端 JS SyntaxError,所有交互功能失效(搜索/发送按钮)
2. inbound_direct_log.js: batch_no 修正为 effectiveBatchNo;storage 表更新时补全 before_locked_quantity/after_locked_quantity;新增 stock_id 归属校验
3. stock_store.js: 多处查询/更新补全 is_valid='Y' 过滤条件,避免软删除/失效数据泄露或误操作
4. storage/entry.js: 入库完成时补全 storage 表 before_locked_quantity/after_locked_quantity 流水字段
2026-08-09 00:23:42 +08:00
liufumingren
358fef0f71 chore: apply ESLint auto-fixes, JSDoc additions, and CRLF→LF normalization (no logic changes) 2026-08-08 20:28:18 +08:00
91 changed files with 9725 additions and 2588 deletions

View File

@ -2043,7 +2043,7 @@ Content-Type: application/json
}).then(function(res) {
return res.text().then(function(txt) { return { status: res.status, body: txt }; });
}).then(function(r) {
resultEl.textContent = 'HTTP ' + r.status + '\n' + r.body;
resultEl.textContent = 'HTTP ' + r.status + '\\n' + r.body;
resultEl.className = r.status === 200 ? 'req-result success' : 'req-result error';
}).catch(function(err) {
resultEl.textContent = '推送失败: ' + err.message;

View File

@ -1253,6 +1253,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
* @param {string[]} warnings 风险提示列表。
* @param {Object} policyConfig 策略配置对象。
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
* @param extraCustomLines
*/
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) {
if (platform !== 'kuaishou') {
@ -1402,6 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param extraCustomLines
*/
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
if (platform !== 'pdd') {
@ -1724,6 +1726,7 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
* @param {Object} policyConfig 策略配置对象。
* @param {string} customControlTemplateURL 菜鸟自定义区模板地址。
* @param {string[]} warnings 风险提示列表。
* @param extraCustomLines
*/
function applyCainiaoExpressFieldMapping(
platform,
@ -1934,6 +1937,7 @@ function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) {
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string[]} warnings 风险提示列表。
* @param extraCustomLines
*/
function applyXhsExpressFieldMapping(
platform,
@ -2036,6 +2040,7 @@ function applyXhsExpressFieldMapping(
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param extraCustomLines
*/
function applySphExpressFieldMapping(
platform,
@ -2176,6 +2181,7 @@ function resolveJdTemplateUrlFromOrderExpress(orderExpress) {
* @param {Object} policyConfig 策略配置对象。
* @param {Object} templateSample 模板样例对象。
* @param {string[]} warnings 风险提示列表。
* @param extraCustomLines
*/
function applyJdExpressFieldMapping(
platform,

434
app/model/after_sale.js Normal file
View File

@ -0,0 +1,434 @@
'use strict';
/**
* 售后主表 Model,基于 `wms_after_sale` 表。
* @param {import('egg').Application} app Egg 应用实例
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 售后 Model(含常量挂载)
*/
module.exports = app => {
const { STRING, BIGINT, INTEGER, DECIMAL, TEXT, TINYINT, DATE } = app.Sequelize;
// ============================
// 枚举常量定义
// ============================
/**
* 售后类型 + 子类型枚举,按业务单据维度分类。
* @type {Array<{name: string, type: string, subType: Array<{name: string, value: string}>}>}
*/
const AFTER_SALE_TYPES = [
{
name: '订单',
type: 'order',
subType: [
{ name: '破损', value: 'damage' },
{ name: '少发', value: 'missing_item' },
{ name: '错发', value: 'mis_shipment' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '发货延迟', value: 'delivery_delay' },
{ name: '物流异常', value: 'logistics_issue' },
{ name: '客户拒收', value: 'rejected' },
{ name: '拦截', value: 'intercept' },
{ name: '核实签收', value: 'verify_delivery' },
{ name: '催件', value: 'urge' },
{ name: '多发', value: 'extra_item' },
{ name: '改地址', value: 'change_address' },
{ name: '换快递', value: 'change_carrier' },
{ name: '重量异常', value: 'weight_issue' },
{ name: '运费争议', value: 'freight_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '收货单',
type: 'receiving',
subType: [
{ name: '少货', value: 'shortage' },
{ name: '破损', value: 'damage' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '入库单',
type: 'entry',
subType: [
{ name: '少货', value: 'shortage' },
{ name: '破损', value: 'damage' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '出库单',
type: 'stockout',
subType: [
{ name: '退货异常', value: 'return_issue' },
{ name: '错发', value: 'wrong_outbound' },
{ name: '少发', value: 'shortage' },
{ name: '其他', value: 'other' },
],
},
];
/**
* 售后处理角色组枚举。
* @type {{customer_service: string, warehouse: string, finance: string}}
*/
const AFTER_SALE_ROLE_GROUPS = {
customer_service: '客服组',
warehouse: '仓库组',
finance: '财务组',
};
/**
* 售后单状态枚举。
* @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}}
*/
const AFTER_SALE_STATUS = {
pending: '待处理',
processing: '处理中',
pending_feedback: '等待外部反馈',
completed: '已完成',
closed: '已关闭',
cancelled: '已取消',
};
/**
* 理赔状态枚举(仓库理赔 & 运方理赔通用)。
* @type {{pending: string, reviewing: string, approved: string, paid: string, monthly: string, rejected: string}}
*/
const CLAIM_STATUS = {
pending: '待理赔',
reviewing: '审核中',
approved: '已通过',
paid: '已打款',
monthly: '月结',
rejected: '已拒绝',
};
// ============================
// Model 定义
// ============================
const AfterSale = app.model.define('after_sale', {
/** 主键 */
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
/** 仓库ID */
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
/** 货主ID */
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID',
},
/** 售后单号,唯一 */
after_sale_no: {
type: STRING(50),
allowNull: false,
comment: '售后单号,唯一。生成规则:前缀AS + 日期YYYYMMDD + 6位序号',
},
/** 售后类型 */
type: {
type: STRING(20),
allowNull: false,
comment: '售后类型:order=订单, receiving=收货单, entry=入库单, stockout=出库单',
},
/** 售后子类型 */
sub_type: {
type: STRING(50),
allowNull: false,
comment: '售后子类型,与 type 组成二级分类',
},
/** 售后状态 */
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消',
},
/** 优先级 */
priority: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '优先级,数值越大越优先(0=普通,10=紧急)',
},
/** 售后标题 */
title: {
type: STRING(200),
allowNull: false,
comment: '售后标题(简要描述)',
},
/** 售后详细描述 */
description: {
type: TEXT,
allowNull: true,
comment: '售后详细描述',
},
/** 创建人账户ID */
creator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人账户ID(关联 accounts 表)',
},
/** 关联站内信消息ID */
inbox_message_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '关联 wms_inbox_message.id,为空表示无关联信息',
},
/** 当前处理角色组 */
role_group: {
type: STRING(50),
allowNull: true,
comment: '当前处理角色组:customer_service=客服组, warehouse=仓库组, finance=财务组。NULL 表示未分配',
},
/** 最终处理结果说明 */
resolution: {
type: TEXT,
allowNull: true,
comment: '最终处理结果说明',
},
/** 完结时间 */
resolved_at: {
type: DATE,
allowNull: true,
comment: '完结时间(状态变为 completed 时写入)',
},
/** 下次跟进时间 */
followup_at: {
type: DATE,
allowNull: true,
comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进',
},
/** 仓库理赔标记 */
claim_needed: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '仓库理赔标记:0=不需要,1=需要',
},
/** 仓库理赔金额(元) */
claim_amount: {
type: DECIMAL(12, 2),
allowNull: true,
comment: '仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写',
},
/** 仓库理赔状态 */
claim_status: {
type: STRING(20),
allowNull: true,
comment: '仓库理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝',
},
/** 运方理赔标记 */
carrier_claim_needed: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '运方理赔标记:0=不需要,1=需要',
},
/** 运方理赔金额(元) */
carrier_claim_amount: {
type: DECIMAL(12, 2),
allowNull: true,
comment: '运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写',
},
/** 运方理赔状态 */
carrier_claim_status: {
type: STRING(20),
allowNull: true,
comment: '运方理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝',
},
// ========== 单据关联字段(替代旧版多态关联) ==========
/** 运单ID */
waybill_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '运单ID(关联 wms_order_express.id)',
},
/** 运单号(冗余) */
waybill_no: {
type: STRING(50),
allowNull: true,
comment: '运单号(冗余字段,方便查询展示)',
},
/** 订单ID */
order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '订单ID(关联 wms_order.id),快递反馈建单时从 wms_order_express.order_id 填入',
},
/** 发货订单ID */
order_delivery_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '发货订单ID(关联 wms_order_delivery.id)',
},
/** 发货订单号(冗余) */
order_delivery_no: {
type: STRING(50),
allowNull: true,
comment: '发货订单号(冗余字段)',
},
/** 入库单ID */
entry_order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '入库单ID(关联 wms_entry_order.id)',
},
/** 入库单号(冗余) */
entry_order_no: {
type: STRING(50),
allowNull: true,
comment: '入库单号(冗余字段)',
},
/** 出库单/退货出库单ID */
order_stockout_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '出库单/退货出库单ID(关联 wms_order_stockout.id)',
},
/** 出库单号(冗余) */
order_stockout_no: {
type: STRING(50),
allowNull: true,
comment: '出库单号(冗余字段)',
},
/** 收货单ID */
receiving_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '收货单ID(关联 wms_receiving.id)',
},
/** 收货单号(冗余) */
receiving_no: {
type: STRING(50),
allowNull: true,
comment: '收货单号(冗余字段)',
},
/** 创建时间 */
created_at: {
type: DATE,
allowNull: true,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
/** 更新时间 */
updated_at: {
type: DATE,
allowNull: true,
comment: '更新时间',
},
/** 软删除时间 */
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale',
comment: '售后主表',
timestamps: false,
indexes: [
{
name: 'uk_after_sale_no',
unique: true,
fields: [ 'after_sale_no' ],
},
{
name: 'idx_warehouse_status',
fields: [ 'warehouse_id', 'status', 'deleted_at' ],
},
{
name: 'idx_warehouse_type',
fields: [ 'warehouse_id', 'type', 'deleted_at' ],
},
{
name: 'idx_type_subtype',
fields: [ 'warehouse_id', 'type', 'sub_type', 'deleted_at' ],
},
{
name: 'idx_store_id',
fields: [ 'store_id', 'deleted_at' ],
},
{
name: 'idx_creator_id',
fields: [ 'creator_id', 'deleted_at' ],
},
{
name: 'idx_role_group',
fields: [ 'role_group', 'status', 'deleted_at' ],
},
{
name: 'idx_created_at',
fields: [ 'warehouse_id', 'created_at' ],
},
{
name: 'idx_waybill_id',
fields: [ 'waybill_id' ],
},
{
name: 'idx_order_delivery_id',
fields: [ 'order_delivery_id' ],
},
{
name: 'idx_entry_order_id',
fields: [ 'entry_order_id' ],
},
{
name: 'idx_order_stockout_id',
fields: [ 'order_stockout_id' ],
},
{
name: 'idx_receiving_id',
fields: [ 'receiving_id' ],
},
{
name: 'idx_carrier_claim_status',
fields: [ 'carrier_claim_status' ],
},
{
name: 'idx_inbox_message_id',
fields: [ 'inbox_message_id' ],
},
],
});
// ============================
// 关联关系
// ============================
AfterSale.associate = function() {
const { AfterSale, AfterSaleDetail } = app.model;
// 关联售后进度步骤(一对多)
AfterSale.hasMany(AfterSaleDetail, {
foreignKey: 'after_sale_id',
as: 'details',
});
};
// ============================
// 常量挂载到 Model
// ============================
AfterSale.AFTER_SALE_TYPES = AFTER_SALE_TYPES;
AfterSale.AFTER_SALE_ROLE_GROUPS = AFTER_SALE_ROLE_GROUPS;
AfterSale.AFTER_SALE_STATUS = AFTER_SALE_STATUS;
AfterSale.CLAIM_STATUS = CLAIM_STATUS;
return AfterSale;
};

View File

@ -0,0 +1,144 @@
'use strict';
/**
* 售后进度步骤表 Model,基于 `wms_after_sale_detail` 表。
* @param {import('egg').Application} app Egg 应用实例
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 售后进度步骤 Model(含常量挂载)
*/
module.exports = app => {
const { STRING, BIGINT, TEXT, DATE } = app.Sequelize;
// ============================
// 枚举常量定义
// ============================
/**
* 步骤状态枚举(与 wms_after_sale.status 一致)。
*/
const STEP_STATUS = {
pending: '待处理',
processing: '处理中',
pending_feedback: '等待外部反馈',
completed: '已完成',
closed: '已关闭',
cancelled: '已取消',
};
// ============================
// Model 定义
// ============================
const AfterSaleDetail = app.model.define('after_sale_detail', {
/** 主键 */
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
/** 关联售后主表ID */
after_sale_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联售后主表ID(wms_after_sale.id)',
},
/** 步骤记录时售后主表的状态 */
step_status: {
type: STRING(20),
allowNull: false,
defaultValue: 'processing',
comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled',
},
/** 操作人账户ID */
operator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作人账户ID(关联 accounts 表);外部系统回调/自动触发的步骤可为空',
},
/** 操作人信息快照 */
operator_snapshot: {
type: TEXT,
allowNull: true,
comment: '操作人信息快照(JSON),如 {"name":"张三","role":"客服"},防止账户删除后历史丢失',
},
/** 操作动作描述 */
action: {
type: STRING(100),
allowNull: true,
comment: '操作动作描述,如"确认收货"、"审核驳回"、"发起退款"',
},
/** 处理备注 */
remark: {
type: TEXT,
allowNull: true,
comment: '处理备注',
},
/** 步骤开始时间 */
started_at: {
type: DATE,
allowNull: true,
comment: '步骤开始时间',
},
/** 步骤完成时间 */
completed_at: {
type: DATE,
allowNull: true,
comment: '步骤完成时间',
},
/** 创建时间 */
created_at: {
type: DATE,
allowNull: true,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
/** 更新时间 */
updated_at: {
type: DATE,
allowNull: true,
comment: '更新时间',
},
/** 软删除时间 */
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale_detail',
comment: '售后进度步骤表',
timestamps: false,
indexes: [
{
name: 'idx_after_sale_id',
fields: [ 'after_sale_id' ],
},
{
name: 'idx_operator_id',
fields: [ 'operator_id' ],
},
],
});
// ============================
// 关联关系
// ============================
AfterSaleDetail.associate = function() {
const { AfterSale, AfterSaleDetail } = app.model;
// 关联售后主表(多对一)
AfterSaleDetail.belongsTo(AfterSale, {
foreignKey: 'after_sale_id',
as: 'afterSale',
});
};
// ============================
// 常量挂载到 Model
// ============================
AfterSaleDetail.STEP_STATUS = STEP_STATUS;
return AfterSaleDetail;
};

View File

@ -1,267 +0,0 @@
'use strict';
module.exports = app => {
const { STRING, BIGINT, INTEGER, TINYINT, TEXT, DATE, DECIMAL } = app.Sequelize;
/**
* 售后工单业务类型定义
* 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问
* 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE
*/
const BUSINESS_TYPES = {
waybill: {
label: '运单',
table: 'wms_order_express',
subtypes: {
intercept: '拦截',
urge: '催件',
damage: '破损',
lost: '丢件',
wrong_info: '信息错误',
},
},
order_delivery: {
label: '发货订单',
table: 'wms_order_delivery',
subtypes: {
mis_shipment: '错发',
missing_item: '少发',
wrong_sku: '错品',
quality_issue: '质量问题',
delivery_delay: '发货延迟',
},
},
entry_order: {
label: '入库单',
table: 'wms_entry_order',
subtypes: {
shortage: '少货',
damage: '破损',
wrong_sku: '错品',
quality_issue: '质量问题',
},
},
order_stockout: {
label: '出库单/退货出库单',
table: 'wms_order_stockout',
subtypes: {
return_issue: '退货异常',
wrong_outbound: '错发',
shortage: '少发',
},
},
receiving: {
label: '收货单',
table: 'wms_receiving',
subtypes: {
shortage: '少货',
damage: '破损',
quality_issue: '质量问题',
},
},
other: {
label: '其他',
table: null,
subtypes: {
general: '通用',
},
},
};
/**
* 根据 business_type 获取关联表名
* @param {string} businessType 业务类型
* @returns {string|null} 关联表名
*/
function getBusinessTable(businessType) {
return BUSINESS_TYPES[businessType]?.table || null;
}
/**
* 校验 business_type + business_sub_type 组合是否合法
* @param {string} businessType 业务类型
* @param {string} businessSubType 业务子类型
* @returns {boolean} 是否合法
*/
function isValidSubType(businessType, businessSubType) {
const def = BUSINESS_TYPES[businessType];
return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType);
}
const AfterSaleWorkOrder = app.model.define('after_sale_work_order', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '货主ID',
},
work_order_no: {
type: STRING(50),
allowNull: false,
comment: '售后工单号,唯一',
},
business_type: {
type: STRING(50),
allowNull: false,
comment: '关联业务类型',
},
business_sub_type: {
type: STRING(50),
allowNull: false,
comment: '关联业务子类型',
},
business_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联业务单据主键ID(多态关联)',
},
business_no: {
type: STRING(100),
allowNull: true,
comment: '关联业务单据号(冗余)',
},
direction: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '记账方向:0=未确定 1=入库 2=出库',
},
status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '工单状态:0=待处理 1=处理中 2=已完成 3=已关闭 9=已取消',
},
priority: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 50,
comment: '优先级:1~100,数字越大优先级越高',
},
title: {
type: STRING(200),
allowNull: false,
comment: '工单标题/摘要',
},
description: {
type: TEXT,
allowNull: true,
comment: '问题描述',
},
creator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人ID,关联 account.id;0 表示 AI 自动接待',
},
creator_snapshot: {
type: TEXT,
allowNull: true,
comment: '创建人信息快照(JSON格式);AI创建时记录模型/会话信息',
},
assignee_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '当前处理人ID,关联 account.id',
},
parent_work_order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '父工单ID,自关联本表;非空时表示子工单',
},
current_step: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '当前进度,值为当前正在处理的 step_order 序号',
},
claim_needed: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '是否需要理赔:0=不需要 1=需要',
},
claim_amount: {
type: DECIMAL(12, 2),
allowNull: true,
defaultValue: 0.00,
comment: '理赔金额(元)',
},
claim_status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '理赔状态:0=未理赔 1=已理赔(单笔结清) 2=月结',
},
resolution: {
type: TEXT,
allowNull: true,
comment: '处理结果说明',
},
resolved_at: {
type: DATE,
allowNull: true,
comment: '解决时间',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale_work_order',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '售后工单主表',
});
AfterSaleWorkOrder.associate = () => {
// 自关联:父工单 → 子工单
AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrder, {
foreignKey: 'parent_work_order_id',
sourceKey: 'id',
as: 'children',
});
AfterSaleWorkOrder.belongsTo(app.model.AfterSaleWorkOrder, {
foreignKey: 'parent_work_order_id',
targetKey: 'id',
as: 'parent',
});
// 关联进度步骤表
AfterSaleWorkOrder.hasMany(app.model.AfterSaleWorkOrderStep, {
foreignKey: 'work_order_id',
sourceKey: 'id',
as: 'steps',
});
};
// 挂载业务类型常量及辅助函数到 Model
AfterSaleWorkOrder.BUSINESS_TYPES = BUSINESS_TYPES;
AfterSaleWorkOrder.getBusinessTable = getBusinessTable;
AfterSaleWorkOrder.isValidSubType = isValidSubType;
return AfterSaleWorkOrder;
};

View File

@ -1,99 +0,0 @@
'use strict';
module.exports = app => {
const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize;
const AfterSaleWorkOrderStep = app.model.define('after_sale_work_order_step', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键ID',
},
work_order_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工单ID,关联 wms_after_sale_work_order.id',
},
step_order: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '步骤序号(从1开始递增)',
},
step_name: {
type: STRING(100),
allowNull: false,
comment: '步骤名称',
},
step_status: {
type: TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过',
},
operator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作员工ID,关联 account.id',
},
operator_snapshot: {
type: TEXT,
allowNull: true,
comment: '操作人信息快照(JSON格式)',
},
action: {
type: STRING(100),
allowNull: true,
comment: '操作动作描述',
},
remark: {
type: TEXT,
allowNull: true,
comment: '处理备注',
},
started_at: {
type: DATE,
allowNull: true,
comment: '步骤开始时间',
},
completed_at: {
type: DATE,
allowNull: true,
comment: '步骤完成时间',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_after_sale_work_order_step',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '售后工单进度步骤表',
});
AfterSaleWorkOrderStep.associate = () => {
AfterSaleWorkOrderStep.belongsTo(app.model.AfterSaleWorkOrder, {
foreignKey: 'work_order_id',
targetKey: 'id',
as: 'workOrder',
});
};
return AfterSaleWorkOrderStep;
};

View File

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

View File

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

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

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

File diff suppressed because it is too large Load Diff

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

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -151,7 +151,7 @@ class expressInterfaceService extends MainService {
// 并行调用 getShopExpressList,构建 Map<shopId, expressList>
const shopExpressMap = new Map();
const shopResults = await Promise.all(
shopIds.map(async (shopId) => {
shopIds.map(async shopId => {
try {
const shopExpressResult = await ctx.service.systemMethods.index.getShopExpressList({
shop_id: shopId,

View File

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

View File

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

View File

@ -51,6 +51,7 @@ class StoreWarehouseWarehouseService extends MainService {
/**
* 仓库侧发起签约。
* @param data
*/
async sign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;
@ -68,6 +69,7 @@ class StoreWarehouseWarehouseService extends MainService {
/**
* 仓库侧确认签约。
* @param data
*/
async confirmSign(data = {}) {
const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse;

View File

@ -14,6 +14,7 @@ class WorkbenchService extends MainService {
/**
* 工作台列表(分页 + 筛选)
* @param data
*/
async list(data) {
const { service } = this;
@ -27,6 +28,7 @@ class WorkbenchService extends MainService {
/**
* 工作台详情
* @param data
*/
async detail(data) {
const { service } = this;
@ -42,6 +44,7 @@ class WorkbenchService extends MainService {
/**
* 创建工作台
* @param data
*/
async create(data) {
const { service } = this;
@ -55,6 +58,7 @@ class WorkbenchService extends MainService {
/**
* 更新工作台
* @param data
*/
async update(data) {
const { service } = this;
@ -70,6 +74,7 @@ class WorkbenchService extends MainService {
/**
* 删除工作台(软删除)
* @param data
*/
async delete(data) {
const { service } = this;
@ -102,6 +107,7 @@ class WorkbenchService extends MainService {
/**
* 工作台绑定摄像头
* @param data
*/
async bindCamera(data) {
const { service } = this;
@ -117,6 +123,7 @@ class WorkbenchService extends MainService {
/**
* 检查条码是否已存在
* @param data
*/
async checkBarcode(data) {
const { service } = this;

File diff suppressed because it is too large Load Diff

View File

@ -1161,7 +1161,7 @@ class DeliveryOrderService extends Service {
isUrgency,
invoiceFlag,
receiverInfo,
sourceOrderCode
sourceOrderCode,
} = deliveryOrder;
const policyConfig = await this.getStoreWarehousePolicyConfig(info.storeId, info.warehouseId);

View File

@ -780,8 +780,8 @@ class ExpressPlatformService extends MainService {
labelformat: listByWarehousePlatformCode.labelformat || '',
extraInfo: ExpressList.find(item => item.code === listByWarehousePlatformCode.sys_express_code)?.polyapi_extra_info || '',
};
console.log("matchedPlatform.platid",matchedPlatform.platid);
console.log("startPlayload",playload);
console.log('matchedPlatform.platid', matchedPlatform.platid);
console.log('startPlayload', playload);
if (Number(matchedPlatform.platid) === 673) {
playload.BizVersion = '2';
@ -919,7 +919,7 @@ class ExpressPlatformService extends MainService {
api: 'Differ.JH.Logistics.PostOrder',
response: JSON.stringify(result),
});
console.log("分配运单号结果",result);
console.log('分配运单号结果', result);
// 统一处理:不再依赖顶层 code,直接从 results 逐条提取 issuccess 和 submessage
{
@ -1109,14 +1109,14 @@ class ExpressPlatformService extends MainService {
eCustomerCode: '',
remark: '',
selleruserid: '',
printno: "",
printno: '',
iscloudprint: 'false',
needprintdetail: 'false',
extenddata: '',
providercode: String(item.procode || item.realcpcode || item.logisticcompanycode || ''),
packageno: '',
fontsize: '',
platorderno: "",
platorderno: '',
sipshopid: 0,
}));
console.log('京东批量打印请求参数', JSON.stringify({

View File

@ -1042,7 +1042,7 @@ class InboundDirectLogService extends Service {
where: {
space_id: spaceId,
stock_id: stockId,
batch_no: batchNo,
batch_no: effectiveBatchNo,
inventory_type: inventoryType,
is_enabled: 1,
delete_at: null,
@ -1054,10 +1054,20 @@ class InboundDirectLogService extends Service {
let sId = null;
let sBeforeQty = 0;
let sAfterQty = 0;
let sBeforeLockedQty = 0;
let sAfterLockedQty = 0;
if (sRecord) {
if (Number(sRecord.stock_id) !== Number(stockId)) {
throw new Error(
`入库库存归属冲突: storage_id=${sRecord.id} 当前 stock_id=${sRecord.stock_id}, ` +
`本次入库 stock_id=${stockId}, space_id=${spaceId}, batch_no=${effectiveBatchNo}`
);
}
sBeforeQty = Number(sRecord.quantity) || 0;
sAfterQty = sBeforeQty + qty;
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
sAfterLockedQty = sBeforeLockedQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${qty}`),
@ -1077,6 +1087,8 @@ class InboundDirectLogService extends Service {
} else {
sBeforeQty = 0;
sAfterQty = qty;
sBeforeLockedQty = 0;
sAfterLockedQty = 0;
const createdStorage = await ctx.model.Storage.create({
warehouse_id: warehouseId,
@ -1114,6 +1126,8 @@ class InboundDirectLogService extends Service {
quantity: qty,
before_quantity: sBeforeQty,
after_quantity: sAfterQty,
before_locked_quantity: sBeforeLockedQty,
after_locked_quantity: sAfterLockedQty,
batch_no: effectiveBatchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

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

View File

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

View File

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

View File

@ -59,6 +59,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
required: false,
description: '订单备注命中任一关键字时,跳过自动分配快递,默认 [](不排除任何订单)',
}),
Object.freeze({
key: 'inbox_reply_exclude_keywords',
name: '排除快递回复关键词',
type: 'string_array',
default: [],
required: false,
description: '消息命中任一关键词时仅记录工单不发送回信通知,默认 [](正常回信)',
}),
Object.freeze({
key: 'default_express_code',
name: '默认快递编码',
@ -228,6 +236,55 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
max: '23:59',
description: '截单时间,格式 HH:mm,如 18:00',
}),
Object.freeze({
key: 'after_sale_followup_hours',
name: '售后跟进时间(h)',
type: 'object',
required: false,
description: '按售后类型+子类型设置跟进小时数。_default 为该类型默认值,具体子类型可覆盖',
item_keys: [
Object.freeze({ key: 'order', name: '订单售后', type: 'object', required: false, description: '订单类型跟进配置',
item_keys: [
Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }),
Object.freeze({ key: 'intercept', name: '拦截', type: 'integer', default: 4, min: 1, max: 720 }),
Object.freeze({ key: 'urge', name: '催件', type: 'integer', default: 4, min: 1, max: 720 }),
Object.freeze({ key: 'change_address', name: '改地址', type: 'integer', default: 8, min: 1, max: 720 }),
Object.freeze({ key: 'change_carrier', name: '换快递', type: 'integer', default: 8, min: 1, max: 720 }),
Object.freeze({ key: 'delivery_delay', name: '发货延迟', type: 'integer', default: 12, min: 1, max: 720 }),
Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }),
Object.freeze({ key: 'quality_issue', name: '质量问题', type: 'integer', default: 48, min: 1, max: 720 }),
Object.freeze({ key: 'missing_item', name: '少发', type: 'integer', default: 24, min: 1, max: 720 }),
],
}),
Object.freeze({ key: 'receiving', name: '收货单售后', type: 'object', required: false, description: '收货单类型跟进配置',
item_keys: [
Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }),
Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }),
Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }),
],
}),
Object.freeze({ key: 'entry', name: '入库单售后', type: 'object', required: false, description: '入库单类型跟进配置',
item_keys: [
Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }),
Object.freeze({ key: 'shortage', name: '少货', type: 'integer', default: 48, min: 1, max: 720 }),
Object.freeze({ key: 'damage', name: '破损', type: 'integer', default: 48, min: 1, max: 720 }),
],
}),
Object.freeze({ key: 'stockout', name: '出库单售后', type: 'object', required: false, description: '出库单类型跟进配置',
item_keys: [
Object.freeze({ key: '_default', name: '默认', type: 'integer', default: 24, min: 1, max: 720 }),
Object.freeze({ key: 'return_issue', name: '退货异常', type: 'integer', default: 48, min: 1, max: 720 }),
Object.freeze({ key: 'shortage', name: '少发', type: 'integer', default: 48, min: 1, max: 720 }),
],
}),
],
default: Object.freeze({
order: Object.freeze({ _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 }),
receiving: Object.freeze({ _default: 24, shortage: 48, damage: 48 }),
entry: Object.freeze({ _default: 24, shortage: 48, damage: 48 }),
stockout: Object.freeze({ _default: 24, return_issue: 48, shortage: 48 }),
}),
}),
Object.freeze({
key: INTERNAL_WAVE_STRATEGY_VERSION_KEY,
name: '仓库波次策略版本号',

View File

@ -1437,6 +1437,7 @@ class stockStoreService extends Service {
warehouse_id: warehouseId,
store_id: sourceData.store_id,
deleted_at: null,
is_valid: 'Y',
},
attributes: [ 'id' ],
raw: true,
@ -1548,6 +1549,7 @@ class stockStoreService extends Service {
goods_code: sourceData.goods_code,
warehouse_id: warehouseId,
is_valid: 'Y',
deleted_at: null,
},
attributes: [ 'id' ],
raw: true,
@ -1599,6 +1601,8 @@ class stockStoreService extends Service {
* @param {Object} sortParams - 排序参数
* @param {string} sortParams.sortField - 排序字段,默认'create_at'
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
* @param externalWarehouseId
* @param externalStoreId
* @return {Promise<Object>} 返回查询结果
*/
async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
@ -2555,7 +2559,8 @@ class stockStoreService extends Service {
where: {
id: { [Op.in]: ids },
warehouse_id: warehouseId,
delete_at: null,
deleted_at: null,
is_valid: 'Y',
},
attributes: [ 'id' ],
});
@ -2782,6 +2787,8 @@ class stockStoreService extends Service {
} else {
const StockWarehouseWhere = {
warehouse_id: warehouseId,
deleted_at: null,
is_valid: 'Y',
};
const StockStoreWhere = {};
if (store_id) {
@ -2903,6 +2910,7 @@ class stockStoreService extends Service {
where: {
warehouse_id: warehouseId,
deleted_at: null,
is_valid: 'Y',
id: warehouse_stock,
},
attributes: [
@ -2983,6 +2991,7 @@ class stockStoreService extends Service {
where: {
warehouse_id: warehouseId,
deleted_at: null,
is_valid: 'Y',
id,
},
attributes: [
@ -3076,6 +3085,7 @@ class stockStoreService extends Service {
where: {
id,
deleted_at: null,
is_valid: 'Y',
warehouse_id: ctx.user.store_id,
},
transaction,
@ -3323,6 +3333,7 @@ class stockStoreService extends Service {
store_id: owner_id,
warehouse_id,
deleted_at: null,
is_valid: 'Y',
};
if (item_id) {
@ -3368,6 +3379,7 @@ class stockStoreService extends Service {
[Op.and]: [
{ id: { [Op.in]: ids } },
{ deleted_at: null },
{ is_valid: 'Y' },
],
};
@ -3676,6 +3688,7 @@ class stockStoreService extends Service {
const whereCondition = {
warehouse_id: warehouseId,
deleted_at: null,
is_valid: 'Y',
};
// 如果有传入store_id,则添加store_id条件
@ -3921,6 +3934,7 @@ class stockStoreService extends Service {
id: stock_id,
warehouse_id: warehouseId,
deleted_at: null,
is_valid: 'Y',
},
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ],
raw: true,

View File

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

View File

@ -1553,10 +1553,14 @@ class EntryService extends Service {
let storageId = null;
let storageBeforeQty = 0;
let storageAfterQty = 0;
let storageBeforeLockedQty = 0;
let storageAfterLockedQty = 0;
if (storageRecord) {
storageBeforeQty = Number(storageRecord.quantity) || 0;
storageAfterQty = storageBeforeQty + planQty;
storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0;
storageAfterLockedQty = storageBeforeLockedQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${planQty}`),
@ -1573,6 +1577,8 @@ class EntryService extends Service {
} else {
storageBeforeQty = 0;
storageAfterQty = planQty;
storageBeforeLockedQty = 0;
storageAfterLockedQty = 0;
const createdStorage = await ctx.model.Storage.create({
warehouse_id: warehouseId,
@ -1608,6 +1614,8 @@ class EntryService extends Service {
quantity: planQty,
before_quantity: storageBeforeQty,
after_quantity: storageAfterQty,
before_locked_quantity: storageBeforeLockedQty,
after_locked_quantity: storageAfterLockedQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

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

View File

@ -328,6 +328,9 @@ class StorageReportService extends Service {
* @param {number[]} [options.storeIds=[]] 货主ID列表
* @param {number[]} [options.spaceIds=[]] 库位ID列表
* @param {boolean} [options.includeBarcode=false] 是否加载条码映射
* @param options.entryOrderIds
* @param options.orderIds
* @param options.warehouseId
* @return {Promise<Object>} 映射对象
*/
async loadReportReferenceMaps({

View File

@ -92,6 +92,8 @@ class StoreExpressBindingPolicyService extends Service {
/**
* 校验快递编码是否存在。
* @param {string} expressCode 快递编码
* @param value
* @param fieldName
* @return {Promise<string>} 标准化快递编码
*/
normalizeJsonArray(value, fieldName) {

View File

@ -1852,6 +1852,7 @@ class SettingStoreWarehouseService extends Service {
/**
* 精简签约对象,仅保留前端需要的字段。
* @param serialized
*/
trimContract(serialized) {
return {
@ -2198,7 +2199,7 @@ class SettingStoreWarehouseService extends Service {
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
// 批量查询账号姓名
let accountNameMap = {};
const accountNameMap = {};
if (accountIds.length > 0) {
try {
const accounts = await ctx.model.Account.findAll({

View File

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

View File

@ -1,644 +0,0 @@
# 售后工单 API 接口设计方案
> **状态**: ⏳ 等待人工审阅
> **设计日期**: 2026-07-29
> **设计人**: wms-db-agent
> **说明**: 本文档仅输出 API 接口设计方案,不直接修改程序代码。审阅通过后再执行实现。
---
## 一、模块概览
| 项目 | 说明 |
|------|------|
| 模块名 | `afterSale` |
| 接口路径 | `POST /system`,body 中 `method` 字段为 `afterSale.{方法名}` |
| 请求方式 | 全部 `POST`,参数放在 `body` 内 |
| 鉴权 | 除 `businessTypes` 外均需登录;写操作需鉴权 |
### 文件规划
```
app/service/systemMethods/afterSale.js ← 入口层(鉴权、参数校验、委托)
app/service/systems/afterSale.js ← 业务层(数据库操作、状态机)
methods/system.json ← API 文档(追加 afterSale group)
```
### 调用链路
```
POST /system { method: "afterSale.list", ... }
→ app/router.js
→ app/service/system.js
→ app/service/systemMethods/afterSale.js ← 鉴权 + 参数校验
→ app/service/systems/afterSale.js ← 业务逻辑 + DB操作
→ app/model/after_sale_work_order.js ← Sequelize Model
→ app/model/after_sale_work_order_step.js
```
---
## 二、接口清单(共 13 个)
| # | method | 描述 | 需登录 | 需鉴权 |
|---|--------|------|--------|--------|
| 1 | `afterSale.businessTypes` | 获取内置业务类型及子类型枚举 | ✗ | ✗ |
| 2 | `afterSale.list` | 工单列表(分页+筛选) | ✓ | ✗ |
| 3 | `afterSale.detail` | 工单详情(含步骤列表) | ✓ | ✗ |
| 4 | `afterSale.create` | 创建工单 | ✓ | ✓ |
| 5 | `afterSale.update` | 更新工单基本信息 | ✓ | ✓ |
| 6 | `afterSale.delete` | 删除工单(软删除) | ✓ | ✓ |
| 7 | `afterSale.assign` | 分配处理人 | ✓ | ✓ |
| 8 | `afterSale.complete` | 完成工单 | ✓ | ✓ |
| 9 | `afterSale.close` | 关闭工单 | ✓ | ✓ |
| 10 | `afterSale.cancel` | 取消工单 | ✓ | ✓ |
| 11 | `afterSale.stepStart` | 开始某个步骤 | ✓ | ✓ |
| 12 | `afterSale.stepComplete` | 完成某个步骤 | ✓ | ✓ |
| 13 | `afterSale.stepSkip` | 跳过某个步骤 | ✓ | ✓ |
---
## 三、接口详细设计
### 3.1 `afterSale.businessTypes` — 获取业务类型枚举
```json
{
"method": "afterSale.businessTypes",
"description": "获取售后工单内置业务类型及子类型枚举,供前端下拉选择使用。数据来源:app/model/after_sale_work_order.js 中的 BUSINESS_TYPES 常量。",
"isNeedAuth": false,
"isNeedLogin": false,
"params": [],
"response": [
{
"name": "data",
"type": "object",
"description": "业务类型枚举,key 为 business_type,value 含 label、table、subtypes",
"example": {
"waybill": {
"label": "运单",
"table": "wms_order_express",
"subtypes": {
"intercept": "拦截",
"urge": "催件",
"damage": "破损",
"lost": "丢件",
"wrong_info": "信息错误"
}
},
"order_delivery": {
"label": "发货订单",
"table": "wms_order_delivery",
"subtypes": {
"mis_shipment": "错发",
"missing_item": "少发",
"wrong_sku": "错品",
"quality_issue": "质量问题",
"delivery_delay": "发货延迟"
}
}
}
}
]
}
```
---
### 3.2 `afterSale.list` — 工单列表
```json
{
"method": "afterSale.list",
"description": "查询售后工单列表,支持分页与多条件筛选。仓库隔离(自动注入 warehouse_id)。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页参数 { page, pageSize },默认 page=1 pageSize=20"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "筛选条件,所有字段均为可选",
"children": [
{ "name": "workOrderNo", "type": "string", "description": "工单号(模糊搜索)" },
{ "name": "businessType", "type": "string", "description": "业务类型(等值),如 waybill" },
{ "name": "businessSubType","type": "string", "description": "业务子类型(等值),如 intercept" },
{ "name": "businessNo", "type": "string", "description": "关联业务单据号(模糊)" },
{ "name": "status", "type": "number", "description": "工单状态(等值):0/1/2/3/9" },
{ "name": "priorityMin", "type": "number", "description": "优先级下限(>=)" },
{ "name": "priorityMax", "type": "number", "description": "优先级上限(<=)" },
{ "name": "claimStatus", "type": "number", "description": "理赔状态(等值):0/1/2" },
{ "name": "assigneeId", "type": "number", "description": "处理人ID(等值)" },
{ "name": "creatorId", "type": "number", "description": "创建人ID(等值)" },
{ "name": "keyword", "type": "string", "description": "关键词:匹配工单号/标题/业务单据号" },
{ "name": "createdAtStart", "type": "string", "description": "创建时间起始(YYYY-MM-DD)" },
{ "name": "createdAtEnd", "type": "string", "description": "创建时间截止(YYYY-MM-DD)" }
]
},
{
"name": "sort",
"type": "object",
"required": false,
"source": "body",
"description": "排序 { field: 'priority'|'created_at'|'status', order: 'asc'|'desc' },默认 priority desc"
}
],
"response": [
{
"name": "list",
"type": "array",
"description": "工单列表(不含 description/resolution 长文本,减少传输量)",
"children": [
{ "name": "id", "type": "number", "description": "工单ID" },
{ "name": "work_order_no", "type": "string", "description": "工单号" },
{ "name": "warehouse_id", "type": "number", "description": "仓库ID" },
{ "name": "store_id", "type": "number", "description": "货主ID" },
{ "name": "business_type", "type": "string", "description": "业务类型" },
{ "name": "business_sub_type","type": "string", "description": "业务子类型" },
{ "name": "business_id", "type": "number", "description": "关联单据ID" },
{ "name": "business_no", "type": "string", "description": "关联单据号" },
{ "name": "direction", "type": "number", "description": "记账方向:0/1/2" },
{ "name": "status", "type": "number", "description": "工单状态:0/1/2/3/9" },
{ "name": "priority", "type": "number", "description": "优先级:1-100" },
{ "name": "title", "type": "string", "description": "工单标题" },
{ "name": "creator_id", "type": "number", "description": "创建人ID" },
{ "name": "creator_name", "type": "string", "description": "创建人姓名(JOIN account)" },
{ "name": "assignee_id", "type": "number", "description": "当前处理人ID" },
{ "name": "assignee_name", "type": "string", "description": "当前处理人姓名(JOIN account)" },
{ "name": "parent_work_order_id","type":"number","description": "父工单ID" },
{ "name": "current_step", "type": "number", "description": "当前进度步骤序号" },
{ "name": "claim_needed", "type": "number", "description": "是否理赔" },
{ "name": "claim_amount", "type": "number", "description": "理赔金额" },
{ "name": "claim_status", "type": "number", "description": "理赔状态" },
{ "name": "resolved_at", "type": "string", "description": "解决时间" },
{ "name": "created_at", "type": "string", "description": "创建时间" },
{ "name": "updated_at", "type": "string", "description": "更新时间" }
]
},
{ "name": "pagination", "type": "object", "description": "分页信息 { page, pageSize, total, totalPages }" }
]
}
```
---
### 3.3 `afterSale.detail` — 工单详情
```json
{
"method": "afterSale.detail",
"description": "查询单个工单详情,含完整字段 + 步骤列表。仓库隔离。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "工单ID(必填)"
}
],
"response": [
{
"name": "data",
"type": "object",
"description": "工单完整信息",
"children": [
{ "name": "id", "type": "number", "description": "工单ID" },
{ "name": "...", "type": "", "description": "同 list 接口所有字段" },
{ "name": "description", "type": "string", "description": "问题描述(详情接口返回)" },
{ "name": "resolution", "type": "string", "description": "处理结果说明(详情接口返回)" },
{ "name": "creator_snapshot", "type": "string", "description": "创建人信息快照" },
{ "name": "steps", "type": "array", "description": "步骤列表",
"children": [
{ "name": "id", "type": "number", "description": "步骤ID" },
{ "name": "step_order", "type": "number", "description": "步骤序号" },
{ "name": "step_name", "type": "string", "description": "步骤名称" },
{ "name": "step_status", "type": "number", "description": "步骤状态:0/1/2/3" },
{ "name": "operator_id", "type": "number", "description": "操作人ID" },
{ "name": "operator_name", "type": "string", "description": "操作人姓名" },
{ "name": "operator_snapshot","type": "string", "description": "操作人快照" },
{ "name": "action", "type": "string", "description": "操作动作" },
{ "name": "remark", "type": "string", "description": "处理备注" },
{ "name": "started_at", "type": "string", "description": "开始时间" },
{ "name": "completed_at", "type": "string", "description": "完成时间" },
{ "name": "created_at", "type": "string", "description": "创建时间" }
]
},
{ "name": "children", "type": "array", "description": "子工单列表(如有)" },
{ "name": "parent", "type": "object", "description": "父工单简要信息(如有)" }
]
}
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "404", "description": "工单不存在或无权访问" }
]
}
```
---
### 3.4 `afterSale.create` — 创建工单
```json
{
"method": "afterSale.create",
"description": "创建售后工单。自动生成工单号(AS+时间戳),自动设置 creator_id 和 warehouse_id。创建成功后返回工单详情。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{
"name": "business_type",
"type": "string",
"required": true,
"source": "body",
"description": "业务类型(必填),如 waybill、order_delivery"
},
{
"name": "business_sub_type",
"type": "string",
"required": true,
"source": "body",
"description": "业务子类型(必填),如 intercept、mis_shipment。需与 business_type 匹配(由 BUSINESS_TYPES 校验)"
},
{
"name": "business_id",
"type": "number",
"required": true,
"source": "body",
"description": "关联业务单据主键ID(必填)"
},
{
"name": "business_no",
"type": "string",
"required": false,
"source": "body",
"description": "关联业务单据号(可选,建议传入方便列表展示)"
},
{
"name": "direction",
"type": "number",
"required": false,
"source": "body",
"description": "记账方向:1=入库 2=出库,默认 0(未确定)"
},
{
"name": "priority",
"type": "number",
"required": false,
"source": "body",
"description": "优先级:1~100,默认 50。AI 创建时自动填入"
},
{
"name": "title",
"type": "string",
"required": true,
"source": "body",
"description": "工单标题(必填)"
},
{
"name": "description",
"type": "string",
"required": false,
"source": "body",
"description": "问题描述"
},
{
"name": "claim_needed",
"type": "number",
"required": false,
"source": "body",
"description": "是否需要理赔:0=否 1=是,默认 0"
},
{
"name": "claim_amount",
"type": "number",
"required": false,
"source": "body",
"description": "理赔金额,默认 0.00"
},
{
"name": "parent_work_order_id",
"type": "number",
"required": false,
"source": "body",
"description": "父工单ID(子工单场景),不传则为根工单"
}
],
"response": [
{
"name": "data",
"type": "object",
"description": "创建成功的工单详情(同 detail 接口返回结构)"
}
],
"errors": [
{ "code": "400", "description": "工单标题不能为空" },
{ "code": "400", "description": "业务类型或子类型不合法" },
{ "code": "400", "description": "父工单不存在" }
]
}
```
---
### 3.5 `afterSale.update` — 更新工单基本信息
```json
{
"method": "afterSale.update",
"description": "更新工单基本信息(标题、描述、优先级、记账方向、理赔信息)。不可修改 business_type/business_sub_type/business_id。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "title", "type": "string", "required": false, "source": "body", "description": "工单标题" },
{ "name": "description", "type": "string", "required": false, "source": "body", "description": "问题描述" },
{ "name": "priority", "type": "number", "required": false, "source": "body", "description": "优先级" },
{ "name": "direction", "type": "number", "required": false, "source": "body", "description": "记账方向" },
{ "name": "claim_needed", "type": "number", "required": false, "source": "body", "description": "是否需要理赔" },
{ "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "理赔金额" },
{ "name": "claim_status", "type": "number", "required": false, "source": "body", "description": "理赔状态" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "404", "description": "工单不存在或无权操作" }
]
}
```
---
### 3.6 `afterSale.delete` — 删除工单
```json
{
"method": "afterSale.delete",
"description": "软删除工单及其所有步骤。仅待处理(0)和已取消(9)状态的工单可删除。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" }
],
"response": [],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "处理中的工单不可删除" },
{ "code": "404", "description": "工单不存在或无权操作" }
]
}
```
---
### 3.7 `afterSale.assign` — 分配处理人
```json
{
"method": "afterSale.assign",
"description": "将工单分配给指定处理人。仅待处理(0)状态的工单可分配。分配后自动流转至处理中(1)。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "assignee_id", "type": "number", "required": true, "source": "body", "description": "处理人ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "分配备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "处理人ID不能为空" },
{ "code": "400", "description": "当前状态不可分配(非待处理状态)" }
]
}
```
---
### 3.8 `afterSale.complete` — 完成工单
```json
{
"method": "afterSale.complete",
"description": "完成工单。仅处理中(1)状态且所有步骤已完成/跳过的工单可完成。完成后自动设置 resolved_at。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "resolution", "type": "string", "required": false, "source": "body", "description": "处理结果说明" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可完成(非处理中状态)" },
{ "code": "400", "description": "仍有步骤未完成,请先完成所有步骤" }
]
}
```
---
### 3.9 `afterSale.close` — 关闭工单
```json
{
"method": "afterSale.close",
"description": "关闭工单。仅已完成(2)状态的工单可关闭。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "关闭备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可关闭(非已完成状态)" }
]
}
```
---
### 3.10 `afterSale.cancel` — 取消工单
```json
{
"method": "afterSale.cancel",
"description": "取消工单。仅待处理(0)和处理中(1)状态的工单可取消。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "number", "required": true, "source": "body", "description": "工单ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "取消原因" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的工单详情" }
],
"errors": [
{ "code": "400", "description": "工单ID不能为空" },
{ "code": "400", "description": "当前状态不可取消" }
]
}
```
---
### 3.11 `afterSale.stepStart` — 开始步骤
```json
{
"method": "afterSale.stepStart",
"description": "开始处理某个步骤。将步骤状态设为进行中(1),同时更新主表 current_step。同一时刻只允许一个步骤处于进行中。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填,wms_after_sale_work_order_step.id)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "已有其他步骤正在进行中" },
{ "code": "400", "description": "步骤当前状态不可开始" }
]
}
```
---
### 3.12 `afterSale.stepComplete` — 完成步骤
```json
{
"method": "afterSale.stepComplete",
"description": "完成某个步骤。将步骤状态设为已完成(2),记录操作人和完成时间。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" },
{ "name": "action", "type": "string", "required": false, "source": "body", "description": "操作动作描述" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "步骤当前状态不可完成(非进行中状态)" }
]
}
```
---
### 3.13 `afterSale.stepSkip` — 跳过步骤
```json
{
"method": "afterSale.stepSkip",
"description": "跳过某个步骤。将步骤状态设为已跳过(3)。仓库隔离。",
"isNeedAuth": true,
"isNeedLogin": true,
"params": [
{ "name": "step_id", "type": "number", "required": true, "source": "body", "description": "步骤ID(必填)" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "跳过原因" }
],
"response": [
{ "name": "data", "type": "object", "description": "更新后的步骤信息" }
],
"errors": [
{ "code": "400", "description": "步骤ID不能为空" },
{ "code": "400", "description": "步骤当前状态不可跳过" }
]
}
```
---
## 四、状态机约束(服务端校验规则)
| 操作 | 允许的当前状态 | 目标状态 |
|------|-------------|---------|
| `create` | — | `status=0`, `current_step=1` |
| `assign` | `status=0` | `status=1` |
| `delete` | `status=0` 或 `status=9` | 软删除 |
| `complete` | `status=1` + 所有步骤已完成/跳过 | `status=2`, `resolved_at=NOW()` |
| `close` | `status=2` | `status=3` |
| `cancel` | `status=0` 或 `status=1` | `status=9` |
| `stepStart` | `step_status=0` + 无其他进行中步骤 | `step_status=1`, `current_step=该step_order` |
| `stepComplete` | `step_status=1` | `step_status=2` |
| `stepSkip` | `step_status=0` | `step_status=3` |
---
## 五、methods/system.json 追加格式
在 `methods.system.json` 的 `methods.groups` 数组末尾追加:
```json
{
"groupName": "售后工单模块",
"module": "afterSale",
"list": [
{ "method": "afterSale.businessTypes", ... },
{ "method": "afterSale.list", ... },
{ "method": "afterSale.detail", ... },
{ "method": "afterSale.create", ... },
{ "method": "afterSale.update", ... },
{ "method": "afterSale.delete", ... },
{ "method": "afterSale.assign", ... },
{ "method": "afterSale.complete", ... },
{ "method": "afterSale.close", ... },
{ "method": "afterSale.cancel", ... },
{ "method": "afterSale.stepStart", ... },
{ "method": "afterSale.stepComplete", ... },
{ "method": "afterSale.stepSkip", ... }
]
}
```
(完整 JSON 定义见第三节各接口)
---
## 六、后续实现计划(审阅通过后执行)
| 步骤 | 文件 | 说明 |
|------|------|------|
| 1 | `app/service/systems/afterSale.js` | 业务层:数据库操作、状态机、工单号生成 |
| 2 | `app/service/systemMethods/afterSale.js` | 入口层:鉴权配置、参数校验、委托调用 |
| 3 | `methods/system.json` | 追加 `afterSale` group 的 13 个 method 文档 |
| 4 | `methods/changes/afterSale-20260729.json` | 接口变更记录 |
---
## 七、待确认事项
- [ ] **1. 模块名**:`afterSale` 是否合适?备选 `asWorkOrder`、`afterSaleWorkOrder`
- [ ] **2. 步骤操作是否需要独立接口**:`stepStart/stepComplete/stepSkip` 三个独立接口 vs 合并为一个 `stepUpdate`(传 status 参数)
- [ ] **3. `businessTypes` 接口免登录**:是否允许未登录用户获取业务类型枚举?
- [ ] **4. 步骤创建时机**:步骤是创建工单时自动初始化一组,还是由前端手动逐条添加?
- [ ] **5. 是否需要批量操作**:批量分配、批量关闭?
- [ ] **6. 是否需要操作日志**:是否复用 `operation_log` 记录关键状态变更?

View File

@ -0,0 +1,853 @@
# 售后模块 V2 设计方案
> **状态**: 📋 v1 初稿,待评审
> **设计日期**: 2026-08-09
> **设计人**: wms-doc-agent
> **模块**: 售后管理(After-Sale)
> **表**: 2 张 — `wms_after_sale`(售后主表)、`wms_after_sale_detail`(售后进度步骤表)
> **说明**: 本文档为全新设计,替代已移除的旧版 `wms_after_sale_work_order` + `wms_after_sale_work_order_step` 体系。
---
## 一、设计背景
### 1.1 旧版问题
旧版售后工单(`after_sale_work_order` + `after_sale_work_order_step`)已于 2026-08-09 通过迁移 `20260809120000-drop-wms-after-sale-work-order.js` 正式移除。旧版存在以下核心问题:
1. **多态关联难以维护**:使用 `business_type` + `business_sub_type` + `business_id` 三元组关联业务单据,导致:
- 查询需要动态拼接 JOIN 条件,性能差
- 无法利用数据库外键约束保证数据完整性
- 业务类型枚举膨胀,新增业务类型需改动多处代码
2. **不支持多单据共存**:一个售后单只能关联一种业务单据,实际场景中退货退款往往同时涉及运单、发货订单、收货单等多张单据
3. **覆盖场景不足**:旧版仅覆盖工单流转,未涵盖理赔、投诉等售后场景
4. **缺少明细层级**:无法记录售后单中的商品明细(退什么货、换什么货、赔多少钱)
### 1.2 V2 设计目标
| 目标 | 说明 |
|------|------|
| **废弃多态关联** | 每种业务单据使用独立字段,类型安全、查询高效 |
| **支持多单据共存** | 一个售后单可同时关联运单、发货订单、入库单、出库单、收货单等 |
| **覆盖全场景** | 按单据维度分类(订单/收货单/入库单/出库单),售后动作(退货/换货/理赔/投诉等)通过进度步骤体现 |
| **进度追溯** | `wms_after_sale_detail` 记录售后处理进度步骤,支持按步骤序号追踪操作人、操作动作、处理时间 |
| **可追溯** | 完整记录创建人、处理人、最终处理结果、完结时间 |
### 1.3 与旧版核心差异
| 维度 | 旧版(已移除) | V2(本设计) |
|------|---------------|-------------|
| 主表 | `wms_after_sale_work_order` | `wms_after_sale` |
| 子表 | `wms_after_sale_work_order_step`(工单步骤流转) | `wms_after_sale_detail`(售后进度步骤) |
| 单据关联 | 多态三元组 `business_type + business_sub_type + business_id` | 每种单据独立字段组,可多个同时有值 |
| 多单据共存 | ❌ 不支持 | ✅ 支持 |
| 理赔 | ❌ 不支持 | ✅ 内建仓库理赔(`claim_needed / claim_amount / claim_status`)和运方理赔(`carrier_claim_needed / carrier_claim_amount / carrier_claim_status`) |
| 进度步骤 | ❌ `after_sale_work_order_step` | ✅ `wms_after_sale_detail` 记录步骤序号/操作人/操作动作/耗时 |
| 商品明细 | ❌ 无 | ❌ 不再独立建表,商品明细可存入 `remark` 或扩展 JSON 字段 |
---
## 二、ER 图
```mermaid
erDiagram
wms_after_sale ||--o{ wms_after_sale_detail : "1:N"
wms_after_sale {
BIGINT id PK "主键"
BIGINT warehouse_id "仓库ID"
BIGINT store_id "货主ID"
VARCHAR after_sale_no UK "售后单号,唯一"
VARCHAR type "售后类型"
VARCHAR sub_type "售后子类型"
VARCHAR status "状态"
INT priority "优先级"
VARCHAR title "标题"
TEXT description "描述"
BIGINT creator_id "创建人"
BIGINT inbox_message_id "关联消息ID"
VARCHAR role_group "角色组"
TEXT resolution "最终处理结果"
DATETIME resolved_at "完结时间"
TINYINT claim_needed "仓库理赔标记"
DECIMAL claim_amount "仓库理赔金额(元)"
VARCHAR claim_status "仓库理赔状态"
TINYINT carrier_claim_needed "运方理赔标记"
DECIMAL carrier_claim_amount "运方理赔金额(元)"
VARCHAR carrier_claim_status "运方理赔状态"
BIGINT waybill_id "运单ID"
VARCHAR waybill_no "运单号"
BIGINT order_delivery_id "发货订单ID"
VARCHAR order_delivery_no "发货订单号"
BIGINT entry_order_id "入库单ID"
VARCHAR entry_order_no "入库单号"
BIGINT order_stockout_id "出库单ID"
VARCHAR order_stockout_no "出库单号"
BIGINT receiving_id "收货单ID"
VARCHAR receiving_no "收货单号"
DATETIME created_at "创建时间"
DATETIME updated_at "更新时间"
DATETIME deleted_at "软删除"
}
wms_after_sale_detail {
BIGINT id PK "主键"
BIGINT after_sale_id FK "关联售后主表"
VARCHAR step_status "步骤记录时主表状态"
BIGINT operator_id "操作人ID"
TEXT operator_snapshot "操作人信息快照"
VARCHAR action "操作动作"
TEXT remark "处理备注"
DATETIME started_at "步骤开始时间"
DATETIME completed_at "步骤完成时间"
DATETIME created_at "创建时间"
DATETIME updated_at "更新时间"
DATETIME deleted_at "软删除"
}
```
### 关联关系说明
```
wms_after_sale
├─ warehouse_id → stores.id(仓库,逻辑关联)
├─ store_id → stores.id(货主,逻辑关联)
├─ creator_id → accounts.id(创建人,逻辑关联)
├─ inbox_message_id → wms_inbox_message.id(站内信消息,逻辑关联)
├─ waybill_id → wms_order_express.id(运单,逻辑关联)
├─ order_delivery_id → wms_order_delivery.id(发货订单,逻辑关联)
├─ entry_order_id → wms_entry_order.id(入库单,逻辑关联)
├─ order_stockout_id → wms_order_stockout.id(出库单,逻辑关联)
└─ receiving_id → wms_receiving.id(收货单,逻辑关联)
wms_after_sale_detail
└─ after_sale_id → wms_after_sale.id(级联删除)
```
> **注意**:所有关联均为逻辑关联(不做物理外键),遵循项目现有惯例。
---
## 三、数据库表
### 3.1 表 A:售后主表 `wms_after_sale`
#### 3.1.1 基础字段
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 仓库ID |
| `store_id` | `BIGINT UNSIGNED` | — | NULL | 货主ID |
#### 3.1.2 售后信息
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `after_sale_no` | `VARCHAR(50)` | ✅ | — | **售后单号**,唯一索引。生成规则:前缀 `AS` + 日期 `YYYYMMDD` + 6 位序号(当天同仓库自增),如 `AS20260809000001`。参考波次号 `wave_no` 生成逻辑。 |
| `type` | `VARCHAR(20)` | ✅ | — | 售后类型,枚举见 §3.1.6 |
| `sub_type` | `VARCHAR(50)` | ✅ | — | 售后子类型,枚举见 §3.1.6,与 type 组成二级分类 |
| `status` | `VARCHAR(20)` | ✅ | `pending` | 售后状态,枚举及流转见 §五 |
| `priority` | `INT(11)` | ✅ | 0 | 优先级,数值越大越优先(0=普通,10=紧急) |
| `title` | `VARCHAR(200)` | ✅ | — | 售后标题(简要描述) |
| `description` | `TEXT` | — | NULL | 售后详细描述 |
#### 3.1.3 人员信息
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `creator_id` | `BIGINT UNSIGNED` | ✅ | — | 创建人账户ID(关联 `accounts` 表) |
| `role_group` | `VARCHAR(50)` | — | NULL | 当前处理角色组,用于角色维度查询待处理工单和转单。枚举见 §3.1.6。NULL 表示未分配。 |
| `inbox_message_id` | `BIGINT UNSIGNED` | — | NULL | 关联 `wms_inbox_message.id`(站内信消息主键)。为空表示无关联信息,非空表示该售后单由对应站内信消息创建或关联。 |
#### 3.1.4 处理结果
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `resolution` | `TEXT` | — | NULL | 最终处理结果说明 |
| `resolved_at` | `DATETIME` | — | NULL | 完结时间(状态变为 `completed` 时写入) |
#### 3.1.5 仓库理赔 & 运方理赔
**仓库理赔**:
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `claim_needed` | `TINYINT(1)` | ✅ | 0 | 仓库理赔标记:0=不需要,1=需要 |
| `claim_amount` | `DECIMAL(12,2)` | — | NULL | 仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写 |
| `claim_status` | `VARCHAR(20)` | — | NULL | 仓库理赔状态,枚举见 §3.1.6,仅 `claim_needed=1` 时有意义 |
**运方理赔**:
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `carrier_claim_needed` | `TINYINT(1)` | ✅ | 0 | 运方理赔标记:0=不需要,1=需要 |
| `carrier_claim_amount` | `DECIMAL(12,2)` | — | NULL | 运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写 |
| `carrier_claim_status` | `VARCHAR(20)` | — | NULL | 运方理赔状态,枚举见 §3.1.6,仅 `carrier_claim_needed=1` 时有意义 |
#### 3.1.6 类型与状态枚举
**售后类型 `type` + 售后子类型 `sub_type`**:
> 售后类型表示售后单主要关联的业务单据类型,售后子类型表示具体售后原因分类,两者组成二级分类。具体的售后动作(退货/换货/理赔/投诉等)通过进度步骤和最终处理结果体现。
| type | 说明 | sub_type |
|------|------|----------|
| `order` | 订单 | `damage` 破损, `missing_item` 少发, `mis_shipment` 错发, `wrong_sku` 错品, `quality_issue` 质量问题, `delivery_delay` 发货延迟, `logistics_issue` 物流异常, `rejected` 客户拒收, `intercept` 拦截, `verify_delivery` 核实签收, `urge` 催件, `extra_item` 多发, `change_address` 改地址, `change_carrier` 换快递, `weight_issue` 重量异常, `freight_issue` 运费争议, `other` 其他 |
| `receiving` | 收货单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 |
| `entry` | 入库单 | `shortage` 少货, `damage` 破损, `wrong_sku` 错品, `quality_issue` 质量问题, `other` 其他 |
| `stockout` | 出库单 | `return_issue` 退货异常, `wrong_outbound` 错发, `shortage` 少发, `other` 其他 |
**Model 层常量定义**(`app/model/after_sale.js`):
```javascript
// app/model/after_sale.js 中的常量定义
const AFTER_SALE_TYPES = [
{
name: '订单',
type: 'order',
subType: [
{ name: '破损', value: 'damage' },
{ name: '少发', value: 'missing_item' },
{ name: '错发', value: 'mis_shipment' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '发货延迟', value: 'delivery_delay' },
{ name: '物流异常', value: 'logistics_issue' },
{ name: '客户拒收', value: 'rejected' },
{ name: '拦截', value: 'intercept' },
{ name: '核实签收', value: 'verify_delivery' },
{ name: '催件', value: 'urge' },
{ name: '多发', value: 'extra_item' },
{ name: '改地址', value: 'change_address' },
{ name: '换快递', value: 'change_carrier' },
{ name: '重量异常', value: 'weight_issue' },
{ name: '运费争议', value: 'freight_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '收货单',
type: 'receiving',
subType: [
{ name: '少货', value: 'shortage' },
{ name: '破损', value: 'damage' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '入库单',
type: 'entry',
subType: [
{ name: '少货', value: 'shortage' },
{ name: '破损', value: 'damage' },
{ name: '错品', value: 'wrong_sku' },
{ name: '质量问题', value: 'quality_issue' },
{ name: '其他', value: 'other' },
],
},
{
name: '出库单',
type: 'stockout',
subType: [
{ name: '退货异常', value: 'return_issue' },
{ name: '错发', value: 'wrong_outbound' },
{ name: '少发', value: 'shortage' },
{ name: '其他', value: 'other' },
],
},
];
```
**角色组 `role_group`**:
| 值 | 说明 |
|----|------|
| `customer_service` | 客服组 |
| `warehouse` | 仓库组 |
| `finance` | 财务组 |
> 设计理由:运方(快递公司)是外部角色,不登录 WMS 系统,不纳入内部角色组。
**售后状态 `status`**:
| 值 | 说明 |
|----|------|
| `pending` | 待处理 |
| `processing` | 处理中 |
| `pending_feedback` | 等待外部反馈(内部处理完成,等待外部反馈后再决定是否继续处理) |
| `completed` | 已完成 |
| `closed` | 已关闭 |
| `cancelled` | 已取消 |
**理赔状态(仓库理赔 & 运方理赔通用枚举)**:
| 值 | 说明 |
|----|------|
| `pending` | 待理赔 |
| `reviewing` | 审核中 |
| `approved` | 已通过 |
| `paid` | 已打款 |
| `monthly` | 月结 |
| `rejected` | 已拒绝 |
#### 3.1.7 单据关联字段(核心设计)
> **设计要点**:每种业务单据使用独立字段组(ID + 单号冗余),替代旧版多态关联。多个字段组可同时有值,实现"一个售后单关联多种单据"。
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `waybill_id` | `BIGINT UNSIGNED` | — | NULL | 运单ID(关联 `wms_order_express.id`) |
| `waybill_no` | `VARCHAR(50)` | — | NULL | 运单号(冗余字段,方便查询展示) |
| `order_delivery_id` | `BIGINT UNSIGNED` | — | NULL | 发货订单ID(关联 `wms_order_delivery.id`) |
| `order_delivery_no` | `VARCHAR(50)` | — | NULL | 发货订单号(冗余字段) |
| `entry_order_id` | `BIGINT UNSIGNED` | — | NULL | 入库单ID(关联 `wms_entry_order.id`) |
| `entry_order_no` | `VARCHAR(50)` | — | NULL | 入库单号(冗余字段) |
| `order_stockout_id` | `BIGINT UNSIGNED` | — | NULL | 出库单/退货出库单ID(关联 `wms_order_stockout.id`) |
| `order_stockout_no` | `VARCHAR(50)` | — | NULL | 出库单号(冗余字段) |
| `receiving_id` | `BIGINT UNSIGNED` | — | NULL | 收货单ID(关联 `wms_receiving.id`) |
| `receiving_no` | `VARCHAR(50)` | — | NULL | 收货单号(冗余字段) |
> **冗余字段说明**:`_no` 后缀字段为冗余存储,目的是在售后列表查询时避免 JOIN 各业务表。写入时从对应业务表同步取数,后续若业务表单号变更需同步更新(建议通过业务 hook 或定时任务保证最终一致)。
#### 3.1.8 时间戳
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 |
| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 |
---
### 3.2 表 B:售后进度步骤表 `wms_after_sale_detail`
用于记录售后单的处理进度步骤(谁在什么时间做了什么操作)。步骤按 `created_at` 自然时间排序,通过 `action` 描述步骤内容,可记录步骤开始/完成时间、操作人及操作快照。
#### 3.2.1 字段定义
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
| `after_sale_id` | `BIGINT UNSIGNED` | ✅ | — | 关联售后主表ID(`wms_after_sale.id`) |
| `step_status` | `VARCHAR(20)` | ✅ | `processing` | 步骤记录时售后主表的状态,与 `wms_after_sale.status` 完全一致: pending / processing / completed / closed / cancelled。每次写入步骤时取主表当前 status 快照 |
| `operator_id` | `BIGINT UNSIGNED` | — | NULL | 操作人账户ID(关联 `accounts` 表);可为空,外部系统回调/自动触发的步骤无人操作 |
| `operator_snapshot` | `TEXT` | — | NULL | 操作人信息快照(JSON),如 `{"name":"张三","role":"客服"}`,防止账户删除后历史丢失 |
| `action` | `VARCHAR(100)` | — | NULL | 操作动作描述,如"确认收货"、"审核驳回"、"发起退款" |
| `remark` | `TEXT` | — | NULL | 处理备注 |
| `started_at` | `DATETIME` | — | NULL | 步骤开始时间 |
| `completed_at` | `DATETIME` | — | NULL | 步骤完成时间 |
| `created_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP` | 创建时间 |
| `updated_at` | `DATETIME` | ✅ | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| `deleted_at` | `DATETIME` | — | NULL | 软删除时间 |
#### 3.2.2 步骤状态 `step_status` 说明
`step_status` 与 `wms_after_sale.status` 完全一致(类型、枚举均相同),每次写入步骤时记录步骤发生时主表的当前状态快照。枚举值:
| 值 | 说明 |
|----|------|
| `pending` | 待处理 |
| `processing` | 处理中 |
| `completed` | 已完成 |
| `closed` | 已关闭 |
| `cancelled` | 已取消 |
> **设计考量**:`step_status` 记录的是"该步骤发生时,售后主表处于什么状态",而非步骤本身的"进行中/已完成"标记。这使得每条步骤都能直接追溯到该步骤执行时的工单状态上下文,无需 JOIN 主表查阅历史状态。步骤按 `created_at` 自然时间排序。
### 3.2.3 附件关联
售后进度步骤可通过 `wms_file_reference` 表挂载附件(如破损照片、签收凭证、理赔单据等)。
**绑定方式:**
| wms_file_reference 字段 | 值 | 说明 |
|--------------------------|-----|------|
| `business_type` | `after_sale_detail` | 售后进度步骤 |
| `business_id` | `{wms_after_sale_detail.id}` | 步骤主键ID |
**典型场景:**
- 仓库验货步骤上传破损商品照片
- 客服接单步骤上传客户提供的聊天截图
- 运方理赔步骤上传快递破损证明
- 退款步骤上传打款凭证截图
**查询示例:**
```sql
-- 查询某售后单所有步骤的附件
SELECT f.*, fr.business_id AS step_id
FROM wms_file_reference fr
JOIN wms_file f ON f.id = fr.file_id
WHERE fr.business_type = 'after_sale_detail'
AND fr.business_id IN (
SELECT id FROM wms_after_sale_detail WHERE after_sale_id = ?
);
```
---
## 四、索引设计
### 4.1 `wms_after_sale` 索引
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `uk_after_sale_no` | `after_sale_no` | 唯一 | 售后单号唯一约束 |
| `idx_warehouse_status` | `warehouse_id`, `status`, `deleted_at` | 普通 | 按仓库+状态查询售后列表(最高频) |
| `idx_warehouse_type` | `warehouse_id`, `type`, `deleted_at` | 普通 | 按仓库+类型筛选 |
| `idx_type_subtype` | `warehouse_id`, `type`, `sub_type`, `deleted_at` | 普通 | 按仓库+类型+子类型筛选 |
| `idx_store_id` | `store_id`, `deleted_at` | 普通 | 按货主查询 |
| `idx_creator_id` | `creator_id`, `deleted_at` | 普通 | 按创建人查询 |
| `idx_role_group` | `role_group`, `status`, `deleted_at` | 普通 | 按角色组+状态查询待处理工单(角色维度) |
| `idx_created_at` | `warehouse_id`, `created_at` | 普通 | 按仓库+时间排序分页 |
| `idx_waybill_id` | `waybill_id` | 普通 | 按运单反查售后单 |
| `idx_order_delivery_id` | `order_delivery_id` | 普通 | 按发货订单反查售后单 |
| `idx_entry_order_id` | `entry_order_id` | 普通 | 按入库单反查售后单 |
| `idx_order_stockout_id` | `order_stockout_id` | 普通 | 按出库单反查售后单 |
| `idx_receiving_id` | `receiving_id` | 普通 | 按收货单反查售后单 |
| `idx_carrier_claim_status` | `carrier_claim_status` | 普通 | 按运方理赔状态筛选 |
| `idx_inbox_message_id` | `inbox_message_id` | 普通 | 按站内信消息反查售后单 |
### 4.2 `wms_after_sale_detail` 索引
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `idx_after_sale_id` | `after_sale_id` | 普通 | 按售后单查询进度步骤(最高频) |
| `idx_operator_id` | `operator_id` | 普通 | 按操作人查询其处理的步骤 |
---
## 五、状态流转
```mermaid
stateDiagram-v2
[*] --> pending: 创建售后单
pending --> processing: 指派处理人 / 开始处理
pending --> cancelled: 取消
processing --> pending_feedback: 内部处理完毕,等待外部反馈
processing --> completed: 处理完成
processing --> closed: 强制关闭
pending_feedback --> processing: 收到外部反馈,继续处理
pending_feedback --> completed: 外部反馈确认完成
completed --> [*]
closed --> [*]
cancelled --> [*]
```
| 流转 | 触发条件 | 说明 |
|------|---------|------|
| `pending` → `processing` | 指派处理人 or 手动开始处理 | 通过 `wms_after_sale_detail` 记录的处理步骤追踪 |
| `pending` → `cancelled` | 创建人取消 | 仅待处理状态可取消 |
| `processing` → `pending_feedback` | 内部处理完毕,等待外部反馈 | 如已将拦截信息发给运方,等待运方反馈拦截结果 |
| `processing` → `completed` | 处理完毕 | 写入 `resolution` + `resolved_at` |
| `processing` → `closed` | 管理员强制关闭 | 如重复单、无效单等 |
| `pending_feedback` → `processing` | 收到外部反馈,继续处理 | 如运方反馈已拦截/未拦截,回到内部通知客户 |
| `pending_feedback` → `completed` | 外部反馈确认完成 | 如平台退款回调确认到账 |
**理赔状态流转**(仓库理赔 & 运方理赔通用):`pending` → `reviewing` → `approved` → `paid`,任意阶段可 → `rejected`,或走 `monthly`(月结)通道。
> `wms_after_sale_detail` 即操作日志:每条进度步骤记录操作人、操作动作、处理备注、开始/完成时间,已完整覆盖状态变更追踪需求,无需额外日志表。
---
## 六、典型使用场景
### 场景1:订单售后(退货退款,关联运单 + 收货单)
```
售后单 type=order, sub_type=damage, role_group=customer_service
├─ inbox_message_id: 12345(关联站内信消息,客户发送"破损"指令触发)
├─ waybill_id / waybill_no: 客户寄回的快递单号
├─ receiving_id / receiving_no: 仓库收货单
└─ 进度步骤:
├─ step_status=processing, operator_id=1001, action=客服接单-受理退货申请
├─ step_status=processing, operator_id=2001, action=仓库收货-确认收货入库
└─ step_status=processing, action=退款打款
```
> **转单说明**:当客服接单后发现需要仓库核实实物时,可将 `role_group` 从 `customer_service` 更新为 `warehouse`,仓库组即可在自己的待办列表中看到该工单。
### 场景2:订单售后(换货,关联运单 + 发货订单)
```
售后单 type=order, sub_type=quality_issue
├─ waybill_id / waybill_no: 客户寄回的快递单号
├─ order_delivery_id / order_delivery_no: 仓库补发的发货订单
└─ 进度步骤:
├─ step_status=processing, action=客服接单-确认换货申请
├─ step_status=processing, action=退回入库-客户退回商品已入库
└─ step_status=processing, action=补发换货-仓库补发新商品
```
### 场景3:订单售后(仓库理赔)
```
售后单 type=order, sub_type=damage
├─ claim_needed=1, claim_amount=50.00, claim_status=pending
└─ 进度步骤:
├─ step_status=processing, action=客服接单-受理仓库理赔
├─ step_status=processing, action=核实定损, remark=仓库出库破损, 核定赔偿50元
└─ step_status=processing, action=审批打款
```
### 场景3b:订单售后(运方理赔)
```
售后单 type=order, sub_type=logistics_issue
├─ carrier_claim_needed=1, carrier_claim_amount=200.00, carrier_claim_status=pending
├─ waybill_id / waybill_no: 涉损运单
└─ 进度步骤:
├─ step_status=processing, action=客服接单-受理运方理赔
├─ step_status=processing, action=核实定损, remark=运输途中破损, 核定赔偿200元
└─ step_status=processing, action=快递审批
```
> **说明**:仓库理赔与运方理赔可同时存在(如货物在仓库出库&运输途中均发生破损),分别使用 `claim_*` 和 `carrier_claim_*` 字段组记录。
### 场景4:订单售后(多单据共存:退货退款 + 运单 + 收货单 + 出库单)
```
售后单 type=order, sub_type=damage, role_group=warehouse
├─ waybill_id / waybill_no: 客户退货快递
├─ receiving_id / receiving_no: 仓库收货单
├─ order_stockout_id / order_stockout_no: 退货出库单
└─ 进度步骤:
├─ step_status=processing, action=客服接单-批量退货受理
├─ step_status=processing, operator_id=3001, action=验货签收, remark=SKU001×3, SKU002×1 均完好(可挂附件:破损照片 × 2)
├─ step_status=processing, action=退货入库
└─ step_status=processing, action=退款打款
```
> **说明**:此场景中 `role_group=warehouse` 表示当前由仓库组负责验货入库环节;验货完成后如需财务退款,转单时将 `role_group` 更新为 `finance`。
---
## 七、迁移计划
### 7.1 迁移文件
```
database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale.js
database/migrations/YYYYMMDDHHMMSS-create-wms-after-sale-detail.js
```
### 7.2 Model 文件
```
app/model/after_sale.js → wms_after_sale
app/model/after_sale_detail.js → wms_after_sale_detail
```
### 7.3 后续扩展(不纳入本期)
| 扩展项 | 说明 |
|--------|------|
| 批量创建 | 按运单号/订单号批量生成售后单 |
| 自动创建规则 | 如收到退货快递自动创建售后单 |
| 售后统计看板 | 按仓库/类型/状态统计售后量、理赔金额等 |
---
## 八、版本记录
| 版本 | 日期 | 变更内容 | 作者 |
|------|------|---------|------|
| v1 | 2026-08-09 | 初稿,待评审 | wms-doc-agent |
---
## 九、权限设计
售后模块的角色组通过 `wms_permission` 表中 `type='block'` 的权限条目来承载,与主表 `role_group` 字段一一对应。
### 9.1 Block 权限(角色组区分)
> ID 516-523 为售后模块固定 ID。
| ID | meta_title | type | 对应 role_group |
|----|-----------|------|-----------------|
| 516 | 售后-客服组 | `block` | `customer_service` |
| 517 | 售后-仓库组 | `block` | `warehouse` |
| 518 | 售后-财务组 | `block` | `finance` |
> 生产组主管(role_code=03)和拣货组组长(role_code=021)使用仓库组 block(517),共享仓库组视角。
### 9.2 页面权限
| ID | path | meta_title | type | parent_id |
|----|------|-----------|------|-----------|
| 519 | `afterSale` | 售后管理 | `web_pages` | null |
| 520 | `afterSale.list` | 售后列表 | `web_pages` | 519 |
| 521 | `afterSale.detail` | 售后明细 | `web_pages` | 519 |
### 9.3 API 权限
| ID | path | meta_title | type |
|----|------|-----------|------|
| 522 | `afterSale.workList` | API:售后工作列表查询 | `api` |
| 523 | `afterSale.auditList` | API:售后审计列表查询 | `api` |
| 508 | `afterSale.detail` | API:售后明细查询 | `api` |
| 509 | `afterSale.create` | API:创建售后单 | `api` |
| 510 | `afterSale.update` | API:更新售后单 | `api` |
| 511 | `afterSale.transfer` | API:售后转单 | `api` |
| 512 | `afterSale.handleWorkOrder` | API:处理工单 | `api` |
| 513 | `afterSale.registerClaim` | API:登记理赔 | `api` |
| 514 | `afterSale.export` | API:售后导出 | `api` |
| 515 | `afterSale.exportTaskProgress` | API:导出进度查询 | `api` |
### 9.4 角色权限绑定
| 角色 | 角色组 block | 页面 | API |
|------|------------|------|-----|
| 客服 | 516 | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 |
| 仓库 | 517 | 519, 520, 521 | 522, 508, 510, 512 |
| 生产组-主管 | 517 | 519, 520, 521 | 522, 508, 510, 512 |
| 拣货组-组长 | 517 | 519, 520, 521 | 522, 508, 510, 512 |
| 财务 | 518 | 519, 520, 521 | 522, 508 |
| 经理 | — | 519, 520, 521 | 522, 523, 508, 509, 510, 511, 512, 513, 514, 515 |
> - 客服:全部权限(创建、更新、转单、查理赔)
> - 仓库:只读查询 + 更新处理结果
> - 生产组-主管 / 拣货组-组长:共享仓库组视角(同仓库组权限),处理退货验货入库等实物操作。普通生产组员工不授权任何售后权限。
> - 财务:只读查询(理赔审核通过财务系统操作,不走 WMS)
> - 经理:全部售后权限
> **生产组其他角色**(普通员工、复核、其他普工)不授权任何售后权限。
> **财务组角色**:role_code=`finance`,role_name=`财务组`,自动创建并授权。
---
## 十、Methods API 设计
### 10.1 概述
售后模块 API method 统一以 `afterSale.` 为前缀,使用 `/system` 网关接入。工作列表与审计列表分离,导出采用异步任务模式。
### 10.2 列表一:工作列表 `afterSale.workList`
**定位**:仓库内员工看到自己角色组需要处理的工单。
**可见性规则:**
- 创建时 `role_group` 默认为 `customer_service`,仅客服组可见
- 转单后(如 `customer_service` → `warehouse`),原角色组不再可见,目标角色组可见
- 用户通过角色绑定的 block 权限(516/517/518)确定可见哪些 role_group
- **核心逻辑**:`WHERE role_group IN (用户拥有的售后block对应的role_group)` 且 `status != 'completed' AND status != 'cancelled'`
**method 定义:**
```json
{
"method": "afterSale.workList",
"description": "售后工作列表。仅返回当前用户角色组负责的待处理工单。创建时默认进入客服组,转单后原组不可见、目标组可见。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "pagination", "type": "object", "required": false, "source": "body", "description": "分页参数 page/pageSize" },
{ "name": "where", "type": "object", "required": false, "source": "body", "description": "筛选条件:支持 type/sub_type/status/priority/after_sale_no/waybill_no 等字段筛选,以及 quickWhere 快捷搜索" },
{ "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数 sortField/sortOrder,默认按 priority DESC, created_at DESC" }
],
"response": [
{ "name": "list", "type": "array", "required": true, "description": "售后工单列表" },
{ "name": "pagination", "type": "object", "required": true, "description": "分页信息" }
]
}
```
### 10.3 列表二:审计列表 `afterSale.auditList`
**定位**:所有售后单全局视图,不限角色组,用于审计和管理。
**可见性规则:**
- 所有 `status` 的工单均可见(包括 completed/cancelled)
- 不限 `role_group`
- 与工作列表共享 where/sort/pagination 参数格式
**method 定义:**
```json
{
"method": "afterSale.auditList",
"description": "售后审计列表。全局售后单视图,不限角色组、不限状态,用于审计和统计分析。入参与 afterSale.workList 一致。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "pagination", "type": "object", "required": false, "source": "body" },
{ "name": "where", "type": "object", "required": false, "source": "body", "description": "同 workList,额外支持 claim_status/carrier_claim_status 筛选" },
{ "name": "sort", "type": "object", "required": false, "source": "body" }
],
"response": [
{ "name": "list", "type": "array", "required": true },
{ "name": "pagination", "type": "object", "required": true }
]
}
```
### 10.4 导出接口 `afterSale.export` + `afterSale.exportTaskProgress`
参考项目现有导出模式(`order.export` / `order.exportTaskProgress`)。
**`afterSale.export`:**
```json
{
"method": "afterSale.export",
"description": "提交售后审计列表导出任务(异步)。入参 where/sort 与 afterSale.auditList 完全一致。提交后立即返回 task_id,后台异步执行 Excel 生成并上传 COS。通过 afterSale.exportTaskProgress 查询进度和下载链接。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "where", "type": "object", "required": false, "source": "body", "description": "查询条件,与 afterSale.auditList 的 where 语义一致" },
{ "name": "sort", "type": "object", "required": false, "source": "body", "description": "排序参数,与 afterSale.auditList 的 sort 语义一致" }
],
"response": [
{ "name": "task_id", "type": "string", "required": true, "description": "导出任务ID" },
{ "name": "status", "type": "string", "required": true, "description": "submitted/running/success/failed" },
{ "name": "progress", "type": "number", "required": true, "description": "0-100" },
{ "name": "message", "type": "string", "required": true }
]
}
```
**`afterSale.exportTaskProgress`:**
```json
{
"method": "afterSale.exportTaskProgress",
"description": "查询售后导出任务进度和下载链接。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "task_id", "type": "string", "required": true, "source": "body", "description": "导出任务ID" }
],
"response": [
{ "name": "task_id", "type": "string", "required": true },
{ "name": "status", "type": "string", "required": true },
{ "name": "progress", "type": "number", "required": true },
{ "name": "download_url", "type": "string", "required": false, "description": "status=success 时返回 Excel 下载链接" },
{ "name": "error", "type": "string", "required": false, "description": "status=failed 时返回错误信息" }
]
}
```
### 10.5 其他 methods
| method | 说明 | 权限 |
|--------|------|------|
| `afterSale.create` | 创建售后单 | 客服 |
| `afterSale.detail` | 售后明细(主表+步骤列表) | 全部 |
| `afterSale.update` | 更新售后单 | 客服/仓库 |
| `afterSale.transfer` | 转单(更新 role_group) | 客服 |
| `afterSale.handleWorkOrder` | 处理工单(写步骤+绑附件) | 当前 role_group 匹配的用户 |
| `afterSale.registerClaim` | 登记售后理赔信息(仓库理赔+运方理赔) | 客服 |
### 10.6 导出流程说明
导出流程参考项目现有异步导出模式(`order.export`):
1. 客户端调用 `afterSale.export` 提交导出任务,服务端生成 `task_id`,在 Redis 中初始化任务状态为 `submitted`
2. 通过 `setImmediate` 启动异步执行,立即返回 `task_id` 给客户端
3. 后台任务分页查询售后数据,使用 ExcelJS 流式写入 Excel 文件
4. Excel 生成完成后上传至 COS,获取下载链接
5. 更新 Redis 中任务状态为 `success`,并写入 `download_url`
6. 若任一步骤失败,更新任务状态为 `failed`,并写入错误信息
7. 客户端轮询 `afterSale.exportTaskProgress` 获取进度和下载链接
**Redis 缓存规范:**
- Key 格式:`after_sale_export_task_{task_id}`
- TTL:30 分钟(任务完成后自动过期)
### 10.7 处理工单 `afterSale.handleWorkOrder`
```json
{
"method": "afterSale.handleWorkOrder",
"description": "处理售后工单。员工在工作列表中对工单进行操作,写入进度步骤并绑定附件。操作人信息从登录上下文自动获取。步骤 action 由服务端固定为\"处理工单\",前端无需传入。status 不填或填错默认 processing。非客服组处理完成后自动转回客服组继续跟进。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID(wms_after_sale.id)" },
{ "name": "status", "type": "string", "required": false, "source": "body", "description": "更新售后单状态: processing | completed | closed | cancelled。不填或填错默认 processing。注意:pending 不适用于处理操作" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注" },
{ "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组,如 [123, 456]。处理时自动绑定到本次步骤。" }
],
"response": [
{ "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的 wms_after_sale_detail.id" },
{ "name": "after_sale_id", "type": "integer", "required": true }
],
"errors": [
{ "code": 400, "message": "工单不存在或参数缺失" },
{ "code": 500, "message": "处理失败" }
]
}
```
**处理流程:**
1. 校验工单 `id` 存在,且当前用户 `role_group` 与工单 `role_group` 匹配(否则 403)
2. 从登录上下文(JWT token)提取操作人 `operator_id` 和 `operator_snapshot`
3. 写入 `wms_after_sale_detail`:
- `step_status` = 主表当前 status(由 safeStatus 决定,不填或填错默认 processing)
- `action` = 服务端固定 `"处理工单"`
- `remark` = 入参 `remark`
- `operator_id` / `operator_snapshot` = 当前用户
- `started_at = now`, `completed_at = now`
4. 若传入了 `attachment_ids`,遍历写入 `wms_file_reference`:
- `business_type = 'after_sale_detail'`
- `business_id` = 刚写入的 `detail.id`
- `file_id = attachment_id`
5. 更新 `wms_after_sale.status`:始终写入 safeStatus(默认 processing,白名单校验,不含 pending)
6. 若当前 `role_group` ≠ `'customer_service'` 且 status ≠ `'completed'`,自动将 `role_group` 回设为 `'customer_service'`(仓库/财务处理完本环节后自动退回客服组继续跟进)
7. 若 status = `'completed'`,同时写入 `resolution` 和 `resolved_at`
### 10.8 理赔登记 `afterSale.registerClaim`
```json
{
"method": "afterSale.registerClaim",
"description": "登记售后理赔信息。一次性填入仓库理赔和运方理赔的全部字段,同时写入进度步骤。两套理赔字段可同时填写(双赔场景)。",
"isNeedAuth": false,
"isNeedLogin": true,
"params": [
{ "name": "id", "type": "integer", "required": true, "source": "body", "description": "售后工单主表ID" },
{ "name": "claim_needed", "type": "integer", "required": false, "source": "body", "description": "仓库理赔标记:0/1" },
{ "name": "claim_amount", "type": "number", "required": false, "source": "body", "description": "仓库理赔金额(元)" },
{ "name": "claim_status", "type": "string", "required": false, "source": "body", "description": "仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected" },
{ "name": "carrier_claim_needed", "type": "integer", "required": false, "source": "body", "description": "运方理赔标记:0/1" },
{ "name": "carrier_claim_amount", "type": "number", "required": false, "source": "body", "description": "运方理赔金额(元)" },
{ "name": "carrier_claim_status", "type": "string", "required": false, "source": "body", "description": "运方理赔状态:pending/reviewing/approved/paid/monthly/rejected" },
{ "name": "action", "type": "string", "required": true, "source": "body", "description": "操作动作描述,如"登记仓库理赔"、"登记运方理赔"" },
{ "name": "remark", "type": "string", "required": false, "source": "body", "description": "处理备注,如"快递破损核定赔200元"" },
{ "name": "attachment_ids", "type": "array", "required": false, "source": "body", "description": "附件 file_id 数组(破损照片、理赔单据等)" }
],
"response": [
{ "name": "detail_id", "type": "integer", "required": true, "description": "本次写入的步骤ID" },
{ "name": "after_sale_id", "type": "integer", "required": true }
],
"errors": [
{ "code": 400, "message": "工单不存在或参数缺失" },
{ "code": 500, "message": "登记失败" }
]
}
```
**处理流程:**
1. 校验工单 `id` 存在
2. 从登录上下文提取操作人信息
3. 更新 `wms_after_sale` 中传入的非空理赔字段(`claim_needed/amount/status`、`carrier_claim_needed/amount/status`)
4. 写入 `wms_after_sale_detail`(step_status=主表当前 status,action/remark/operator)
5. 若有 `attachment_ids`,绑定到本次步骤
**使用场景:**
- 单赔:只传仓库理赔字段组,运方字段不传
- 单赔:只传运方理赔字段组,仓库字段不传
- 双赔:同时传两套字段(仓库+运输途中均破损)
---
## 十一、待评审事项
- [ ] 售后单号 `after_sale_no` 生成规则:格式已确定为 `AS + YYYYMMDD + 6位序号`(如 `AS20260809000001`),待确认序号从 1 起始还是从指定起始值起
- [ ] 仓库理赔(`claim_status`)和运方理赔(`carrier_claim_status`)是否需要更细粒度的流转(如:待审核 → 审核通过 → 已打款 → 月结)
- [ ] 进度步骤表是否需要记录商品明细信息(如退货 SKU/数量),或通过 `remark` JSON 扩展存储
- [ ] 单据关联字段是否需要扩展到更多类型(如质检单 `quality_check_id`)
- [ ] 是否需要支持售后单之间的关联(如换货单关联原退货单)

View File

@ -1,440 +0,0 @@
# 售后工单表设计方案
> **状态**: ✅ 已落库(开发环境)
> **设计日期**: 2026-07-28(v4 定稿:新增 parent_work_order_id 支持主子工单)
> **设计人**: wms-db-agent
> **说明**: 本文档仅输出设计方案,不执行落库。审阅通过后再生成迁移文件。
---
## 一、需求概述
1. **主表**:售后工单单表,支持灵活绑定多种业务单据(运单、订单、入库单、退货单等),通过 `business_type` + `business_sub_type` + `business_id` 三级多态关联
2. **副表**:进度步骤处理表,记录每一步的操作员工、动作、备注(步骤不预设模板,由业务逻辑动态创建)
3. **状态流转**:工单整体状态 + 主表 `current_step` 进度 + 步骤级状态三层次
4. **简单记账**:记录是"进"还是"出"
5. **理赔追踪**:是否需要理赔、理赔金额、理赔结算状态
6. **附件关联**:通过现有 `wms_file_reference` 表关联附件/图片
---
## 二、表结构设计
### 2.1 主表:`wms_after_sale_work_order`(售后工单主表)
| # | 字段名 | 类型 | 必填 | 默认值 | 说明 |
|---|--------|------|------|--------|------|
| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID |
| 2 | `warehouse_id` | `BIGINT(20) UNSIGNED` | Y | — | 仓库ID |
| 3 | `store_id` | `BIGINT(20) UNSIGNED` | Y | — | 货主ID |
| 4 | `work_order_no` | `VARCHAR(50)` | Y | — | 售后工单号,唯一,格式 `AS` + 时间戳(如 AS202607280001) |
| 5 | `business_type` | `VARCHAR(50)` | Y | — | 关联业务类型,见 §3.1 枚举及 §五 Model 内置定义 |
| 6 | `business_sub_type` | `VARCHAR(50)` | Y | — | 关联业务子类型,如运单下的 `intercept`(拦截)、订单下的 `mis_shipment`(错发),见 §五 |
| 7 | `business_id` | `BIGINT(20) UNSIGNED` | Y | — | 关联业务单据主键ID(多态关联) |
| 8 | `business_no` | `VARCHAR(100)` | N | — | 关联业务单据号(冗余,方便列表展示) |
| 9 | `direction` | `TINYINT UNSIGNED` | Y | 0 | 记账方向:`1`=入库(退货入库/换货入库),`2`=出库(补发/换货出库),`0`=未确定 |
| 10 | `status` | `TINYINT UNSIGNED` | Y | 0 | 工单状态,见 §3.4 状态机 |
| 11 | `priority` | `TINYINT UNSIGNED` | Y | 50 | 优先级:`1`~`100`,数字越大优先级越高,由客服接待或AI自动识别填入 |
| 12 | `title` | `VARCHAR(200)` | Y | — | 工单标题/摘要 |
| 13 | `description` | `TEXT` | N | — | 问题描述 |
| 14 | `creator_id` | `BIGINT(20) UNSIGNED` | Y | — | 创建人ID,关联 `account.id`;`0` 表示 AI 自动接待 |
| 15 | `creator_snapshot` | `TEXT` | N | — | 创建人信息快照(JSON格式);AI创建时记录模型/会话信息 |
| 16 | `assignee_id` | `BIGINT(20) UNSIGNED` | N | — | 当前处理人ID,关联 `account.id` |
| 17 | `parent_work_order_id` | `BIGINT(20) UNSIGNED` | N | — | 父工单ID,自关联 `wms_after_sale_work_order.id`;非空时表示当前工单为子工单 |
| 18 | `current_step` | `TINYINT UNSIGNED` | Y | 1 | **当前进度**(位于主表),值为当前正在处理的 `step_order` 序号 |
| 19 | `claim_needed` | `TINYINT UNSIGNED` | Y | 0 | 是否需要理赔:`0`=不需要,`1`=需要 |
| 20 | `claim_amount` | `DECIMAL(12,2)` | N | 0.00 | 理赔金额(元),精度2位小数 |
| 21 | `claim_status` | `TINYINT UNSIGNED` | Y | 0 | 理赔状态:`0`=未理赔,`1`=已理赔(单笔结清),`2`=月结 |
| 22 | `resolution` | `TEXT` | N | — | 处理结果说明 |
| 23 | `resolved_at` | `DATETIME` | N | — | 解决时间 |
| 24 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 |
| 25 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| 26 | `deleted_at` | `DATETIME` | N | — | 软删除时间 |
**索引设计**:
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `uk_work_order_no` | `work_order_no` | 唯一 | 工单号唯一 |
| `idx_warehouse_id` | `warehouse_id` | 普通 | 按仓库查询 |
| `idx_store_id` | `store_id` | 普通 | 按货主查询 |
| `idx_business_type_subtype_id` | `business_type, business_sub_type, business_id` | 普通 | 按业务类型+子类型+单据ID反查工单 |
| `idx_status` | `status` | 普通 | 按状态筛选 |
| `idx_assignee_id` | `assignee_id` | 普通 | 按处理人查询 |
| `idx_parent_work_order_id` | `parent_work_order_id` | 普通 | 按父工单查所有子工单 |
| `idx_priority` | `priority` | 普通 | 按优先级排序 |
| `idx_claim_status` | `claim_status` | 普通 | 按理赔状态筛选 |
| `idx_created_at` | `created_at` | 普通 | 按时间排序 |
| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 |
---
### 2.2 副表:`wms_after_sale_work_order_step`(售后工单进度步骤表)
| # | 字段名 | 类型 | 必填 | 默认值 | 说明 |
|---|--------|------|------|--------|------|
| 1 | `id` | `BIGINT(20) UNSIGNED` | Y | AUTO | 主键ID |
| 2 | `work_order_id` | `BIGINT(20) UNSIGNED` | Y | — | 工单ID,关联 `wms_after_sale_work_order.id` |
| 3 | `step_order` | `TINYINT UNSIGNED` | Y | 1 | 步骤序号(从1开始递增) |
| 4 | `step_name` | `VARCHAR(100)` | Y | — | 步骤名称 |
| 5 | `step_status` | `TINYINT UNSIGNED` | Y | 0 | 步骤状态:`0`=待开始,`1`=进行中,`2`=已完成,`3`=已跳过 |
| 6 | `operator_id` | `BIGINT(20) UNSIGNED` | N | — | 操作员工ID,关联 `account.id` |
| 7 | `operator_snapshot` | `TEXT` | N | — | 操作人信息快照(JSON格式) |
| 8 | `action` | `VARCHAR(100)` | N | — | 操作动作描述(如"核实问题属实,安排退货入库") |
| 9 | `remark` | `TEXT` | N | — | 处理备注 |
| 10 | `started_at` | `DATETIME` | N | — | 步骤开始时间 |
| 11 | `completed_at` | `DATETIME` | N | — | 步骤完成时间 |
| 12 | `created_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP` | 创建时间 |
| 13 | `updated_at` | `DATETIME` | Y | `CURRENT_TIMESTAMP ON UPDATE` | 更新时间 |
| 14 | `deleted_at` | `DATETIME` | N | — | 软删除时间 |
**索引设计**:
| 索引名 | 字段 | 类型 | 说明 |
|--------|------|------|------|
| `PRIMARY` | `id` | 主键 | — |
| `idx_work_order_id` | `work_order_id` | 普通 | 按工单查所有步骤 |
| `idx_operator_id` | `operator_id` | 普通 | 按操作人反查 |
| `idx_deleted_at` | `deleted_at` | 普通 | 软删除查询 |
| `uk_work_order_step` | `work_order_id, step_order, deleted_at` | 唯一 | 同一工单下步骤序号唯一(含软删除) |
---
## 三、枚举定义
### 3.1 `business_type` 与 `business_sub_type`(业务类型及子类型)
业务类型和子类型由 Model 文件 `app/model/after_sale_work_order.js` 中的 `BUSINESS_TYPES` 常量统一定义。数据库层面使用 `VARCHAR(50)` 存储,方便扩展。
#### 内置业务类型总览
| business_type | 业务名称 | 关联表 | 子类型 (business_sub_type) |
|---------------|---------|--------|---------------------------|
| `waybill` | 运单 | `wms_order_express` | `intercept`(拦截)、`urge`(催件)、`damage`(破损)、`lost`(丢件)、`wrong_info`(信息错误) |
| `order_delivery` | 发货订单 | `wms_order_delivery` | `mis_shipment`(错发)、`missing_item`(少发)、`wrong_sku`(错品)、`quality_issue`(质量问题)、`delivery_delay`(发货延迟) |
| `entry_order` | 入库单 | `wms_entry_order` | `shortage`(少货)、`damage`(破损)、`wrong_sku`(错品)、`quality_issue`(质量问题) |
| `order_stockout` | 出库单/退货出库单 | `wms_order_stockout` | `return_issue`(退货异常)、`wrong_outbound`(错发)、`shortage`(少发) |
| `receiving` | 收货单 | `wms_receiving` | `shortage`(少货)、`damage`(破损)、`quality_issue`(质量问题) |
| `other` | 其他 | — | `general`(通用) |
> **扩展方式**:在 Model 的 `BUSINESS_TYPES` 常量中增删条目即可,无需 ALTER TABLE。外部代码通过 `require` Model 文件读取。
### 3.2 `priority`(优先级)
```
1 ~ 100 的整数,数字越大优先级越高。
由客服接待手动填入,或由 AI 根据问题描述自动识别并填入。
默认值 50(中等优先级)。
```
### 3.3 `direction`(记账方向)
```
0 — 未确定
1 — 入库(IN):退货入库 / 换货入库 / 赔付补货入库
2 — 出库(OUT):补发出库 / 换货出库 / 退款退货出库
```
> 与 `stock_transaction.transaction_type`(`INBOUND`/`OUTBOUND`)语义对齐。
### 3.4 `status`(工单状态)
```
0 — 待处理 (工单刚创建,尚未分配)
1 — 处理中 (已分配处理人,正在推进)
2 — 已完成 (问题已解决,全部步骤完成)
3 — 已关闭 (问题关闭,不再跟进)
9 — 已取消 (工单作废)
```
### 3.5 `claim_status`(理赔状态)
```
0 — 未理赔 (不需要理赔,或尚未发起理赔)
1 — 已理赔 (单笔已结清,理赔款项已到账)
2 — 月结 (纳入月度结算,按月统一对账打款)
```
### 3.6 `step_status`(步骤状态)
```
0 — 待开始 (步骤尚未激活)
1 — 进行中 (当前正在处理的步骤)
2 — 已完成 (步骤已处理完毕)
3 — 已跳过 (该步骤被跳过,不适用)
```
### 3.7 `creator_id` 特殊值
```
0 — AI 自动接待(非员工账号创建)
> 0 — 对应 account.id,人工客服/员工创建
```
> 当 `creator_id = 0` 时,`creator_snapshot` 可记录 AI 模型标识及会话 ID 等元信息。
---
## 四、状态流转设计
### 4.1 工单级别状态机
```
┌──────────────────────────────────┐
│ │
┌───┴──────┐ ┌───┴──────┐
创建工单 ───→ │ 待处理(0) │ ──── 分配处理人 ───→ │ 处理中(1) │
└───┬──────┘ └───┬──────┘
│ │
│ 取消 │ 全部步骤完成
↓ ↓
┌───┴──────┐ ┌───┴──────┐
│ 已取消(9) │ │ 已完成(2) │
└──────────┘ └───┬──────┘
│
│ 关闭
↓
┌───┴──────┐
│ 已关闭(3) │
└──────────┘
```
**流转规则**:
| 当前状态 | 允许流转到 | 触发条件 |
|----------|-----------|----------|
| `0-待处理` | `1-处理中` | 分配处理人 |
| `0-待处理` | `9-已取消` | 主动取消 |
| `1-处理中` | `2-已完成` | 所有步骤均标记为已完成 |
| `1-处理中` | `9-已取消` | 主动取消 |
| `2-已完成` | `3-已关闭` | 确认关闭 |
| `3-已关闭` | — | 终态,不可流转 |
### 4.2 步骤级别状态机
```
┌──────────────────────────────────┐
│ │
┌───┴──────┐ ┌───┴──────┐
步骤创建 ───→ │ 待开始(0) │ ──── 开始处理 ───→ │ 进行中(1) │
└───┬──────┘ └───┬──────┘
│ │
│ 跳过 │ 完成
↓ ↓
┌───┴──────┐ ┌───┴──────┐
│ 已跳过(3) │ │ 已完成(2) │
└──────────┘ └──────────┘
```
**约束**:
- 同一工单下,同一时刻最多只有 1 个步骤处于 `进行中(1)`
- 步骤按 `step_order` 顺序流转,但允许跳过中间步骤
- 工单进度由主表 `current_step` 字段追踪,指向当前正在处理的 `step_order`
- 所有步骤标记为 `已完成(2)` 或 `已跳过(3)` 后,`current_step` 置为最终步骤号,工单状态可流转至 `已完成(2)`
---
## 五、Model 内置业务类型定义
> **步骤不预设模板**:`wms_after_sale_work_order_step` 表的步骤由业务逻辑在运行时动态创建,不在数据库或 Model 中硬编码步骤模板。
### 5.1 `BUSINESS_TYPES` 常量(定义在 `app/model/after_sale_work_order.js`)
```javascript
/**
* 售后工单业务类型定义
* 外部可通过 require('./app/model/after_sale_work_order').BUSINESS_TYPES 访问
* 增删业务类型或子类型只需修改此常量,无需 ALTER TABLE
*/
const BUSINESS_TYPES = {
waybill: {
label: '运单',
table: 'wms_order_express', // 关联的数据库表名
subtypes: {
intercept: '拦截',
urge: '催件',
damage: '破损',
lost: '丢件',
wrong_info: '信息错误',
},
},
order_delivery: {
label: '发货订单',
table: 'wms_order_delivery',
subtypes: {
mis_shipment: '错发',
missing_item: '少发',
wrong_sku: '错品',
quality_issue: '质量问题',
delivery_delay: '发货延迟',
},
},
entry_order: {
label: '入库单',
table: 'wms_entry_order',
subtypes: {
shortage: '少货',
damage: '破损',
wrong_sku: '错品',
quality_issue: '质量问题',
},
},
order_stockout: {
label: '出库单/退货出库单',
table: 'wms_order_stockout',
subtypes: {
return_issue: '退货异常',
wrong_outbound: '错发',
shortage: '少发',
},
},
receiving: {
label: '收货单',
table: 'wms_receiving',
subtypes: {
shortage: '少货',
damage: '破损',
quality_issue: '质量问题',
},
},
other: {
label: '其他',
table: null,
subtypes: {
general: '通用',
},
},
};
// 辅助函数:根据 business_type 获取关联表名
function getBusinessTable(businessType) {
return BUSINESS_TYPES[businessType]?.table || null;
}
// 辅助函数:校验 business_type + business_sub_type 组合是否合法
function isValidSubType(businessType, businessSubType) {
const def = BUSINESS_TYPES[businessType];
return def && Object.prototype.hasOwnProperty.call(def.subtypes, businessSubType);
}
module.exports = { BUSINESS_TYPES, getBusinessTable, isValidSubType };
```
### 5.2 使用示例
```javascript
// 外部读取
const { BUSINESS_TYPES, getBusinessTable, isValidSubType } = require('./app/model/after_sale_work_order');
// 获取所有业务类型列表
Object.keys(BUSINESS_TYPES); // ['waybill', 'order_delivery', 'entry_order', ...]
// 获取运单下的子类型
BUSINESS_TYPES.waybill.subtypes; // { intercept: '拦截', urge: '催件', ... }
// 获取关联表
const table = getBusinessTable('waybill'); // 'wms_order_express'
// 校验合法性
isValidSubType('waybill', 'intercept'); // true
isValidSubType('waybill', 'mis_shipment'); // false
```
---
## 六、与现有系统的关联
### 6.1 与业务单据的多态关联(三级定位)
```
wms_after_sale_work_order
.business_type = 'waybill'
.business_sub_type = 'intercept' ← 子类型(Model 常量定义)
.business_id = 12345 ← wms_order_express.id
.business_no = 'YD202607280001' ← 冗余单号
实际关联链路:
business_type → BUSINESS_TYPES[type].table → 确定关联表
business_id → 关联表主键
business_sub_type → 细分工单类别(如拦截/催件/破损)
示例:
├── 'waybill' / 'intercept' → wms_order_express.id
├── 'waybill' / 'urge' → wms_order_express.id
├── 'waybill' / 'damage' → wms_order_express.id
├── 'order_delivery' / 'mis_shipment' → wms_order_delivery.id
├── 'order_delivery' / 'missing_item' → wms_order_delivery.id
├── 'entry_order' / 'shortage' → wms_entry_order.id
├── 'order_stockout' / 'return_issue' → wms_order_stockout.id
├── 'receiving' / 'damage' → wms_receiving.id
└── 'other' / 'general' → 自定义
```
### 6.2 与库存交易的对账
```
售后工单.direction = 1 (入库)
→ stock_transaction.transaction_type = 'INBOUND'
→ stock_transaction.order_type = 'AFTER_SALE' (需同步在 stock_transaction 中新增此类型)
售后工单.direction = 2 (出库)
→ stock_transaction.transaction_type = 'OUTBOUND'
→ stock_transaction.order_type = 'AFTER_SALE'
```
### 6.4 与附件的关联
售后工单不新增附件字段,复用现有 `wms_file_reference` 表做多态附件关联:
```
wms_file_reference
.reference_type = 'after_sale_work_order' ← 固定标识
.reference_id = 工单 id ← wms_after_sale_work_order.id
.file_id = 文件 id ← wms_file.id
示例:一张工单可关联多张图片/多个附件(如破损照片、快递面单照片等)。
```
> `file_reference` 表已支持多态关联(`reference_type` + `reference_id`),无需新建表或字段。
### 6.5 与员工的关联
```
wms_after_sale_work_order.creator_id → account.id(创建人)
wms_after_sale_work_order.assignee_id → account.id(当前处理人)
wms_after_sale_work_order_step.operator_id → account.id(步骤操作人)
```
---
## 七、待确认事项(审阅清单)
请审阅时重点关注以下设计决策:
- [x] **1. `business_type` 枚举值**:`order_delivery` / `entry_order` / `order_stockout` / `waybill` / `receiving` / `other` — ✅ 已确认,暂不增加 `return_order` 独立类型(退货场景通过 `order_stockout` 覆盖)
- [x] **2. `direction` 记账方向**:`1`=入库 / `2`=出库 / `0`=未确定 — ✅ 已确认,细粒度区分由关联的实际出入库单承载
- [x] **3. 工单状态值**:`0-待处理/1-处理中/2-已完成/3-已关闭/9-已取消` — ✅ 已确认,当前中间态足够,无需增加"驳回/退回"
- [x] **4. 预设步骤模板**:不再预设步骤模板,步骤由业务逻辑动态创建 ✅
- [x] **5. `business_id` 多态关联**:采用 `business_type` + `business_sub_type` + `business_id` 三级多态关联,子类型由 Model 常量定义 ✅
- [x] **6. 理赔信息**:已新增 `claim_needed` / `claim_amount` / `claim_status` 三个字段 ✅
- [x] **7. 进度追踪**:进度由主表 `current_step` 字段承载(不再仅依赖副表步骤状态) ✅
- [x] **8. 优先级**:改为 `TINYINT UNSIGNED` 取值范围 `1-100`,由客服或 AI 自动识别填入,默认值 `50` ✅
- [x] **9. AI 创建支持**:`creator_id = 0` 表示 AI 自动接待,`creator_snapshot` 记录模型/会话信息 ✅
- [x] **10. 附件/图片**:复用现有 `wms_file_reference` 表做多态关联,不新增字段 ✅
- [x] **11. 预计完成时间**:暂不增加,后续通过 `created_at` + `priority` 做超时告警替代;SLA 配置表留待后续迭代 ✅
- [x] **12. 关联工单**:已确认新增 `parent_work_order_id` 字段,支持主子工单拆分 ✅
- [x] **13. 表名**:`wms_after_sale_work_order` 和 `wms_after_sale_work_order_step` — ✅ 已确认
- [x] **14. 权限**:API 接口设计阶段再补录 `wms_permission` 记录,不阻塞表落库 ✅
---
## 八、后续落库计划(审阅通过后执行)
1. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order.js`
2. 创建迁移文件 `database/migrations/20260728XXXXXX-create-wms-after-sale-work-order-step.js`
3. 创建 Model 文件 `app/model/after_sale_work_order.js`
4. 创建 Model 文件 `app/model/after_sale_work_order_step.js`
5. 在 `methods/system.json` 中新增接口路由
6. 如需,在 `stock_transaction.order_type` 中新增 `AFTER_SALE` 枚举值(独立迁移)
7. 如需,新增 `wms_permission` 权限记录

View File

@ -5,7 +5,7 @@ module.exports = {
// 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+
// 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大
await queryInterface.sequelize.query(
"ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000"
'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000'
);
},

View File

@ -13,7 +13,7 @@ module.exports = {
});
},
down: async (queryInterface) => {
down: async queryInterface => {
await queryInterface.removeColumn(TABLE_NAME, 'type');
},
};

View File

@ -149,7 +149,7 @@ module.exports.up = async queryInterface => {
}
console.log(
`[Migration] 面单余额导出权限迁移完成:` +
'[Migration] 面单余额导出权限迁移完成:' +
`新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色`
);
};

View File

@ -21,7 +21,7 @@ module.exports = {
// 2. 查询刚插入的权限 ID
const [ rows ] = await queryInterface.sequelize.query(
`SELECT id FROM wms_permission WHERE path IN ('print_computer.list', 'print_computer.update', 'print_computer.delete') ORDER BY id`
'SELECT id FROM wms_permission WHERE path IN (\'print_computer.list\', \'print_computer.update\', \'print_computer.delete\') ORDER BY id'
);
const ids = rows.map(r => r.id);
if (ids.length !== 3) {

View File

@ -20,7 +20,7 @@ module.exports = {
// 2. 查询刚插入的权限 ID
const [ rows ] = await queryInterface.sequelize.query(
`SELECT id FROM wms_permission WHERE path IN ('print_computer.setRecording', 'print_computer.cancelRecording') ORDER BY id`
'SELECT id FROM wms_permission WHERE path IN (\'print_computer.setRecording\', \'print_computer.cancelRecording\') ORDER BY id'
);
const ids = rows.map(r => r.id);
if (ids.length !== 2) {

View File

@ -29,7 +29,7 @@ module.exports = {
}
},
down: async (queryInterface) => {
down: async queryInterface => {
const tableInfo = await queryInterface.describeTable('wms_inbox_group');
if (tableInfo.express_interfaces) {

View File

@ -18,7 +18,7 @@ module.exports = {
},
// eslint-disable-next-line no-unused-vars
down: async (queryInterface) => {
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

@ -29,7 +29,7 @@ module.exports = {
}
},
down: async (queryInterface) => {
down: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE);
if (columns.express_code) {

View File

@ -12,7 +12,7 @@
* 授权角色:经理(8)、仓库组-主管(26)、客服组-主管(28)、生产组-主管(29)、客服组-员工(30)
*/
module.exports = {
up: async (queryInterface) => {
up: async queryInterface => {
// ===== 第一步:写入权限行 =====
const perms = [
[ 504, 'storage.stockout.list', '出库单列表' ],
@ -50,7 +50,7 @@ module.exports = {
}
},
down: async (queryInterface) => {
down: async queryInterface => {
// 移除授权
const roleIds = [ 8, 26, 28, 29, 30 ];
const permIdStr = '504, 505, 506, 507';

View File

@ -38,7 +38,7 @@ module.exports = {
}
},
down: async (queryInterface) => {
down: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE);
if (columns.express_name) {

View File

@ -1,14 +1,18 @@
'use strict';
'use strict';
const TABLE_NAME = 'wms_after_sale_work_order';
const TABLE_MAIN = 'wms_after_sale_work_order';
const TABLE_STEP = 'wms_after_sale_work_order_step';
module.exports = {
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.dropTable(TABLE_STEP);
await queryInterface.dropTable(TABLE_MAIN);
},
await queryInterface.createTable(TABLE_NAME, {
down: async (queryInterface, Sequelize) => {
// ========== 1. 重建主表:wms_after_sale_work_order ==========
await queryInterface.createTable(TABLE_MAIN, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
@ -152,64 +156,101 @@ module.exports = {
},
});
// 工单号唯一
await queryInterface.addIndex(TABLE_NAME, ['work_order_no'], {
unique: true,
name: 'uk_work_order_no',
});
await queryInterface.addIndex(TABLE_MAIN, ['work_order_no'], { unique: true, name: 'uk_work_order_no' });
await queryInterface.addIndex(TABLE_MAIN, ['warehouse_id'], { name: 'idx_warehouse_id' });
await queryInterface.addIndex(TABLE_MAIN, ['store_id'], { name: 'idx_store_id' });
await queryInterface.addIndex(TABLE_MAIN, ['business_type', 'business_sub_type', 'business_id'], { name: 'idx_business_type_subtype_id' });
await queryInterface.addIndex(TABLE_MAIN, ['status'], { name: 'idx_status' });
await queryInterface.addIndex(TABLE_MAIN, ['assignee_id'], { name: 'idx_assignee_id' });
await queryInterface.addIndex(TABLE_MAIN, ['parent_work_order_id'], { name: 'idx_parent_work_order_id' });
await queryInterface.addIndex(TABLE_MAIN, ['priority'], { name: 'idx_priority' });
await queryInterface.addIndex(TABLE_MAIN, ['claim_status'], { name: 'idx_claim_status' });
await queryInterface.addIndex(TABLE_MAIN, ['created_at'], { name: 'idx_created_at' });
await queryInterface.addIndex(TABLE_MAIN, ['deleted_at'], { name: 'idx_deleted_at' });
// 仓库隔离查询
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], {
name: 'idx_warehouse_id',
});
// 货主隔离查询
await queryInterface.addIndex(TABLE_NAME, ['store_id'], {
name: 'idx_store_id',
});
// 按业务类型+子类型+单据ID反查工单
await queryInterface.addIndex(TABLE_NAME, ['business_type', 'business_sub_type', 'business_id'], {
name: 'idx_business_type_subtype_id',
});
// 按状态筛选
await queryInterface.addIndex(TABLE_NAME, ['status'], {
name: 'idx_status',
});
// 按处理人查询
await queryInterface.addIndex(TABLE_NAME, ['assignee_id'], {
name: 'idx_assignee_id',
});
// 按父工单查子工单
await queryInterface.addIndex(TABLE_NAME, ['parent_work_order_id'], {
name: 'idx_parent_work_order_id',
});
// 按优先级排序
await queryInterface.addIndex(TABLE_NAME, ['priority'], {
name: 'idx_priority',
});
// 按理赔状态筛选
await queryInterface.addIndex(TABLE_NAME, ['claim_status'], {
name: 'idx_claim_status',
});
// 按时间排序
await queryInterface.addIndex(TABLE_NAME, ['created_at'], {
name: 'idx_created_at',
});
// 软删除查询优化
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], {
name: 'idx_deleted_at',
});
// ========== 2. 重建子表:wms_after_sale_work_order_step ==========
await queryInterface.createTable(TABLE_STEP, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
work_order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工单ID,关联 wms_after_sale_work_order.id',
},
step_order: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '步骤序号(从1开始递增)',
},
step_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '步骤名称',
},
step_status: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过',
},
operator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作员工ID,关联 account.id',
},
operator_snapshot: {
type: Sequelize.TEXT,
allowNull: true,
comment: '操作人信息快照(JSON格式)',
},
action: {
type: Sequelize.STRING(100),
allowNull: true,
comment: '操作动作描述',
},
remark: {
type: Sequelize.TEXT,
allowNull: true,
comment: '处理备注',
},
started_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '步骤开始时间',
},
completed_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '步骤完成时间',
},
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: '软删除时间',
},
});
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
await queryInterface.addIndex(TABLE_STEP, ['work_order_id'], { name: 'idx_work_order_id' });
await queryInterface.addIndex(TABLE_STEP, ['operator_id'], { name: 'idx_operator_id' });
await queryInterface.addIndex(TABLE_STEP, ['deleted_at'], { name: 'idx_deleted_at' });
await queryInterface.addIndex(TABLE_STEP, ['work_order_id', 'step_order', 'deleted_at'], { unique: true, name: 'uk_work_order_step' });
},
};

View File

@ -0,0 +1,293 @@
'use strict';
const TABLE_NAME = 'wms_after_sale';
module.exports = {
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: '主键',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID',
},
store_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '货主ID',
},
after_sale_no: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后单号,唯一,生成规则:AS+YYYYMMDD+6位序号',
},
type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '售后类型:order/receiving/entry/stockout',
},
sub_type: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后子类型,与 type 组成二级分类',
},
status: {
type: Sequelize.STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '售后状态:pending/processing/completed/closed/cancelled',
},
priority: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '优先级,数值越大越优先(0=普通,10=紧急)',
},
title: {
type: Sequelize.STRING(200),
allowNull: false,
comment: '售后标题/简要描述',
},
description: {
type: Sequelize.TEXT,
allowNull: true,
defaultValue: null,
comment: '售后详细描述',
},
creator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人账户ID',
},
role_group: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '当前处理角色组:customer_service/warehouse/finance',
},
inbox_message_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '关联站内信消息ID(wms_inbox_message.id)',
},
resolution: {
type: Sequelize.TEXT,
allowNull: true,
defaultValue: null,
comment: '最终处理结果说明',
},
resolved_at: {
type: Sequelize.DATE,
allowNull: true,
defaultValue: null,
comment: '完结时间(状态变为 completed 时写入)',
},
claim_needed: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '仓库理赔标记:0=不需要,1=需要',
},
claim_amount: {
type: Sequelize.DECIMAL(12, 2),
allowNull: true,
defaultValue: null,
comment: '仓库理赔金额,单位:元',
},
claim_status: {
type: Sequelize.STRING(20),
allowNull: true,
defaultValue: null,
comment: '仓库理赔状态:pending/reviewing/approved/paid/monthly/rejected',
},
carrier_claim_needed: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '运方理赔标记:0=不需要,1=需要',
},
carrier_claim_amount: {
type: Sequelize.DECIMAL(12, 2),
allowNull: true,
defaultValue: null,
comment: '运方理赔金额,单位:元',
},
carrier_claim_status: {
type: Sequelize.STRING(20),
allowNull: true,
defaultValue: null,
comment: '运方理赔状态:pending/reviewing/approved/paid/monthly/rejected',
},
waybill_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '运单ID(关联 wms_order_express.id)',
},
waybill_no: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '运单号(冗余)',
},
order_delivery_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '发货订单ID(关联 wms_order_delivery.id)',
},
order_delivery_no: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '发货订单号(冗余)',
},
entry_order_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '入库单ID(关联 wms_entry_order.id)',
},
entry_order_no: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '入库单号(冗余)',
},
order_stockout_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '出库单ID(关联 wms_order_stockout.id)',
},
order_stockout_no: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '出库单号(冗余)',
},
receiving_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '收货单ID(关联 wms_receiving.id)',
},
receiving_no: {
type: Sequelize.STRING(50),
allowNull: true,
defaultValue: null,
comment: '收货单号(冗余)',
},
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,
defaultValue: null,
comment: '软删除时间',
},
});
// 唯一索引 — 售后单号
await queryInterface.addIndex(TABLE_NAME, ['after_sale_no'], {
unique: true,
name: 'uk_after_sale_no',
});
// 仓库+状态查询(最高频)
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'status', 'deleted_at'], {
name: 'idx_warehouse_status',
});
// 仓库+类型筛选
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'deleted_at'], {
name: 'idx_warehouse_type',
});
// 仓库+类型+子类型筛选
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'type', 'sub_type', 'deleted_at'], {
name: 'idx_type_subtype',
});
// 货主查询
await queryInterface.addIndex(TABLE_NAME, ['store_id', 'deleted_at'], {
name: 'idx_store_id',
});
// 创建人查询
await queryInterface.addIndex(TABLE_NAME, ['creator_id', 'deleted_at'], {
name: 'idx_creator_id',
});
// 角色组+状态查询
await queryInterface.addIndex(TABLE_NAME, ['role_group', 'status', 'deleted_at'], {
name: 'idx_role_group',
});
// 仓库+时间排序分页
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'created_at'], {
name: 'idx_created_at',
});
// 运单反查
await queryInterface.addIndex(TABLE_NAME, ['waybill_id'], {
name: 'idx_waybill_id',
});
// 发货订单反查
await queryInterface.addIndex(TABLE_NAME, ['order_delivery_id'], {
name: 'idx_order_delivery_id',
});
// 入库单反查
await queryInterface.addIndex(TABLE_NAME, ['entry_order_id'], {
name: 'idx_entry_order_id',
});
// 出库单反查
await queryInterface.addIndex(TABLE_NAME, ['order_stockout_id'], {
name: 'idx_order_stockout_id',
});
// 收货单反查
await queryInterface.addIndex(TABLE_NAME, ['receiving_id'], {
name: 'idx_receiving_id',
});
// 运方理赔状态筛选
await queryInterface.addIndex(TABLE_NAME, ['carrier_claim_status'], {
name: 'idx_carrier_claim_status',
});
// 站内信消息反查
await queryInterface.addIndex(TABLE_NAME, ['inbox_message_id'], {
name: 'idx_inbox_message_id',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,6 +1,6 @@
'use strict';
'use strict';
const TABLE_NAME = 'wms_after_sale_work_order_step';
const TABLE_NAME = 'wms_after_sale_detail';
module.exports = {
up: async (queryInterface, Sequelize) => {
@ -14,58 +14,53 @@ module.exports = {
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
comment: '主键',
},
work_order_id: {
after_sale_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '工单ID,关联 wms_after_sale_work_order.id',
},
step_order: {
type: Sequelize.TINYINT.UNSIGNED,
allowNull: false,
defaultValue: 1,
comment: '步骤序号(从1开始递增)',
},
step_name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '步骤名称',
comment: '关联售后主表ID(wms_after_sale.id)',
},
step_status: {
type: Sequelize.TINYINT.UNSIGNED,
type: Sequelize.TINYINT(3).UNSIGNED,
allowNull: false,
defaultValue: 0,
comment: '步骤状态:0=待开始 1=进行中 2=已完成 3=已跳过',
comment: '步骤状态:0=待开始,1=进行中,2=已完成,3=已跳过',
},
operator_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '操作员工ID,关联 account.id',
defaultValue: null,
comment: '操作人账户ID(关联 accounts 表)',
},
operator_snapshot: {
type: Sequelize.TEXT,
allowNull: true,
comment: '操作人信息快照(JSON格式)',
defaultValue: null,
comment: '操作人信息快照(JSON),防止账户删除后历史丢失',
},
action: {
type: Sequelize.STRING(100),
allowNull: true,
defaultValue: null,
comment: '操作动作描述',
},
remark: {
type: Sequelize.TEXT,
allowNull: true,
defaultValue: null,
comment: '处理备注',
},
started_at: {
type: Sequelize.DATE,
allowNull: true,
defaultValue: null,
comment: '步骤开始时间',
},
completed_at: {
type: Sequelize.DATE,
allowNull: true,
defaultValue: null,
comment: '步骤完成时间',
},
created_at: {
@ -83,30 +78,20 @@ module.exports = {
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
defaultValue: null,
comment: '软删除时间',
},
});
// 按工单查所有步骤
await queryInterface.addIndex(TABLE_NAME, ['work_order_id'], {
name: 'idx_work_order_id',
// 按售后单查询进度步骤(最高频)
await queryInterface.addIndex(TABLE_NAME, ['after_sale_id'], {
name: 'idx_after_sale_id',
});
// 按操作人反查
// 按操作人查询
await queryInterface.addIndex(TABLE_NAME, ['operator_id'], {
name: 'idx_operator_id',
});
// 软删除查询优化
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], {
name: 'idx_deleted_at',
});
// 同一工单下步骤序号唯一(含软删除)
await queryInterface.addIndex(TABLE_NAME, ['work_order_id', 'step_order', 'deleted_at'], {
unique: true,
name: 'uk_work_order_step',
});
},
down: async queryInterface => {

View File

@ -0,0 +1,97 @@
'use strict';
/**
* 新增售后模块权限记录(固定 ID 策略,确保开发/生产一致)。
*
* 新增权限明细:
* Block(角色组维度):
* 516 — 售后-客服组
* 517 — 售后-仓库组
* 518 — 售后-财务组
*
* Web Pages(菜单/页面):
* 519 — afterSale 售后管理(根菜单)
* 520 — afterSale.list 售后列表
* 521 — afterSale.detail 售后明细
*
* API:
* 522 — afterSale.workList API:售后工作列表查询
* 523 — afterSale.auditList API:售后审计列表查询
* 508 — afterSale.detail API:售后明细查询
* 509 — afterSale.create API:创建售后单
* 510 — afterSale.update API:更新售后单
* 511 — afterSale.transfer API:售后转单
* 512 — afterSale.handleWorkOrder API:处理工单
* 513 — afterSale.registerClaim API:登记理赔
* 514 — afterSale.export API:售后导出
* 515 — afterSale.exportTaskProgress API:导出进度查询
*
* 幂等设计:使用 INSERT IGNORE,已存在的 id 不会重复插入。
*/
const TABLE = 'wms_permission';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. Block 权限(角色组维度,用于权限分配分组)──
const blocks = [
[516, null, null, '售后-客服组', null, '售后-客服组', null, 0, 0, null, 'block', 0, 1],
[517, null, null, '售后-仓库组', null, '售后-仓库组', null, 0, 0, null, 'block', 0, 1],
[518, null, null, '售后-财务组', null, '售后-财务组', null, 0, 0, null, 'block', 0, 1],
];
for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of blocks) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] }
);
}
// ── 2. Web Pages 权限(菜单/页面)──
const pages = [
[519, 'afterSale', null, 'afterSale', null, '售后管理', null, 0, 0, null, 'web_pages', 14, 1],
[520, 'afterSale.list', null, 'afterSale.list', null, '售后列表', null, 0, 0, 519, 'web_pages', 0, 1],
[521, 'afterSale.detail', null, 'afterSale.detail', null, '售后明细', null, 0, 0, 519, 'web_pages', 1, 1],
];
for (const [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] of pages) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status] }
);
}
// ── 3. API 权限 ──
const apis = [
[522, 'afterSale.workList', 'API:售后工作列表查询'],
[523, 'afterSale.auditList', 'API:售后审计列表查询'],
[508, 'afterSale.detail', 'API:售后明细查询'],
[509, 'afterSale.create', 'API:创建售后单'],
[510, 'afterSale.update', 'API:更新售后单'],
[511, 'afterSale.transfer', 'API:售后转单'],
[512, 'afterSale.handleWorkOrder', 'API:处理工单'],
[513, 'afterSale.registerClaim', 'API:登记理赔'],
[514, 'afterSale.export', 'API:售后导出'],
[515, 'afterSale.exportTaskProgress', 'API:导出进度查询'],
];
for (const [id, path, meta_title] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [id, path, null, path, null, meta_title, null, 0, 0, null, 'api', 0, 1] }
);
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
const ids = [516, 517, 518, 519, 520, 521, 522, 523, 508, 509, 510, 511, 512, 513, 514, 515];
const placeholders = ids.map(() => '?').join(', ');
await queryInterface.sequelize.query(
`DELETE FROM \`${TABLE}\` WHERE id IN (${placeholders})`,
{ replacements: ids }
);
},
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -94,7 +94,7 @@ async function grantPermission(conn, permId, envLabel) {
try {
perms = JSON.parse(record.permissions);
} catch {
results.push({ role, status: 'error', msg: `permissions JSON 解析失败` });
results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' });
continue;
}

View File

@ -127,7 +127,7 @@ async function main() {
console.log('═══════════════════════════════════════');
console.log(` 权限 ID: ${permIdNum}`);
console.log(` 目标角色: ${CS_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`);
console.log(` 通配符角色(跳过): id=7,2 (已有 *)`);
console.log(' 通配符角色(跳过): id=7,2 (已有 *)');
console.log('═══════════════════════════════════════\n');
// ── 开发环境:查询权限信息 ──

View File

@ -7,6 +7,7 @@ const PendingOrderService = require('../../../../../app/service/systemMethods/or
* 创建 manualWaybill 操作日志回归测试上下文。
*
* 仅覆盖 operationLog.createOperationLog 的 businessId 传入值。
* @param options
*/
function createManualWaybillLogHarness(options = {}) {
const calls = {
@ -103,14 +104,14 @@ function createManualWaybillLogHarness(options = {}) {
},
});
service.buildOrderWhere = (orderIds) => ({
service.buildOrderWhere = orderIds => ({
id: { [ctx.app.Sequelize.Op.in]: orderIds },
warehouse_id: warehouseId,
});
service.success = (msg, data) => ({ code: 0, msg, data });
service.syncOrderIds = (payload) => {
service.syncOrderIds = payload => {
calls.syncOrderIdsPayload = payload;
return Promise.resolve();
};