WMS_MAIN/app/service/systems/afterSale.js
liufumingren f1a487bb06 feat(returnUnpack): 原单 items 顶层透出与订单序列表车道定位
- create 新增顶层 order_items 字段(原订单商品明细,order.items 顶层透出),新建/幂等复用分支返回结构一致,非原单退回为 null
- 原订单详情解析优先按订单 id 序列表(wms_order_id_location_{warehouseId})定位车道(current/history/dispatch/outsourced)直接查分表,未命中再遍历四车道、最后回退基表;修复订单位于 history/dispatch 车道时 create/detail 返回 order=null、order_items=null
- _resolveReturnOrderInfo 原订单兜底查询同步改造(查退回交易单号/快递信息)
- 同步 methods/system.json 与 methods/changes/system.json 变更记录
2026-08-21 23:03:04 +08:00

2176 lines
77 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
/**
* 售后模块业务逻辑层。
* 负责 wms_after_sale / wms_after_sale_detail 的 CRUD、附件绑定等核心操作。
* 所有数据库交互集中在此层,供 systemMethods/afterSale.js 调用。
*/
class AfterSaleService extends Service {
// ===========================
// 列表查询
// ===========================
/**
* 售后单列表查询,支持 where 条件、分页、排序。
*
* @param {Object} where 标准化 where 条件对象
* @param {Object} [where.after_sale_no] 售后单号条件
* @param {Object} [where.type] 售后类型条件
* @param {Object} [where.sub_type] 售后子类型条件
* @param {Object} [where.status] 售后状态条件
* @param {Object} [where.priority] 优先级条件
* @param {Object} [where.role_group] 角色组条件
* @param {Object} [where.waybill_no] 运单号条件
* @param {Object} [where.claim_status] 仓库理赔状态条件
* @param {Object} [where.carrier_claim_status] 运方理赔状态条件
* @param {Object} [where.quickWhere] 快捷搜索条件
* @param {Object} [where.warehouse_id] 仓库ID(由方法层注入)
* @param {Object} [pagination] 分页参数
* @param {number} [pagination.page=1] 页码
* @param {number} [pagination.pageSize=20] 每页数量
* @param {Object} [sort] 排序参数
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sortOrder] 排序顺序(asc/desc)
* @param {Object} [opts] 额外选项
* @param {Array<Array>} [opts.order] 自定义 Sequelize order(优先于 sort)
* @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单
* @param {boolean} [opts.enrichStoreName] 是否补充每行 store_name 货主名称(合约表货主备注 store_remask,无备注时回退货主公司全称)
* @return {Promise<Object>} { list: Array, pagination: Object }
*/
async list(where = {}, pagination = {}, sort = {}, opts = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const page = Math.max(1, parseInt(pagination.page) || 1);
const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20));
// 构建 Sequelize where 条件
const queryWhere = this._buildListWhere(where, Op);
// 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不显示
if (opts.excludeFutureFollowup) {
const pendingFeedbackWhere = {
[Op.or]: [
{ status: { [Op.ne]: 'pending_feedback' } },
{
status: 'pending_feedback',
[Op.or]: [
{ followup_at: null },
{ followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } },
],
},
],
};
// 合并到现有 where 中(AND 关系)
if (queryWhere[Op.and]) {
queryWhere[Op.and].push(pendingFeedbackWhere);
} else {
queryWhere[Op.and] = [ pendingFeedbackWhere ];
}
}
// 排序:opts.order 优先于 sort
const order = Array.isArray(opts.order) && opts.order.length > 0
? opts.order
: this._buildListOrder(sort);
const { count, rows } = await ctx.model.AfterSale.findAndCountAll({
where: queryWhere,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
});
const totalPages = Math.ceil(count / pageSize);
const list = rows.map(row => this._formatAfterSaleRow(row, app));
// 工作列表:批量补充货主名称(合约表 store_remask 货主备注,无备注时回退货主公司全称)
if (opts.enrichStoreName && list.length > 0) {
await this._enrichListStoreNames(list);
}
return {
list,
pagination: {
page,
pageSize,
total: count,
totalPages,
hasPrevious: page > 1,
hasNext: page * pageSize < count,
},
};
}
/**
* 快速统计符合条件的售后单数量(用于角标显示,不做分页)。
* 与 list() 共享相同的 where 构建逻辑,但只返回 count。
*
* @param {Object} where 标准化 where 条件对象
* @param {Object} [opts] 额外选项
* @param {boolean} [opts.excludeFutureFollowup] 是否排除 followup_at 未到的 pending_feedback 工单
* @return {Promise<Object>} { count: number }
*/
async countPending(where = {}, opts = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const queryWhere = this._buildListWhere(where, Op);
// 工作列表特殊逻辑:pending_feedback 状态的工单,若 followup_at 未到,暂不计数
if (opts.excludeFutureFollowup) {
const pendingFeedbackWhere = {
[Op.or]: [
{ status: { [Op.ne]: 'pending_feedback' } },
{
status: 'pending_feedback',
[Op.or]: [
{ followup_at: null },
{ followup_at: { [Op.lte]: app.Sequelize.literal('NOW()') } },
],
},
],
};
if (queryWhere[Op.and]) {
queryWhere[Op.and].push(pendingFeedbackWhere);
} else {
queryWhere[Op.and] = [ pendingFeedbackWhere ];
}
}
const count = await ctx.model.AfterSale.count({
where: queryWhere,
});
return { count };
}
/**
* 根据标准化 where 条件构建 Sequelize 查询条件。
*
* @param {Object} where 标准化 where 条件对象
* @param {Object} Op Sequelize Op 对象
* @return {Object} Sequelize where 条件
*/
_buildListWhere(where = {}, Op) {
const queryWhere = {};
// 软删除过滤
queryWhere.deleted_at = null;
// 直接映射字段
const directFields = [
'type', 'sub_type', 'status', 'priority', 'role_group',
'claim_status', 'carrier_claim_status', 'after_sale_no',
'waybill_no', 'order_delivery_no', 'entry_order_no',
'order_stockout_no', 'receiving_no', 'warehouse_id',
'store_id', 'creator_id',
];
for (const field of directFields) {
if (where[field] !== undefined && where[field] !== null) {
queryWhere[field] = this._resolveConditionValue(where[field], Op);
}
}
// 快捷搜索:在 after_sale_no / title / waybill_no 等字段中模糊搜索
if (where.quickWhere !== undefined && where.quickWhere !== null) {
const quickValue = this._extractConditionValue(where.quickWhere);
if (quickValue !== undefined && quickValue !== null && String(quickValue).trim() !== '') {
const likePattern = { [Op.like]: `%${String(quickValue).trim()}%` };
queryWhere[Op.or] = [
{ after_sale_no: likePattern },
{ title: likePattern },
{ waybill_no: likePattern },
{ order_delivery_no: likePattern },
{ entry_order_no: likePattern },
{ order_stockout_no: likePattern },
{ receiving_no: likePattern },
];
}
}
return queryWhere;
}
/**
* 解析标准化条件值为 Sequelize 可用的条件对象。
*
* @param {*} condition 标准化条件(可能是 {operator, value} 或直接值)
* @param {Object} Op Sequelize Op 对象
* @return {*} Sequelize 条件
*/
_resolveConditionValue(condition, Op) {
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
const operator = condition.operator;
const value = condition.value;
if (!operator) {
return value;
}
switch (operator) {
case 'eq':
return value;
case 'ne':
return { [Op.ne]: value };
case 'in':
return { [Op.in]: Array.isArray(value) ? value : [ value ] };
case 'notin':
return { [Op.notIn]: Array.isArray(value) ? value : [ value ] };
case 'like':
return { [Op.like]: `%${value}%` };
case 'gt':
return { [Op.gt]: value };
case 'gte':
return { [Op.gte]: value };
case 'lt':
return { [Op.lt]: value };
case 'lte':
return { [Op.lte]: value };
case 'between':
return { [Op.between]: Array.isArray(value) ? value : [ value ] };
default:
return value;
}
}
return condition;
}
/**
* 从条件对象中提取原始 value。
*
* @param {*} condition 标准化条件
* @return {*} 原始值
*/
_extractConditionValue(condition) {
if (condition && typeof condition === 'object' && !Array.isArray(condition)) {
if ('value' in condition) {
return condition.value;
}
}
return condition;
}
/**
* 根据 sort 参数构建 Sequelize 排序数组。
*
* @param {Object} sort 排序参数
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sort_order] 排序顺序
* @param {string} [sort.sortOrder] 排序顺序(驼峰)
* @return {Array<Array<string>>} Sequelize order 数组
*/
_buildListOrder(sort = {}) {
const sortField = sort.sortField || sort.sort_field || 'updated_at';
const sortOrderRaw = (sort.sortOrder || sort.sort_order || 'desc').toLowerCase();
const sortOrder = sortOrderRaw === 'asc' ? 'ASC' : 'DESC';
// 允许排序的字段白名单
const allowedSortFields = new Set([
'id', 'after_sale_no', 'type', 'sub_type', 'status', 'priority',
'role_group', 'created_at', 'updated_at', 'resolved_at',
'claim_status', 'carrier_claim_status',
]);
const safeSortField = allowedSortFields.has(sortField) ? sortField : 'created_at';
return [[ safeSortField, sortOrder ]];
}
// ===========================
// 明细查询
// ===========================
/**
* 售后单明细查询,包含主表信息、步骤列表及附件。
* 售后主表 description(详细描述)非空时,默认作为第一条 step 输出
* (虚拟步骤:id=null、is_virtual=true、action=售后描述、remark=description,不落库)。
* 若关联了订单(order_delivery_id),自动补充收件人/发件人/订单明细/打包视频。
* 若关联了货主(store_id),自动补充货主合约备注。
*
* @param {number} id 售后单主键ID
* @return {Promise<Object>} 售后单明细,包含主表、步骤列表(含附件)、关联单据详情
* @throws {Error} 售后单不存在时抛出
*/
async getDetail(id) {
const { ctx, app } = this;
// 查询主表
const afterSale = await ctx.model.AfterSale.findOne({
where: { id, deleted_at: null },
raw: true,
});
if (!afterSale) {
throw new Error('售后单不存在');
}
// 查询步骤列表(按创建时间升序)
const steps = await ctx.model.AfterSaleDetail.findAll({
where: { after_sale_id: id, deleted_at: null },
order: [[ 'created_at', 'ASC' ]],
raw: true,
});
// 查询步骤附件
const stepsWithAttachments = await this._enrichStepsWithAttachments(steps);
// 格式化时间字段
const formatRow = row => this._formatAfterSaleRow(row, app);
// 补充关联单据详情
const related = await this._enrichAfterSaleDetail(afterSale);
// 默认详细描述作为第一条 step 输出(虚拟步骤,不落库)
let finalSteps = stepsWithAttachments;
if (afterSale.description && String(afterSale.description).trim()) {
finalSteps = [{
id: null,
after_sale_id: afterSale.id,
step_status: 'pending',
operator_id: null,
operator_snapshot: null,
action: '售后描述',
remark: afterSale.description,
started_at: null,
completed_at: null,
created_at: afterSale.created_at,
attachments: [],
is_virtual: true,
}, ...stepsWithAttachments ];
}
// 开始处理时间:取首条真实步骤记录的创建时间(不含默认描述虚拟步骤)
const firstStep = steps[0];
const startedAt = firstStep ? (firstStep.created_at ? app.formatDate(firstStep.created_at) : null) : null;
return {
after_sale: { ...formatRow(afterSale), started_at: startedAt },
steps: finalSteps.map(formatRow),
related,
};
}
/**
* 根据售后单关联的业务单据ID,补充关联详情。
* 包括:订单信息(收件人/发件人/明细/打包视频)、货主合约备注。
*
* @param {Object} afterSale 售后主表记录
* @return {Promise<Object>} 关联详情对象
*/
async _enrichAfterSaleDetail(afterSale) {
const { ctx } = this;
const related = {};
// ======= 1. 关联订单详情 =======
// 统一使用 order_id
const resolvedOrderId = afterSale.order_id;
if (resolvedOrderId) {
try {
related.order = await this._resolveOrderDetail(
resolvedOrderId,
afterSale.warehouse_id
);
} catch (err) {
ctx.logger.warn(`[_enrichAfterSaleDetail] 解析订单详情失败 id=${resolvedOrderId}: ${err.message}`);
}
}
// ======= 2. 关联运单详情(快递公司 + 接口) =======
if (afterSale.waybill_id) {
try {
related.waybill = await this._resolveWaybillDetail(afterSale.waybill_id);
} catch (err) {
ctx.logger.warn(`[_enrichAfterSaleDetail] 解析运单详情失败 id=${afterSale.waybill_id}: ${err.message}`);
}
}
// ======= 3. 货主合约备注 =======
if (afterSale.store_id && afterSale.warehouse_id) {
try {
related.store_contract = await this._resolveStoreContractNote(
afterSale.store_id,
afterSale.warehouse_id
);
} catch (err) {
ctx.logger.warn(`[_enrichAfterSaleDetail] 解析货主合约备注失败 store_id=${afterSale.store_id}: ${err.message}`);
}
}
return related;
}
/**
* 解析关联订单的详细信息:收件人、发件人、订单明细、打包视频。
*
* @param {number} orderDeliveryId 发货订单ID
* @param {number} warehouseId 仓库ID
* @return {Promise<Object|null>} 订单详情,查询失败返回 null
*/
async _resolveOrderDetail(orderDeliveryId, warehouseId) {
const { ctx, app } = this;
try {
// 1. 查询订单主记录:优先按订单 id 序列表(wms_order_id_location_{warehouseId})
// 定位订单所在车道直接查对应分表,未命中再按 current → history → dispatch → outsourced
// 遍历回退,最后回退基表(存量订单)
let order = null;
let preferredLane = null;
const factory = ctx.model.OrderDeliveryFactory;
if (factory && typeof factory.getCurrentModel === 'function') {
const laneLabels = [ 'current', 'history', 'dispatch', 'outsourced' ];
const laneGetters = {
current: () => factory.getCurrentModel(warehouseId),
history: () => factory.getHistoryModel(warehouseId),
dispatch: () => factory.getDispatchModel(warehouseId),
outsourced: () => factory.getOutsourcedModel(warehouseId),
};
// 序列表定位优先:命中车道先查对应分表
try {
if (typeof factory.getOrderLocation === 'function') {
const location = await factory.getOrderLocation(orderDeliveryId, warehouseId);
if (location && laneGetters[location]) {
preferredLane = String(location);
}
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 序列表定位失败: ${err.message}`);
}
const orderedLanes = preferredLane
? [ preferredLane, ...laneLabels.filter(label => label !== preferredLane) ]
: laneLabels;
for (const lane of orderedLanes) {
try {
const model = await laneGetters[lane]();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderDeliveryId },
raw: true,
});
if (row) {
order = row;
break;
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表 ${lane} 查询失败: ${err.message}`);
}
}
}
// 分表均未命中:回退基表(存量订单)
if (!order) {
try {
order = await ctx.model.OrderDelivery.findOne({
where: { id: orderDeliveryId },
raw: true,
});
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 主表查询失败: ${err.message}`);
}
}
if (!order) {
ctx.logger.info(`[_resolveOrderDetail] 未找到订单 id=${orderDeliveryId} warehouseId=${warehouseId}`);
return null;
}
ctx.logger.info(`[_resolveOrderDetail] 找到订单 id=${orderDeliveryId} code=${order.delivery_order_code} status=${order.status}`);
// 2. 构建收件人信息
const recipient = {
name: order.name || '',
tel: order.tel || '',
mobile: order.mobile || '',
email: order.email || '',
zip_code: order.zip_code || '',
country: order.country_code || '',
province: order.province || '',
city: order.city || '',
district: order.district || '',
town: order.town || '',
address: order.detail_address || '',
};
// 3. 构建发件人信息(从货主 subject_config 中取)
let sender = null;
if (order.store_id) {
try {
const store = await ctx.model.Store.findOne({
where: { id: order.store_id },
attributes: [ 'id', 'subject_config', 'company_name' ],
raw: true,
});
if (store) {
let subjectConfig = store.subject_config;
if (typeof subjectConfig === 'string') {
try { subjectConfig = JSON.parse(subjectConfig); } catch { subjectConfig = {}; }
}
sender = {
name: (subjectConfig && subjectConfig.sender_name) || store.company_name || '',
tel: (subjectConfig && subjectConfig.sender_tel) || '',
province: (subjectConfig && subjectConfig.province_name) || '',
city: (subjectConfig && subjectConfig.city_name) || '',
district: (subjectConfig && subjectConfig.district_name) || '',
town: (subjectConfig && subjectConfig.town_name) || '',
address: (subjectConfig && subjectConfig.address) || '',
};
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 查询发件人信息失败: ${err.message}`);
}
}
// 4. 订单明细(优先 order.items JSON,为空时回退到分表查询)
let orderItems = [];
if (order.items) {
try {
const parsed = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
orderItems = Array.isArray(parsed) ? parsed : [];
} catch {
// items 解析失败,忽略
}
}
// 回退:若 items 为空且 OrderItemsFactory 可用,从分表查询(序列表定位车道优先)
if (orderItems.length === 0 && ctx.model.OrderItemsFactory) {
try {
const itemsFactory = ctx.model.OrderItemsFactory;
const itemsLaneLabels = [ 'current', 'history', 'dispatch' ];
const itemsLaneGetters = {
current: () => itemsFactory.getCurrentModel(warehouseId),
history: () => itemsFactory.getHistoryModel(warehouseId),
dispatch: () => itemsFactory.getDispatchModel(warehouseId),
};
const orderedItemsLanes = preferredLane && itemsLaneGetters[preferredLane]
? [ preferredLane, ...itemsLaneLabels.filter(label => label !== preferredLane) ]
: itemsLaneLabels;
let dbItems = [];
for (const lane of orderedItemsLanes) {
try {
const itemsModel = await itemsLaneGetters[lane]();
if (!itemsModel || typeof itemsModel.findAll !== 'function') continue;
const laneRows = await itemsModel.findAll({
where: { order_id: orderDeliveryId },
raw: true,
});
if (laneRows && laneRows.length > 0) {
dbItems = laneRows;
break;
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 商品明细分表 ${lane} 查询失败: ${err.message}`);
}
}
if (dbItems.length > 0) {
// 收集 stock_id 用于批量查库存详情
const stockIds = dbItems
.map(item => Number(item.stock_id))
.filter(id => Number.isInteger(id) && id > 0);
// 批量获取库存详情(带缓存的并行查询:条码 + 图片 + 库存属性)
const stockDetailsMap = new Map();
if (stockIds.length > 0) {
try {
const details = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, {
warehouseId,
cacheTTL: 300,
});
for (const detail of details) {
stockDetailsMap.set(detail.id, detail);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 批量获取库存详情失败: ${err.message}`);
}
}
orderItems = dbItems.map(item => {
const stock = stockDetailsMap.get(Number(item.stock_id)) || {};
return {
id: item.id,
order_line_no: item.order_line_no || '',
item_code: item.item_code || stock.item_code || '',
item_name: item.item_name || stock.item_name || '',
sku_property: stock.sku_property || '',
quantity: stock.quantity || 0,
locked_quantity: stock.locked_quantity || 0,
is_batch_mgmt: stock.is_batch_mgmt || 'N',
is_shelf_life_mgmt: stock.is_shelf_life_mgmt || 'N',
is_images: stock.is_images || 'N',
store_id: stock.store_id || null,
packing_requirements: stock.packing_requirements || '',
stock_unit: stock.stock_unit || '',
image_url: stock.image_url || [],
barcodes: stock.barcodes || [],
plan_qty: item.plan_qty || 0,
stock_id: item.stock_id || null,
order_item_id: item.id,
order_id: orderDeliveryId,
};
});
ctx.logger.info(`[_resolveOrderDetail] 从分表加载 ${orderItems.length} 条明细(含库存详情)`);
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 分表查询商品明细失败: ${err.message}`);
}
}
// 5. 打包视频
const packVideos = [];
try {
const packTasks = await ctx.model.PackTask.findAll({
where: { order_id: orderDeliveryId, deleted_at: null },
include: [
{
model: ctx.model.PackTaskVideo,
as: 'videos',
where: { deleted_at: null },
required: false,
},
],
order: [[ 'create_time', 'DESC' ]],
raw: false,
});
for (const task of packTasks) {
const taskJson = task.toJSON ? task.toJSON() : task;
const videos = (taskJson.videos || []).map(v => ({
id: v.id,
video_url: v.video_url,
camera_id: v.camera_id,
status: v.status,
created_at: v.created_at ? app.formatDate(v.created_at) : null,
}));
packVideos.push({
pack_task_id: taskJson.id,
status: taskJson.status,
pack_quantity: taskJson.pack_quantity,
start_time: taskJson.start_time ? app.formatDate(taskJson.start_time) : null,
end_time: taskJson.end_time ? app.formatDate(taskJson.end_time) : null,
operator_text: taskJson.operator_text || '',
videos,
});
}
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 查询打包视频失败: ${err.message}`);
}
// 6. 组装返回
return {
id: order.id,
delivery_order_code: order.delivery_order_code || '',
warehouse_id: order.warehouse_id,
store_id: order.store_id,
// 重量(g)
items_weight: order.items_weight || 0,
// 波次
wave_id: order.wave_id || 0,
wave_no: order.wave_no || '',
// 来源
platform_name: order.source_platform_name || '',
source_order_codes: order.source_order_codes || '',
// 创建来源渠道
create_channel: order.create_channel || '',
create_channel_label: this._getCreateChannelLabel(order.create_channel),
// 状态机
sync_status: order.sync_status || 'padding',
inspection_status: order.inspection_status || 'none',
storage_status: order.storage_status || 'none',
post_status: order.post_status || 'none',
print_status: order.print_status || 'none',
pick_status: order.pick_status || 'none',
pack_status: order.pack_status || 'none',
intercept_status: order.intercept_status || 'none',
// 数量
items_count: order.items_count,
items_total: order.items_total,
// 金额
total_amount: order.total_amount,
item_amount: order.item_amount,
// 收件人 / 发件人 / 明细 / 打包视频
recipient,
sender,
items: orderItems,
pack_videos: packVideos,
};
} catch (err) {
ctx.logger.warn(`[_resolveOrderDetail] 整体异常 id=${orderDeliveryId}: ${err.message}`, err.stack);
return null;
}
}
/**
* 解析货主在当前仓库下的合约备注。
*
* @param {number} storeId 货主ID
* @param {number} warehouseId 仓库ID
* @return {Promise<Object|null>} 合约备注信息
*/
async _resolveStoreContractNote(storeId, warehouseId) {
const { ctx } = this;
const sw = await ctx.model.StoreWarehouse.findOne({
where: { store_id: storeId, warehouse_id: warehouseId },
attributes: [ 'id', 'store_remask', 'warehouse_remask', 'store_use_status', 'warehouse_use_status' ],
raw: true,
});
if (!sw) return null;
return {
contract_id: sw.id,
store_remask: sw.store_remask || '',
warehouse_remask: sw.warehouse_remask || '',
store_use_status: sw.store_use_status,
warehouse_use_status: sw.warehouse_use_status,
};
}
/**
* 解析关联运单的快递公司名称与使用的物流接口。
*
* @param {number} waybillId 运单ID(wms_order_express.id)
* @return {Promise<Object|null>} 运单详情,查询失败返回 null
*/
async _resolveWaybillDetail(waybillId) {
const { ctx } = this;
const waybill = await ctx.model.OrderExpress.findOne({
where: { id: waybillId },
attributes: [
'id', 'waybill_code', 'order_id', 'logistics_code',
'logistics_name', 'logistics_interface_id', 'logistics_interface_name',
'status', 'is_back', 'is_intercept', 'warehouse_id', 'create_at',
],
raw: true,
});
if (!waybill) return null;
return {
id: waybill.id,
waybill_code: waybill.waybill_code || '',
order_id: waybill.order_id,
logistics_code: waybill.logistics_code || '',
logistics_name: waybill.logistics_name || '',
logistics_interface_id: waybill.logistics_interface_id,
logistics_interface_name: waybill.logistics_interface_name || '',
status: waybill.status,
is_back: waybill.is_back || 'N',
is_intercept: waybill.is_intercept || 'N',
warehouse_id: waybill.warehouse_id,
create_at: waybill.create_at ? ctx.app.formatDate(waybill.create_at) : null,
};
}
/**
* 为步骤列表补充附件信息。
*
* @param {Array<Object>} steps 步骤列表
* @return {Promise<Array<Object>>} 含附件信息的步骤列表
*/
async _enrichStepsWithAttachments(steps = []) {
const { ctx } = this;
if (!steps || steps.length === 0) {
return [];
}
const detailIds = steps.map(s => s.id).filter(Boolean);
if (detailIds.length === 0) {
return steps;
}
// 查询所有步骤的附件引用
const references = await ctx.model.FileReference.findAll({
where: {
business_type: 'after_sale_detail',
business_id: { [ctx.app.Sequelize.Op.in]: detailIds.map(String) },
},
include: [
{
model: ctx.model.File,
as: 'file',
attributes: [ 'id', 'file_key', 'file_url', 'file_name', 'file_size', 'mime_type' ],
required: false,
},
],
raw: false,
});
// 构建 detailId → files 映射
const attachmentMap = new Map();
for (const ref of references) {
const refJson = ref.toJSON ? ref.toJSON() : ref;
const detailId = Number(refJson.business_id);
const fileInfo = refJson.file || null;
if (!detailId) continue;
if (!attachmentMap.has(detailId)) {
attachmentMap.set(detailId, []);
}
if (fileInfo) {
attachmentMap.get(detailId).push({
id: fileInfo.id,
file_key: fileInfo.file_key,
file_url: fileInfo.file_url,
file_name: fileInfo.file_name,
file_size: fileInfo.file_size,
mime_type: fileInfo.mime_type,
});
}
}
// 为每个步骤挂载附件
return steps.map(step => ({
...step,
attachments: attachmentMap.get(step.id) || [],
}));
}
// ===========================
// 创建售后单
// ===========================
/**
* 创建售后单主表记录。
*
* @param {Object} data 售后单数据
* @param {number} data.warehouse_id 仓库ID
* @param {string} data.after_sale_no 售后单号
* @param {string} data.type 售后类型
* @param {string} data.sub_type 售后子类型
* @param {string} data.title 售后标题
* @param {string} [data.description] 售后描述
* @param {number} [data.priority] 优先级
* @param {number} data.creator_id 创建人ID
* @param {string} [data.role_group] 当前处理角色组
* @param {string} [data.status] 售后状态
* @param {Object} [transaction] Sequelize 事务对象
* @return {Promise<Object>} 创建的售后单记录
*/
async create(data, transaction = null) {
const { ctx, app } = this;
const record = await ctx.model.AfterSale.create(data, { transaction });
const json = record && record.toJSON ? record.toJSON() : record;
return this._formatAfterSaleRow(json, app);
}
/**
* 批量补充列表行的货主名称 store_name。
* 货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),
* 无合约或备注为空时回退 wms_store.company_name(公司全称)。
*
* @param {Object[]} list 售后单列表行(原地补充 store_name 字段)
* @return {Promise<void>}
*/
async _enrichListStoreNames(list) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const storeIds = [ ...new Set(list.map(row => row.store_id).filter(Boolean)) ];
const warehouseIds = [ ...new Set(list.map(row => row.warehouse_id).filter(Boolean)) ];
if (storeIds.length === 0) {
list.forEach(row => {
row.store_name = '';
});
return;
}
// 1. 合约表货主备注名称(store_id + warehouse_id 维度)
let contractMap = {};
if (warehouseIds.length > 0) {
const swRows = await ctx.model.StoreWarehouse.findAll({
where: {
store_id: { [Op.in]: storeIds },
warehouse_id: { [Op.in]: warehouseIds },
},
attributes: [ 'store_id', 'warehouse_id', 'store_remask' ],
raw: true,
});
contractMap = swRows.reduce((acc, sw) => {
acc[`${sw.store_id}_${sw.warehouse_id}`] = sw.store_remask || '';
return acc;
}, {});
}
// 2. 货主公司全称兜底
let storeMap = {};
const storeRows = await ctx.model.Store.findAll({
where: { id: { [Op.in]: storeIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
storeMap = storeRows.reduce((acc, store) => {
acc[store.id] = store.company_name || '';
return acc;
}, {});
list.forEach(row => {
const contractRemask = contractMap[`${row.store_id}_${row.warehouse_id}`] || '';
row.store_name = contractRemask || storeMap[row.store_id] || '';
});
}
// ===========================
// 更新售后单
// ===========================
/**
* 更新售后单主表字段。
*
* @param {number} id 售后单主键ID
* @param {Object} data 需要更新的字段键值对
* @param {Object} [transaction] Sequelize 事务对象
* @return {Promise<Object>} 更新后的售后单记录
* @throws {Error} 售后单不存在时抛出
*/
async update(id, data, transaction = null) {
const { ctx, app } = this;
const record = await ctx.model.AfterSale.findOne({
where: { id, deleted_at: null },
transaction,
});
if (!record) {
throw new Error('售后单不存在');
}
await record.update(data, { transaction });
const json = record && record.toJSON ? record.toJSON() : record;
return this._formatAfterSaleRow(json, app);
}
/**
* 格式化售后单记录的时间字段。
* @param {Object} row 原始数据库行
* @param {Object} app Egg app 实例
* @return {Object} 格式化后的行
*/
_formatAfterSaleRow(row, app) {
if (!row) return row;
return {
...row,
created_at: row.created_at ? app.formatDate(row.created_at) : null,
updated_at: row.updated_at ? app.formatDate(row.updated_at) : null,
resolved_at: row.resolved_at ? app.formatDate(row.resolved_at) : null,
followup_at: row.followup_at ? app.formatDate(row.followup_at) : null,
started_at: row.started_at ? app.formatDate(row.started_at) : null,
completed_at: row.completed_at ? app.formatDate(row.completed_at) : null,
};
}
// ===========================
// 步骤记录
// ===========================
/**
* 写入一条售后进度步骤记录。
*
* @param {number} afterSaleId 售后单主键ID
* @param {Object} stepData 步骤数据
* @param {number} [stepData.step_status=2] 步骤状态(0=待开始,1=进行中,2=已完成,3=已跳过)
* @param {number} [stepData.operator_id] 操作人账户ID
* @param {string} [stepData.operator_snapshot] 操作人信息快照 JSON
* @param {string} [stepData.action] 操作动作描述
* @param {string} [stepData.remark] 处理备注
* @param {Date} [stepData.started_at] 步骤开始时间
* @param {Date} [stepData.completed_at] 步骤完成时间
* @param {Object} [transaction] Sequelize 事务对象
* @return {Promise<Object>} 创建的步骤记录
*/
async addStep(afterSaleId, stepData = {}, transaction = null) {
const { ctx } = this;
const now = new Date();
const record = await ctx.model.AfterSaleDetail.create({
after_sale_id: afterSaleId,
step_status: stepData.step_status !== undefined ? stepData.step_status : 'processing',
operator_id: stepData.operator_id || null,
operator_snapshot: stepData.operator_snapshot || null,
action: stepData.action || null,
remark: stepData.remark || null,
started_at: stepData.started_at || now,
completed_at: stepData.completed_at || now,
created_at: now,
}, { transaction });
return record && record.toJSON ? record.toJSON() : record;
}
// ===========================
// 附件绑定
// ===========================
/**
* 将文件绑定到售后步骤(批量)。
* 通过 wms_file_reference 表建立关联。
*
* @param {number} detailId 售后步骤ID
* @param {number[]} fileIds 文件ID列表
* @param {Object} [transaction] Sequelize 事务对象
* @return {Promise<Array<Object>>} 创建的文件引用记录列表
*/
async bindAttachments(detailId, fileIds = [], transaction = null) {
const { ctx } = this;
if (!detailId || !Array.isArray(fileIds) || fileIds.length === 0) {
return [];
}
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const createdBy = ctx.user
? String(ctx.user.employees_name || ctx.user.real_name || ctx.user.name || ctx.user.id || '')
: '';
const references = [];
for (const fileId of fileIds) {
// 检查是否已存在绑定,防止重复
const existing = await ctx.model.FileReference.findOne({
where: {
file_id: fileId,
warehouse_id: warehouseId,
business_type: 'after_sale_detail',
business_id: String(detailId),
},
transaction,
});
if (existing) {
references.push(existing);
continue;
}
const reference = await ctx.model.FileReference.create({
file_id: fileId,
warehouse_id: warehouseId,
business_type: 'after_sale_detail',
business_id: String(detailId),
display_order: 0,
created_by: createdBy,
created_at: new Date(),
}, { transaction });
references.push(reference);
}
return references.map(r => (r && r.toJSON ? r.toJSON() : r));
}
// ===========================
// 转单
// ===========================
/**
* 转单:更新售后单 role_group 并写入步骤记录。
*
* @param {Object} params 转单参数
* @param {number} params.id 售后单主键ID
* @param {string} params.targetRoleGroup 目标角色组
* @param {string} params.remark 转单备注
* @param {number} params.operatorId 操作人ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @return {Promise<Object>} 更新后的售后单记录
*/
async transfer(params = {}) {
const { id, targetRoleGroup, remark, operatorId, operatorSnapshot } = params;
const transaction = await this.ctx.model.transaction();
try {
// 更新 role_group
const updated = await this.update(id, {
role_group: targetRoleGroup,
updated_at: new Date(),
}, transaction);
// 写入步骤记录(step_status 与主表当前 status 一致)
await this.addStep(id, {
step_status: updated.status || 'processing',
operator_id: operatorId,
operator_snapshot: operatorSnapshot,
action: '转单',
remark: remark || `转至${targetRoleGroup}`,
started_at: new Date(),
completed_at: new Date(),
}, transaction);
await transaction.commit();
return updated;
} catch (error) {
await transaction.rollback();
throw error;
}
}
// ===========================
// 处理工单
// ===========================
/**
* 处理工单:校验权限 → 写步骤 → 可选更新状态 → 变量回设 → 绑附件。
*
* @param {Object} params 处理参数
* @param {number} params.id 售后单主键ID
* @param {string|null} params.remark 处理备注
* @param {string|null} params.targetStatus 目标售后状态
* @param {string|null} params.resolution 完结处理结果
* @param {number[]} params.attachmentIds 附件文件ID列表
* @param {number} params.operatorId 操作人ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @param {number} params.warehouseId 仓库ID
* @param {boolean} [params.notifyGroup] 是否将处理备注发送到对应货主售后群(内部自动处理不传)
* @return {Promise<Object>} 处理结果,包含更新后的售后单、步骤记录和通知群数量
* @throws {Error} 售后单不存在或权限不足时抛出
*/
async handleWorkOrder(params = {}) {
const {
id, remark, targetStatus, resolution,
attachmentIds, operatorId, operatorSnapshot,
warehouseId, notifyGroup,
} = params;
const { ctx } = this;
// 1. 查询售后单并校验存在性(限定仓库范围)
const afterSale = await ctx.model.AfterSale.findOne({
where: { id, warehouse_id: warehouseId, deleted_at: null },
});
if (!afterSale) {
throw new Error('售后单不存在');
}
// 2. status 不填或填错默认 processing;pending 是创建默认值,不适用于处理操作
const ALLOWED_STATUSES = Object.keys(ctx.model.AfterSale.AFTER_SALE_STATUS).filter(s => s !== 'pending');
const safeStatus = (targetStatus && ALLOWED_STATUSES.includes(targetStatus)) ? targetStatus : 'processing';
// 3. 校验 role_group 权限:操作人必须有对应 role_group 的处理权限。
// 实际权限解析已在方法层(systemMethods/afterSale.js)通过 block 权限完成,
// 此处仅做兜底校验。
const allowedRoleGroups = [ 'customer_service', 'warehouse', 'finance' ];
const currentRoleGroup = afterSale.role_group;
if (currentRoleGroup && !allowedRoleGroups.includes(currentRoleGroup)) {
throw new Error('无权限处理当前角色组的售后单');
}
// 4. 开启事务
const transaction = await ctx.model.transaction();
try {
const now = new Date();
// 5. 写入步骤记录(action 由服务端固定为"处理工单",step_status 同步主表 status)
const step = await this.addStep(id, {
step_status: safeStatus,
operator_id: operatorId,
operator_snapshot: operatorSnapshot,
action: '处理工单',
remark,
started_at: now,
completed_at: now,
}, transaction);
// 6. 绑定附件
if (Array.isArray(attachmentIds) && attachmentIds.length > 0) {
await this.bindAttachments(step.id, attachmentIds, transaction);
}
// 7. 更新售后单状态
const updateFields = { updated_at: now };
updateFields.status = safeStatus;
// 若完结,写入 resolution 和 resolved_at;清除 followup_at
if (safeStatus === 'completed') {
updateFields.resolution = resolution || null;
updateFields.resolved_at = now;
updateFields.followup_at = null;
}
// 若设为 pending_feedback:按仓库配置自动计算下次跟进时间
if (safeStatus === 'pending_feedback') {
const hours = await this._resolveFollowupHours(afterSale.warehouse_id, afterSale.type, afterSale.sub_type);
ctx.logger.info(
'[handleWorkOrder] id=%s warehouse=%s type=%s subType=%s hours=%d',
id, afterSale.warehouse_id, afterSale.type, afterSale.sub_type, hours
);
// 使用数据库 NOW() 确保与查询条件时区一致
updateFields.followup_at = ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`);
}
// 8. 若当前角色非客服组且状态非完结,自动回设为客服组
if (currentRoleGroup && currentRoleGroup !== 'customer_service' && safeStatus !== 'completed') {
updateFields.role_group = 'customer_service';
}
await afterSale.update(updateFields, { transaction });
await transaction.commit();
// 9. 处理备注发送到对应的货主售后群(仅交互处理传入 notifyGroup 时触发,不转发快递群)
let notifiedGroupCount = 0;
if (notifyGroup && remark && String(remark).trim()) {
try {
const remarkText = String(remark).trim();
const asRow = afterSale.toJSON ? afterSale.toJSON() : afterSale;
// 定位货主:优先工单 store_id,缺失时从来源消息所在群反查
let notifyStoreId = Number(asRow.store_id || 0);
if (!notifyStoreId && asRow.inbox_message_id) {
try {
const inbound = await ctx.model.InboxMessage.findByPk(asRow.inbox_message_id, {
attributes: [ 'group_id' ],
raw: true,
});
if (inbound && inbound.group_id) {
const originGroup = await ctx.model.InboxGroup.findOne({
attributes: [ 'store_id' ],
where: {
group_id: inbound.group_id,
warehouse_id: warehouseId,
is_blocked: 0,
},
raw: true,
});
if (originGroup && originGroup.store_id) {
notifyStoreId = Number(originGroup.store_id);
}
}
} catch (originErr) {
ctx.logger.warn(`[handleWorkOrder] 反查来源群货主失败 id=${id}: ${originErr.message}`);
}
}
if (notifyStoreId) {
const storeGroups = await ctx.service.systems.inbox.group.findStoreAfterSalesGroups({
storeIds: [ notifyStoreId ],
warehouseId,
});
const content = `【工单 ${asRow.after_sale_no}】处理备注:\n${remarkText}`;
for (const g of storeGroups) {
if (!g.group_id) continue;
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name || '',
content,
ext_data: g.ext_data || null,
});
notifiedGroupCount += 1;
}
}
ctx.logger.info(
`[handleWorkOrder] 处理备注发送到货主售后群 id=${id} store=${notifyStoreId} notified=${notifiedGroupCount}`
);
} catch (notifyErr) {
ctx.logger.warn(`[handleWorkOrder] 处理备注发送群失败 id=${id}: ${notifyErr.message}`);
}
}
const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale;
return {
after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app),
step,
notified_groups: notifiedGroupCount,
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
// ===========================
// 拦截链路:批量创建工单 + 通知快递群
// ===========================
/**
* 拦截链路共享方法:根据订单 ID 查找运单,幂等创建售后工单,并按快递分组通知售后群。
* 用于 batchIntercept / confirmIntercept / Qimen cancel / OpenAPI cancel 等入口统一调用。
*
* @param {Object} params 参数。
* @param {number[]} params.orderIds 订单 ID 列表。
* @param {number} params.warehouseId 仓库 ID。
* @param {string} params.creatorLabel 创建人标签(如 "系统"、"王小明")。
* @param {string} [params.reason] 拦截原因。
* @return {Promise<{ createdCount: number, notifiedCount: number }>} 创建与通知统计。
*/
async createInterceptWorkOrdersAndNotify(params = {}) {
const { ctx } = this;
const { orderIds, warehouseId, creatorLabel, reason } = params;
if (!Array.isArray(orderIds) || orderIds.length === 0 || !warehouseId) {
return { createdCount: 0, notifiedCount: 0 };
}
try {
// 1. 查询运单信息
const expressList = await ctx.model.OrderExpress.findAll({
attributes: [
'id', 'waybill_code', 'logistics_name', 'store_id',
'logistics_interface_id', 'logistics_code', 'order_id',
],
where: {
order_id: { [ctx.app.Sequelize.Op.in]: orderIds },
warehouse_id: warehouseId,
},
raw: true,
});
if (expressList.length === 0) {
return { createdCount: 0, notifiedCount: 0 };
}
// 2. 幂等检查:已有未完结的拦截工单不再重复创建
const expressIds = expressList.map(e => e.id);
const existingASList = await ctx.model.AfterSale.findAll({
attributes: [ 'waybill_id' ],
where: {
waybill_id: { [ctx.app.Sequelize.Op.in]: expressIds },
type: 'order',
sub_type: 'intercept',
status: { [ctx.app.Sequelize.Op.notIn]: [ 'completed', 'closed', 'cancelled' ] },
},
raw: true,
});
const existingWaybillIds = new Set(existingASList.map(r => r.waybill_id));
const toCreate = expressList.filter(e => !existingWaybillIds.has(e.id));
if (toCreate.length === 0) {
return { createdCount: 0, notifiedCount: 0 };
}
// 3. 批量创建工单
const label = creatorLabel || '系统';
let createdCount = 0;
const createdWaybillIds = [];
for (const e of toCreate) {
try {
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
const descParts = [
`发起人: ${label}`,
`运单号: ${e.waybill_code}`,
`快递公司: ${e.logistics_name || '未知'}`,
reason ? `拦截原因: ${reason}` : '',
].filter(Boolean).join('\n');
await this.create({
warehouse_id: warehouseId,
after_sale_no: afterSaleNo,
type: 'order',
sub_type: 'intercept',
title: `[系统拦截] ${e.waybill_code}`,
description: descParts,
priority: 10,
creator_id: 0,
inbox_message_id: null,
role_group: 'customer_service',
status: 'pending',
waybill_id: e.id,
waybill_no: e.waybill_code,
store_id: e.store_id || null,
order_id: e.order_id || null,
});
createdCount += 1;
createdWaybillIds.push(e.id);
} catch (createErr) {
ctx.logger.warn(
`[afterSale.createInterceptWorkOrdersAndNotify] 创建工单失败, waybill=${e.waybill_code}, error=${createErr.message}`
);
}
}
// 4. 按快递分组通知售后群
const expressByCode = {};
for (const e of toCreate) {
const code = e.logistics_code || '__unknown__';
if (!expressByCode[code]) {
expressByCode[code] = {
code,
interfaceId: e.logistics_interface_id,
logisticsName: String(e.logistics_name || '').trim(),
waybills: [],
};
}
expressByCode[code].waybills.push(e.waybill_code);
}
let notifiedCount = 0;
const notifiedWaybillIds = new Set();
// 无对应快递群(或快递无接口)的运单收集后统一降级通知仓库异常群(与货主群缺失降级行为一致)
const fallbackEntries = [];
for (const [ code, info ] of Object.entries(expressByCode)) {
if (code === '__unknown__' || !info.interfaceId) {
fallbackEntries.push(info);
continue;
}
try {
const { afterSalesGroups } = await ctx.service.systems.inbox.group.findGroupsByExpress({
expressInterfaceId: info.interfaceId,
expressCode: code,
warehouseId,
});
if (afterSalesGroups.length === 0) {
fallbackEntries.push(info);
continue;
}
const notifyMsg = info.waybills.join('\n') + '\n拦截';
for (const g of afterSalesGroups) {
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name,
content: notifyMsg,
ext_data: g.ext_data || null,
});
notifiedCount += 1;
}
// 标记该快递下所有运单已通知
const codeWaybills = toCreate.filter(e => (e.logistics_code || '__unknown__') === code);
codeWaybills.forEach(e => notifiedWaybillIds.add(e.id));
} catch (e) {
fallbackEntries.push(info);
ctx.logger.warn(`[afterSale] 查售后群失败 code=${code}: ${e.message}`);
}
}
// 4b. 无对应快递群降级:转发仓库异常群,内容前缀标记失败(与货主群缺失降级一致)
if (fallbackEntries.length > 0) {
try {
const exceptionGroups = await ctx.model.InboxGroup.findAll({
attributes: [ 'group_id', 'group_name', 'ext_data' ],
where: {
warehouse_id: warehouseId,
group_type: 'warehouse',
sub_type: 'exception',
is_blocked: 0,
},
raw: true,
});
if (exceptionGroups.length > 0) {
const labelSet = new Set();
const fallbackLines = [];
for (const entry of fallbackEntries) {
const label = entry.logisticsName || entry.code || '未知快递';
labelSet.add(label);
for (const waybill of entry.waybills) {
fallbackLines.push(`${label} ${waybill}`);
}
}
const fallbackContent = `通知快递【${Array.from(labelSet).join('、')}】失败\n${fallbackLines.join('\n')}\n拦截`;
for (const g of exceptionGroups) {
ctx.service.inbox.processor.pushSystemNotification({
warehouse_id: warehouseId,
group_id: g.group_id,
group_name: g.group_name,
content: fallbackContent,
ext_data: g.ext_data || null,
});
}
ctx.logger.warn('[afterSale.createInterceptWorkOrdersAndNotify] 无对应快递群,已降级通知仓库异常群', {
warehouseId,
fallbackCount: fallbackEntries.length,
exceptionGroupCount: exceptionGroups.length,
});
}
} catch (fallbackErr) {
ctx.logger.warn(`[afterSale] 降级通知异常群失败: ${fallbackErr.message}`);
}
}
// 5. 有通知的工单升级为 pending_feedback
if (notifiedWaybillIds.size > 0) {
const notifiedWaybillIdArr = [ ...notifiedWaybillIds ];
const hours = await this._resolveFollowupHours(warehouseId, 'order', 'intercept');
await ctx.model.AfterSale.update(
{
status: 'pending_feedback',
followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`),
role_group: 'customer_service',
},
{
where: {
waybill_id: { [ctx.app.Sequelize.Op.in]: notifiedWaybillIdArr },
warehouse_id: warehouseId,
type: 'order',
sub_type: 'intercept',
status: 'pending',
},
}
);
}
return { createdCount, notifiedCount };
} catch (error) {
ctx.logger.warn(`[afterSale.createInterceptWorkOrdersAndNotify] 整体失败: ${error.message}`);
return { createdCount: 0, notifiedCount: 0 };
}
}
// ===========================
// 跟进时间配置
// ===========================
/**
* 根据仓库配置解析跟进小时数。
* 优先级:policy_config sub_type 精确匹配 → type._default → 整数兜底 → 24h。
*
* @param {number} warehouseId 仓库ID
* @param {string} type 售后类型
* @param {string} subType 售后子类型
* @return {Promise<number>} 跟进小时数
*/
async _resolveFollowupHours(warehouseId, type, subType) {
const { ctx } = this;
// 仓库配置值的最小有效阈值:≤1 视为未配置的占位值,回退到 DEFAULTS
// (实际业务最小合理值为 intercept/urge 的 4h,不存在 0/1h 的跟进场景)
const MIN_VALID_FOLLOWUP_HOURS = 2;
// 1. 仓库已保存的配置
const sw = await ctx.model.StoreWarehouse.findOne({
where: { warehouse_id: warehouseId },
attributes: [ 'policy_config' ],
order: [[ 'id', 'DESC' ]],
raw: true,
});
ctx.logger.info(
'[_resolveFollowupHours] warehouseId=%s type=%s subType=%s hasStoreWarehouse=%s',
warehouseId, type, subType, !!(sw && sw.policy_config)
);
if (sw && sw.policy_config) {
let config = sw.policy_config;
if (typeof config === 'string') {
try { config = JSON.parse(config); } catch { config = {}; }
}
const whConfig = config && config.after_sale_followup_hours;
ctx.logger.info(
'[_resolveFollowupHours] whConfig type=%s value=%s',
typeof whConfig, JSON.stringify(whConfig)
);
if (whConfig && typeof whConfig === 'object') {
const whTypeMap = whConfig[type];
ctx.logger.info(
'[_resolveFollowupHours] whTypeMap for type=%s: %s',
type, JSON.stringify(whTypeMap)
);
// 分支 A:嵌套对象格式 {"order": {"damage": 48, "_default": 24}}
if (whTypeMap && typeof whTypeMap === 'object') {
if (subType) {
const subVal = this._tryParseHours(whTypeMap[subType]);
if (typeof subVal === 'number' && subVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH subType (nested): %s=%dh', subType, subVal);
return subVal;
}
}
const defVal = this._tryParseHours(whTypeMap._default);
if (typeof defVal === 'number' && defVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH type._default (nested): %s._default=%dh', type, defVal);
return defVal;
}
}
// 分支 B:扁平格式 {"order": "24"} 或 {"order": 24}
// 值为字符串或数字,直接作为该 type 下所有 subType 的统一时长
const flatVal = this._tryParseHours(whTypeMap);
if (typeof flatVal === 'number' && flatVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH type flat: %s=%dh', type, flatVal);
return flatVal;
}
}
// 分支 C:全局数字 {"after_sale_followup_hours": 24} 或 {"after_sale_followup_hours": "24"}
{
const globalVal = this._tryParseHours(whConfig);
if (typeof globalVal === 'number' && globalVal >= MIN_VALID_FOLLOWUP_HOURS) {
ctx.logger.info('[_resolveFollowupHours] MATCH whConfig global: %dh', globalVal);
return globalVal;
}
}
ctx.logger.info(`[_resolveFollowupHours] whConfig found but no valid match (all < ${MIN_VALID_FOLLOWUP_HOURS}h or type mismatch), falling to DEFAULTS`);
}
// 2. 仓库未配置时,使用字段默认值(与 setting.warehouse.getFieldMeta 返回一致)
const DEFAULTS = {
order: { _default: 24, intercept: 4, urge: 4, change_address: 8, change_carrier: 8, delivery_delay: 12, damage: 48, quality_issue: 48, missing_item: 24 },
receiving: { _default: 24, shortage: 48, damage: 48 },
entry: { _default: 24, shortage: 48, damage: 48 },
stockout: { _default: 24, return_issue: 48, shortage: 48 },
};
const typeDefault = DEFAULTS[type];
if (typeDefault) {
if (subType && typeof typeDefault[subType] === 'number') {
ctx.logger.info('[_resolveFollowupHours] DEFAULTS subType match: %s=%dh', subType, typeDefault[subType]);
return typeDefault[subType];
}
if (typeof typeDefault._default === 'number') {
ctx.logger.info('[_resolveFollowupHours] DEFAULTS type._default: %s=%dh', type, typeDefault._default);
return typeDefault._default;
}
}
// 3. 硬兜底
ctx.logger.warn('[_resolveFollowupHours] FALLBACK 24h for type=%s subType=%s', type, subType);
return 24;
}
/**
* 将配置值尝试转为有效的小时数。
* 兼容数字 24 和字符串 "24" 两种格式;无法解析时返回 null。
*
* @param {*} raw 原始配置值
* @return {number|null} 有效小时数,或 null
*/
_tryParseHours(raw) {
if (raw === null || raw === undefined || raw === '') return null;
if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
if (typeof raw === 'string') {
const parsed = Number(raw);
if (Number.isFinite(parsed)) return parsed;
}
return null;
}
// ===========================
// 批量设为待反馈
// ===========================
/**
* 批量将售后工单设为"待反馈"状态,并按仓库配置自动计算 followup_at。
* 对每个工单写入步骤记录,所有操作在同一事务中执行。
*
* @param {Object} params 批量操作参数
* @param {number[]} params.ids 售后单主键ID列表
* @param {number} params.operatorId 操作人账户ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @param {string} [params.remark] 统一处理备注(所有工单共用)
* @param {number} params.warehouseId 仓库ID(用于权限校验)
* @return {Promise<Object>} { total, success, failed: [{id, reason}] }
*/
async batchSetPendingFeedback(params = {}) {
const { ids, operatorId, operatorSnapshot, remark, warehouseId } = params;
const { ctx } = this;
// 1. 入参校验
if (!Array.isArray(ids) || ids.length === 0) {
return { total: 0, success: 0, failed: [] };
}
const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0);
if (numericIds.length === 0) {
return { total: 0, success: 0, failed: [] };
}
// 2. 查询所有目标工单
const afterSales = await ctx.model.AfterSale.findAll({
where: {
id: { [ctx.app.Sequelize.Op.in]: numericIds },
deleted_at: null,
},
});
const afterSaleMap = new Map();
for (const record of afterSales) {
afterSaleMap.set(record.id, record);
}
// 3. 预校验 & 分类
const validRecords = [];
const failed = [];
// 终态不可设为待反馈
const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]);
for (const id of numericIds) {
const record = afterSaleMap.get(id);
if (!record) {
failed.push({ id, reason: '售后单不存在或已删除' });
continue;
}
if (TERMINAL_STATUSES.has(record.status)) {
failed.push({ id, reason: `工单已完结(${record.status}),不可设为待反馈` });
continue;
}
if (record.warehouse_id !== warehouseId) {
failed.push({ id, reason: '仓库不匹配,无权操作' });
continue;
}
validRecords.push(record);
}
// 4. 开启事务,逐条更新
const transaction = await ctx.model.transaction();
try {
const now = new Date();
let successCount = 0;
for (const record of validRecords) {
// 4a. 解析该工单的跟进小时数
const hours = await this._resolveFollowupHours(
record.warehouse_id,
record.type,
record.sub_type
);
ctx.logger.info(
'[batchSetPendingFeedback] id=%s type=%s subType=%s hours=%d',
record.id, record.type, record.sub_type, hours
);
// 4b. 写入步骤记录
await this.addStep(record.id, {
step_status: 'pending_feedback',
operator_id: operatorId,
operator_snapshot: operatorSnapshot,
action: '设为待反馈',
remark: remark || null,
started_at: now,
completed_at: now,
}, transaction);
// 4c. 更新主表:status + followup_at + role_group 回客服组
const updateFields = {
status: 'pending_feedback',
followup_at: ctx.app.Sequelize.literal(`DATE_ADD(NOW(), INTERVAL ${hours} HOUR)`),
updated_at: now,
};
// 若非客服组,自动回设为客服组(与 handleWorkOrder 行为一致)
if (record.role_group && record.role_group !== 'customer_service') {
updateFields.role_group = 'customer_service';
}
await record.update(updateFields, { transaction });
successCount++;
}
await transaction.commit();
return {
total: numericIds.length,
success: successCount,
failed,
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
// ===========================
// 批量完结/关闭
// ===========================
/**
* 批量将售后工单设为完结或关闭状态。
* completed 时自动写入 resolved_at 并清除 followup_at;closed 仅更新状态。
* 对每个工单写入步骤记录,所有操作在同一事务中执行。
*
* @param {Object} params 批量操作参数
* @param {number[]} params.ids 售后单主键ID列表
* @param {string} params.status 目标状态:completed | closed
* @param {string} [params.resolution] 完结处理结果(仅 status=completed 时写入)
* @param {number} params.operatorId 操作人账户ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @param {string} [params.remark] 统一处理备注(所有工单共用)
* @param {number} params.warehouseId 仓库ID(用于权限校验)
* @return {Promise<Object>} { total, success, failed: [{id, reason}] }
*/
async batchClose(params = {}) {
const { ids, status: targetStatus, resolution, operatorId, operatorSnapshot, remark, warehouseId } = params;
const { ctx } = this;
// 1. 入参校验
const ALLOWED_TARGET_STATUSES = new Set([ 'completed', 'closed' ]);
if (!targetStatus || !ALLOWED_TARGET_STATUSES.has(targetStatus)) {
return { total: 0, success: 0, failed: [{ id: 0, reason: 'status 必须为 completed 或 closed' }] };
}
if (!Array.isArray(ids) || ids.length === 0) {
return { total: 0, success: 0, failed: [] };
}
const numericIds = ids.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0);
if (numericIds.length === 0) {
return { total: 0, success: 0, failed: [] };
}
// 2. 查询所有目标工单
const afterSales = await ctx.model.AfterSale.findAll({
where: {
id: { [ctx.app.Sequelize.Op.in]: numericIds },
deleted_at: null,
},
});
const afterSaleMap = new Map();
for (const record of afterSales) {
afterSaleMap.set(record.id, record);
}
// 3. 预校验 & 分类
const validRecords = [];
const failed = [];
// 终态不可重复完结/关闭
const TERMINAL_STATUSES = new Set([ 'completed', 'closed', 'cancelled' ]);
for (const id of numericIds) {
const record = afterSaleMap.get(id);
if (!record) {
failed.push({ id, reason: '售后单不存在或已删除' });
continue;
}
if (TERMINAL_STATUSES.has(record.status)) {
failed.push({ id, reason: `工单已是终态(${record.status}),不可重复${targetStatus === 'completed' ? '完结' : '关闭'}` });
continue;
}
if (record.warehouse_id !== warehouseId) {
failed.push({ id, reason: '仓库不匹配,无权操作' });
continue;
}
validRecords.push(record);
}
// 4. 开启事务,逐条更新
const transaction = await ctx.model.transaction();
try {
const now = new Date();
let successCount = 0;
// 操作动作名称
const actionName = targetStatus === 'completed' ? '批量完结' : '批量关闭';
for (const record of validRecords) {
// 4a. 写入步骤记录
await this.addStep(record.id, {
step_status: targetStatus,
operator_id: operatorId,
operator_snapshot: operatorSnapshot,
action: actionName,
remark: remark || null,
started_at: now,
completed_at: now,
}, transaction);
// 4b. 更新主表
const updateFields = {
status: targetStatus,
updated_at: now,
followup_at: null,
};
// completed:额外写入 resolution + resolved_at
if (targetStatus === 'completed') {
updateFields.resolution = resolution || null;
updateFields.resolved_at = now;
}
await record.update(updateFields, { transaction });
successCount++;
}
await transaction.commit();
return {
total: numericIds.length,
success: successCount,
failed,
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
// ===========================
// 登记理赔
// ===========================
/**
* 登记理赔:更新售后单的理赔字段,写入步骤记录,绑定附件。
*
* @param {Object} params 理赔参数
* @param {number} params.id 售后单主键ID
* @param {number} [params.claimNeeded] 仓库理赔标记
* @param {number} [params.claimAmount] 仓库理赔金额
* @param {string} [params.claimStatus] 仓库理赔状态
* @param {number} [params.carrierClaimNeeded] 运方理赔标记
* @param {number} [params.carrierClaimAmount] 运方理赔金额
* @param {string} [params.carrierClaimStatus] 运方理赔状态
* @param {string|null} params.remark 理赔备注
* @param {string} params.action 操作动作描述
* @param {number[]} params.attachmentIds 附件文件ID列表
* @param {number} params.operatorId 操作人ID
* @param {string} params.operatorSnapshot 操作人快照 JSON
* @param {number} params.warehouseId 仓库ID
* @return {Promise<Object>} 理赔处理结果
* @throws {Error} 售后单不存在时抛出
*/
async registerClaim(params = {}) {
const {
id, claimNeeded, claimAmount, claimStatus,
carrierClaimNeeded, carrierClaimAmount, carrierClaimStatus,
remark, action, attachmentIds, operatorId, operatorSnapshot,
} = params;
const { ctx } = this;
// 校验售后单存在
const afterSale = await ctx.model.AfterSale.findOne({
where: { id, deleted_at: null },
});
if (!afterSale) {
throw new Error('售后单不存在');
}
const transaction = await ctx.model.transaction();
try {
const now = new Date();
// 构建更新字段(仅含非空传入值)
const updateFields = { updated_at: now };
if (claimNeeded !== undefined) updateFields.claim_needed = claimNeeded;
if (claimAmount !== undefined) updateFields.claim_amount = claimAmount;
if (claimStatus !== undefined) updateFields.claim_status = claimStatus;
if (carrierClaimNeeded !== undefined) updateFields.carrier_claim_needed = carrierClaimNeeded;
if (carrierClaimAmount !== undefined) updateFields.carrier_claim_amount = carrierClaimAmount;
if (carrierClaimStatus !== undefined) updateFields.carrier_claim_status = carrierClaimStatus;
await afterSale.update(updateFields, { transaction });
// 写入步骤(step_status 与主表当前 status 一致)
const step = await this.addStep(id, {
step_status: afterSale.status || 'processing',
operator_id: operatorId,
operator_snapshot: operatorSnapshot,
action,
remark,
started_at: now,
completed_at: now,
}, transaction);
// 绑定附件
if (Array.isArray(attachmentIds) && attachmentIds.length > 0) {
await this.bindAttachments(step.id, attachmentIds, transaction);
}
await transaction.commit();
const updatedAfterSale = afterSale.toJSON ? afterSale.toJSON() : afterSale;
return {
after_sale: this._formatAfterSaleRow(updatedAfterSale, ctx.app),
step,
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
// ===========================
// 导出
// ===========================
/**
* 售后单导出:分页查询 → ExcelJS 流式写入 → COS 上传。
* 通过 onProgress 回调实时推送进度。
*
* @param {Object} options 导出选项
* @param {Object} [options.where] 筛选条件
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 导出结果,包含文件下载信息
*/
async exportAfterSales(options = {}) {
const { where = {}, sort = {}, onProgress } = options;
const reportProgress = (status, progress, message, extra = {}) => {
if (typeof onProgress === 'function') {
onProgress({ status, progress, message, ...extra });
}
};
reportProgress('running', 5, '正在准备导出数据...');
// 先统计总数
const { count: totalCount } = await this.ctx.model.AfterSale.findAndCountAll({
where: this._buildListWhere(where, this.ctx.app.Sequelize.Op),
raw: true,
});
reportProgress('running', 10, `共 ${totalCount} 条记录,开始导出...`, { totalCount, currentCount: 0 });
// 分页查询并导出
const pageSize = 500;
const totalPages = Math.ceil(totalCount / pageSize);
const allRows = [];
for (let page = 1; page <= totalPages; page++) {
const result = await this.list(where, { page, pageSize }, sort);
const rows = Array.isArray(result.list) ? result.list : [];
allRows.push(...rows);
const progress = 10 + Math.floor(((page / totalPages) * 80));
reportProgress('running', progress, `正在导出... (${allRows.length}/${totalCount})`, {
totalCount,
currentCount: allRows.length,
});
// 每页之间稍作让渡,避免长时间阻塞
await new Promise(resolve => setImmediate(resolve));
}
reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: allRows.length });
// 生成 Excel 文件并上传 COS
const exportResult = await this._generateAndUploadExcel(allRows);
reportProgress('success', 100, '导出完成', {
totalCount,
currentCount: allRows.length,
result: exportResult,
});
return {
...exportResult,
total_count: totalCount,
current_count: allRows.length,
};
}
/**
* 生成 Excel 并上传 COS,返回下载信息。
*
* @param {Array<Object>} rows 售后单数据行
* @return {Promise<Object>} { url, fileKey, fileName }
*/
async _generateAndUploadExcel(rows = []) {
const { ctx } = this;
try {
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('售后单列表');
// 定义列
worksheet.columns = [
{ header: '售后单号', key: 'after_sale_no', width: 22 },
{ header: '售后类型', key: 'type', width: 12 },
{ header: '售后子类型', key: 'sub_type', width: 14 },
{ header: '售后状态', key: 'status', width: 12 },
{ header: '优先级', key: 'priority', width: 10 },
{ header: '标题', key: 'title', width: 30 },
{ header: '描述', key: 'description', width: 30 },
{ header: '当前处理角色', key: 'role_group', width: 16 },
{ header: '仓库理赔状态', key: 'claim_status', width: 14 },
{ header: '仓库理赔金额', key: 'claim_amount', width: 14 },
{ header: '运方理赔状态', key: 'carrier_claim_status', width: 14 },
{ header: '运方理赔金额', key: 'carrier_claim_amount', width: 14 },
{ header: '运单号', key: 'waybill_no', width: 20 },
{ header: '发货订单号', key: 'order_delivery_no', width: 20 },
{ header: '入库单号', key: 'entry_order_no', width: 20 },
{ header: '出库单号', key: 'order_stockout_no', width: 20 },
{ header: '收货单号', key: 'receiving_no', width: 20 },
{ header: '处理结果', key: 'resolution', width: 30 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
{ header: '完结时间', key: 'resolved_at', width: 20 },
];
// 写入数据行
for (const row of rows) {
worksheet.addRow(row);
}
// 生成 buffer
const buffer = await workbook.xlsx.writeBuffer();
// 上传到 COS
const now = new Date();
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
const timestamp = Date.now();
const fileName = `after_sale_export_${dateStr}_${timestamp}.xlsx`;
const fileKey = `export/after_sale/${fileName}`;
let url = '';
try {
if (ctx.service.systems && ctx.service.systems.upload && typeof ctx.service.systems.upload.uploadToCos === 'function') {
const uploadResult = await ctx.service.systems.upload.uploadToCos({
buffer,
fileKey,
fileName,
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
url = uploadResult && uploadResult.url ? uploadResult.url : '';
}
} catch (uploadError) {
ctx.logger.warn(`[afterSale.export] COS 上传失败: ${uploadError.message}`);
}
return {
url,
fileKey,
fileName,
};
} catch (error) {
ctx.logger.error(`[afterSale.export] 生成 Excel 失败: ${error.message}`);
return {
url: '',
fileKey: '',
fileName: '',
};
}
}
// ===========================
// 工具方法
// ===========================
/**
* 获取创建来源渠道的中文标签。
* @param {string} channel 创建渠道代码
* @return {string} 中文标签
*/
_getCreateChannelLabel(channel) {
const labels = {
MANUAL: '手工单',
API: '接口',
QM: '奇门',
};
return labels[channel] || channel || '';
}
}
module.exports = AfterSaleService;