@ -1562,6 +1562,901 @@ class InboxFunctionsService extends Service {
} ,
} ) ;
this . register ( 'handleStoreFeedback' , {
description : '货主售后群问题反馈建工单。客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"等问题并提供了运单号时调用。校验货主权限后创建售后工单,初始状态为未开始处理(pending),不转发通知快递群' ,
weight : 88 ,
keywords : [ '错发' , '发错' , '破损' , '坏了' , '多发' , '发多' , '少发' , '漏发' , '发少' ] ,
params : {
keyword : { type : 'string' , required : true , description : '运单号,多个用逗号或空格分隔,如 SF111,SF222' } ,
issue _type : { type : 'string' , required : true , description : '问题类型: wrong(错发)/damaged(破损)/multiple(多发)/missing(少发)' } ,
} ,
groups : [ GROUP . BOUND _STORE _AFTER _SALES ] ,
handler : async ( params = { } ) => {
const { ctx } = this ;
const raw = String ( params . keyword || '' ) . trim ( ) ;
const issueTypeRaw = String ( params . issue _type || '' ) . trim ( ) ;
const storeId = Number ( ctx . inboxContext ? . store _id || 0 ) ;
const warehouseId = Number ( ctx . inboxContext ? . warehouse _id || 0 ) ;
const groupName = String ( ctx . inboxContext ? . group _name || '' ) . trim ( ) ;
const userName = String ( ctx . inboxContext ? . user _name || '' ) . trim ( ) ;
if ( ! raw ) return { success : false , error : '请提供运单号' } ;
if ( ! warehouseId ) return { success : false , error : '无法获取仓库信息' } ;
if ( ! storeId ) return { success : false , error : '无法获取货主信息,请确认已在货主售后群上下文中操作' } ;
// 问题类型 → 售后子类型映射(支持英文枚举与中文别名)
const ISSUE _TYPE _MAP = {
wrong : { sub _type : 'mis_shipment' , label : '错发' } ,
错发 : { sub _type : 'mis_shipment' , label : '错发' } ,
damaged : { sub _type : 'damage' , label : '破损' } ,
破损 : { sub _type : 'damage' , label : '破损' } ,
multiple : { sub _type : 'extra_item' , label : '多发' } ,
多发 : { sub _type : 'extra_item' , label : '多发' } ,
missing : { sub _type : 'missing_item' , label : '少发' } ,
少发 : { sub _type : 'missing_item' , label : '少发' } ,
} ;
const issue = ISSUE _TYPE _MAP [ issueTypeRaw ] ;
if ( ! issue ) {
return {
success : false ,
error : ` 不支持的问题类型「 ${ issueTypeRaw || '空' } 」,仅支持 wrong(错发)/damaged(破损)/multiple(多发)/missing(少发) ` ,
} ;
}
const keywords = raw . split ( /[,, \s\n]+/ ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
if ( keywords . length === 0 ) return { success : false , error : '未解析到有效运单号' } ;
// 前置拦截:拒绝看起来像售后单号(AS...)的输入
const asLikeList = keywords . filter ( k => / ^ AS / i . test ( k ) ) ;
if ( asLikeList . length > 0 ) {
return { success : false , error : ` ${ asLikeList . join ( '、' ) } 是售后工单号而非运单号,请提供运单号 ` } ;
}
try {
// 第一步:批量查询运单(限当前仓库 + 当前货主)
const expressList = await ctx . model . OrderExpress . findAll ( {
attributes : [ 'id' , 'waybill_code' , 'logistics_name' , 'store_id' , 'order_id' ] ,
where : {
waybill _code : { [ ctx . app . Sequelize . Op . in ] : keywords } ,
warehouse _id : warehouseId ,
store _id : storeId ,
} ,
raw : true ,
} ) ;
const foundCodes = new Set ( expressList . map ( e => e . waybill _code ) ) ;
const notFound = keywords . filter ( k => ! foundCodes . has ( k ) ) ;
if ( expressList . length === 0 ) {
return { success : false , error : ` 未找到当前货主在仓库中的运单「 ${ raw } 」,请核实单号后重试 ` } ;
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList . map ( e => e . id ) ;
const existingASList = await ctx . model . AfterSale . findAll ( {
attributes : [ 'waybill_id' , 'after_sale_no' ] ,
where : {
waybill _id : { [ ctx . app . Sequelize . Op . in ] : expressIds } ,
type : 'order' ,
sub _type : issue . sub _type ,
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 ) ) ;
const alreadyExist = existingASList . map ( r => r . after _sale _no ) ;
/ * *
* 组装客户回信模板 : 单号 + 问题信息 + 工单号 。
* @ param { Array < { waybill : string , as _no : string } > } pairs 运单号 → 工单号列表 。
* @ return { string } 模板消息 。
* /
const buildReply = pairs => {
const lines = pairs . map ( p => ` 运单 ${ p . waybill } ${ issue . label } 问题已登记,工单: ${ p . as _no } ` ) ;
if ( notFound . length > 0 ) {
lines . push ( ` 未找到运单: ${ notFound . join ( '、' ) } ,请核实单号 ` ) ;
}
return ` ${ lines . join ( '\n' ) } ,稍后客服将人工核实跟进 ` ;
} ;
if ( toCreate . length === 0 ) {
const existedPairs = expressList
. filter ( e => existingWaybillIds . has ( e . id ) )
. map ( e => {
const row = existingASList . find ( r => Number ( r . waybill _id ) === Number ( e . id ) ) ;
return { waybill : e . waybill _code , as _no : ( row && row . after _sale _no ) || '' } ;
} )
. filter ( p => p . as _no ) ;
return {
success : true ,
data : {
existed : true ,
message : buildReply ( existedPairs ) ,
direct _reply : true ,
after _sale _nos : alreadyExist ,
} ,
} ;
}
// 第三步:创建工单(初始状态 pending=未开始处理,不转发通知快递群)
const creatorLabel = [ groupName , userName ] . filter ( Boolean ) . join ( '-' ) || 'AI系统' ;
let msgContent = '' ;
try {
const mid = ctx . inboxContext ? . inbound _message _id ;
if ( mid ) {
const m = await ctx . model . InboxMessage . findByPk ( mid , { attributes : [ 'content' ] , raw : true } ) ;
if ( m && m . content ) msgContent = String ( m . content ) ;
}
} catch ( e ) { /* ignore */ }
const createdNos = [ ] ;
const waybillToAsNo = { } ; // waybill_id → after_sale_no 映射
for ( const e of toCreate ) {
const afterSaleNo = await ctx . service . systemMethods . afterSale . generateAfterSaleNo ( warehouseId ) ;
const descParts = [
` 发起人: ${ creatorLabel } ` ,
` 运单号: ${ e . waybill _code } ` ,
` 快递公司: ${ e . logistics _name || '未知' } ` ,
` 问题类型: ${ issue . label } ` ,
msgContent ? ` 原消息: ${ msgContent } ` : '' ,
] . filter ( Boolean ) . join ( '\n' ) ;
await ctx . service . systems . afterSale . create ( {
warehouse _id : warehouseId ,
after _sale _no : afterSaleNo ,
type : 'order' ,
sub _type : issue . sub _type ,
title : ` [AI工单] ${ issue . label } - ${ e . waybill _code } ` ,
description : descParts ,
priority : 10 ,
creator _id : 0 ,
inbox _message _id : ctx . inboxContext ? . inbound _message _id || null ,
role _group : 'customer_service' ,
status : 'pending' ,
waybill _id : e . id ,
waybill _no : e . waybill _code ,
store _id : e . store _id || storeId ,
order _id : e . order _id || null ,
} ) ;
createdNos . push ( afterSaleNo ) ;
waybillToAsNo [ e . id ] = afterSaleNo ;
}
ctx . logger . info (
` [inbox functions] 货主问题反馈建工单: sub_type= ${ issue . sub _type } ` +
` total= ${ keywords . length } found= ${ expressList . length } created= ${ createdNos . length } notFound= ${ notFound . length } `
) ;
// 构造返回数据(客户回信模板:单号+问题+工单,细节字段仅作内部记录)
const createdPairs = toCreate . map ( e => ( {
waybill : e . waybill _code ,
as _no : waybillToAsNo [ e . id ] || '' ,
} ) ) ;
const existedPairs = expressList
. filter ( e => existingWaybillIds . has ( e . id ) )
. map ( e => {
const row = existingASList . find ( r => Number ( r . waybill _id ) === Number ( e . id ) ) ;
return { waybill : e . waybill _code , as _no : ( row && row . after _sale _no ) || '' } ;
} )
. filter ( p => p . as _no ) ;
return {
success : true ,
data : {
created : createdNos . length ,
existed : alreadyExist . length ,
after _sale _nos : [ ... createdNos , ... alreadyExist ] ,
not _found : notFound ,
message : buildReply ( [ ... createdPairs , ... existedPairs ] ) ,
direct _reply : true ,
} ,
} ;
} catch ( error ) {
ctx . logger . error ( ` [inbox functions] 货主问题反馈建工单失败: ${ error . message } ` ) ;
return { success : false , error : ` 操作失败: ${ error . message } ` } ;
}
} ,
} ) ;
this . register ( 'changeAddr' , {
description : '货主售后群改地址/催退回处理。客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/尽快安排派送/催促退回"等诉求且提供了运单号时调用:创建售后工单(改地址/催退回),并将客户原文转发到对应快递的售后群通知快递处理' ,
weight : 89 ,
keywords : [ '改地址' , '改电话' , '改联系人' , '改收件人' , '地址更改' , '改手机' , '催退回' , '尽快安排派送' , '催促退回' ] ,
params : {
keyword : { type : 'string' , required : true , description : '运单号,多个用逗号或空格分隔,如 SF111,SF222' } ,
issue _type : { type : 'string' , required : true , description : '诉求类型: addr(改地址类诉求)/return(催退回类诉求)' } ,
} ,
groups : [ GROUP . BOUND _STORE _AFTER _SALES ] ,
handler : async ( params = { } ) => {
const { ctx } = this ;
const raw = String ( params . keyword || '' ) . trim ( ) ;
const issueTypeRaw = String ( params . issue _type || '' ) . trim ( ) ;
const storeId = Number ( ctx . inboxContext ? . store _id || 0 ) ;
const warehouseId = Number ( ctx . inboxContext ? . warehouse _id || 0 ) ;
const groupName = String ( ctx . inboxContext ? . group _name || '' ) . trim ( ) ;
const userName = String ( ctx . inboxContext ? . user _name || '' ) . trim ( ) ;
if ( ! raw ) return { success : false , error : '请提供运单号' } ;
if ( ! warehouseId ) return { success : false , error : '无法获取仓库信息' } ;
if ( ! storeId ) return { success : false , error : '无法获取货主信息,请确认已在货主售后群上下文中操作' } ;
// 诉求类型 → 售后子类型映射(支持英文枚举与中文别名)
const ISSUE _TYPE _MAP = {
addr : { sub _type : 'change_address' , label : '改地址' } ,
改地址 : { sub _type : 'change_address' , label : '改地址' } ,
return : { sub _type : 'rejected' , label : '催退回' } ,
催退回 : { sub _type : 'rejected' , label : '催退回' } ,
} ;
const issue = ISSUE _TYPE _MAP [ issueTypeRaw ] || ISSUE _TYPE _MAP . addr ;
const keywords = raw . split ( /[,, \s\n]+/ ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
if ( keywords . length === 0 ) return { success : false , error : '未解析到有效运单号' } ;
const asLikeList = keywords . filter ( k => / ^ AS / i . test ( k ) ) ;
if ( asLikeList . length > 0 ) {
return { success : false , error : ` ${ asLikeList . join ( '、' ) } 是售后工单号而非运单号,请提供运单号 ` } ;
}
try {
// 原文(客户原始消息,用于转发快递群 + 工单明细)
let originalText = '' ;
try {
const mid = ctx . inboxContext ? . inbound _message _id ;
if ( mid ) {
const m = await ctx . model . InboxMessage . findByPk ( mid , { attributes : [ 'content' ] , raw : true } ) ;
if ( m && m . content ) originalText = String ( m . content ) ;
}
} catch ( e ) { /* ignore */ }
// 第一步:批量查询运单(限当前仓库 + 当前货主)
const expressList = await ctx . model . OrderExpress . findAll ( {
attributes : [ 'id' , 'waybill_code' , 'logistics_name' , 'store_id' , 'order_id' ,
'logistics_interface_id' , 'logistics_code' ] ,
where : {
waybill _code : { [ ctx . app . Sequelize . Op . in ] : keywords } ,
warehouse _id : warehouseId ,
store _id : storeId ,
} ,
raw : true ,
} ) ;
const foundCodes = new Set ( expressList . map ( e => e . waybill _code ) ) ;
const notFound = keywords . filter ( k => ! foundCodes . has ( k ) ) ;
if ( expressList . length === 0 ) {
return { success : false , error : ` 未找到当前货主在仓库中的运单「 ${ raw } 」,请核实单号后重试 ` } ;
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList . map ( e => e . id ) ;
const existingASList = await ctx . model . AfterSale . findAll ( {
attributes : [ 'waybill_id' , 'after_sale_no' ] ,
where : {
waybill _id : { [ ctx . app . Sequelize . Op . in ] : expressIds } ,
type : 'order' ,
sub _type : issue . sub _type ,
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 ) ) ;
const alreadyExist = existingASList . map ( r => r . after _sale _no ) ;
const existedPairs = expressList
. filter ( e => existingWaybillIds . has ( e . id ) )
. map ( e => {
const row = existingASList . find ( r => Number ( r . waybill _id ) === Number ( e . id ) ) ;
return { waybill : e . waybill _code , as _no : ( row && row . after _sale _no ) || '' } ;
} )
. filter ( p => p . as _no ) ;
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [ ] ;
const waybillToAsNo = { } ; // waybill_id → after_sale_no 映射
if ( toCreate . length > 0 ) {
const creatorLabel = [ groupName , userName ] . filter ( Boolean ) . join ( '-' ) || 'AI系统' ;
for ( const e of toCreate ) {
const afterSaleNo = await ctx . service . systemMethods . afterSale . generateAfterSaleNo ( warehouseId ) ;
const descParts = [
` 发起人: ${ creatorLabel } ` ,
` 运单号: ${ e . waybill _code } ` ,
` 快递公司: ${ e . logistics _name || '未知' } ` ,
` 诉求类型: ${ issue . label } ` ,
originalText ? ` 原文: ${ originalText } ` : '' ,
] . filter ( Boolean ) . join ( '\n' ) ;
await ctx . service . systems . afterSale . create ( {
warehouse _id : warehouseId ,
after _sale _no : afterSaleNo ,
type : 'order' ,
sub _type : issue . sub _type ,
title : ` [AI工单] ${ issue . label } - ${ e . waybill _code } ` ,
description : descParts ,
priority : 10 ,
creator _id : 0 ,
inbox _message _id : ctx . inboxContext ? . inbound _message _id || null ,
role _group : 'customer_service' ,
status : 'pending' ,
waybill _id : e . id ,
waybill _no : e . waybill _code ,
store _id : e . store _id || storeId ,
order _id : e . order _id || null ,
} ) ;
createdNos . push ( afterSaleNo ) ;
waybillToAsNo [ e . id ] = afterSaleNo ;
}
}
// 第四步:原文转发到对应快递的售后群(按快递分组)
const expressByCode = { } ;
for ( const e of toCreate ) {
const code = e . logistics _code || '__unknown__' ;
if ( ! expressByCode [ code ] ) {
expressByCode [ code ] = { interfaceId : e . logistics _interface _id , waybills : [ ] } ;
}
expressByCode [ code ] . waybills . push ( e . waybill _code ) ;
}
let notifiedTotal = 0 ;
const notifiedWaybillIds = new Set ( ) ;
for ( const [ code , info ] of Object . entries ( expressByCode ) ) {
if ( code === '__unknown__' || ! info . interfaceId ) continue ;
try {
const { afterSalesGroups } = await ctx . service . systems . inbox . group . findGroupsByExpress ( {
expressInterfaceId : info . interfaceId ,
expressCode : code ,
warehouseId ,
} ) ;
if ( afterSalesGroups . length === 0 ) {
ctx . logger . info ( ` [inbox functions] 快递 ${ code } 未配置售后群,跳过转发 ` ) ;
continue ;
}
// 原文转发:运单号 + 客户原始消息
const forwardMsg = ` 运单: ${ info . waybills . join ( '、' ) } \n 原文: ${ originalText || raw } ` ;
for ( const g of afterSalesGroups ) {
ctx . service . inbox . processor . pushSystemNotification ( {
warehouse _id : warehouseId ,
group _id : g . group _id ,
group _name : g . group _name ,
content : forwardMsg ,
ext _data : g . ext _data || null ,
} ) ;
notifiedTotal += 1 ;
}
toCreate
. filter ( e => ( e . logistics _code || '__unknown__' ) === code )
. forEach ( e => notifiedWaybillIds . add ( e . id ) ) ;
} catch ( e ) {
ctx . logger . warn ( ` [inbox functions] 改地址/催退回查快递群失败 code= ${ code } : ${ e . message } ` ) ;
}
}
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限
const notifiedAsNos = createdNos . filter ( ( asNo , idx ) => notifiedWaybillIds . has ( toCreate [ idx ] . id ) ) ;
if ( notifiedAsNos . length > 0 ) {
try {
const hours = await ctx . service . systems . afterSale . _resolveFollowupHours (
warehouseId , 'order' , issue . sub _type
) ;
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 : { after _sale _no : { [ ctx . app . Sequelize . Op . in ] : notifiedAsNos } } }
) ;
} catch ( e ) {
ctx . logger . warn ( ` [inbox functions] 改地址/催退回更新工单状态失败: ${ e . message } ` ) ;
}
}
// 第六步:客户回信模板(单号+诉求+工单)
const createdPairs = toCreate . map ( e => ( {
waybill : e . waybill _code ,
as _no : waybillToAsNo [ e . id ] || '' ,
} ) ) ;
const lines = [ ... createdPairs , ... existedPairs ] . map ( p => ` 运单 ${ p . waybill } ${ issue . label } 问题已登记,工单: ${ p . as _no } ` ) ;
if ( notFound . length > 0 ) {
lines . push ( ` 未找到运单: ${ notFound . join ( '、' ) } ,请核实单号 ` ) ;
}
ctx . logger . info (
` [inbox functions] 改地址/催退回: sub_type= ${ issue . sub _type } ` +
` total= ${ keywords . length } found= ${ expressList . length } created= ${ createdNos . length } notified= ${ notifiedTotal } `
) ;
return {
success : true ,
data : {
created : createdNos . length ,
existed : alreadyExist . length ,
after _sale _nos : [ ... createdNos , ... alreadyExist ] ,
notified _groups : notifiedTotal ,
not _found : notFound ,
message : ` ${ lines . join ( '\n' ) } ,稍后客服将人工核实跟进 ` ,
direct _reply : true ,
} ,
} ;
} catch ( error ) {
ctx . logger . error ( ` [inbox functions] 改地址/催退回处理失败: ${ error . message } ` ) ;
return { success : false , error : ` 操作失败: ${ error . message } ` } ;
}
} ,
} ) ;
this . register ( 'weishoudao' , {
description : '货主售后群核实签收处理。客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时调用: 创建核实签收售后工单( verify_delivery) , 并把"运单号+核实签收"转发到对应快递的售后群通知快递核实' ,
weight : 89 ,
keywords : [ '核实签收' , '未收到' , '是否发出' , '是否已经发货' , '没有找到快递' ] ,
params : {
keyword : { type : 'string' , required : true , description : '运单号,多个用逗号或空格分隔,如 SF111,SF222' } ,
} ,
groups : [ GROUP . BOUND _STORE _AFTER _SALES ] ,
handler : async ( params = { } ) => {
const { ctx } = this ;
const raw = String ( params . keyword || '' ) . trim ( ) ;
const storeId = Number ( ctx . inboxContext ? . store _id || 0 ) ;
const warehouseId = Number ( ctx . inboxContext ? . warehouse _id || 0 ) ;
const groupName = String ( ctx . inboxContext ? . group _name || '' ) . trim ( ) ;
const userName = String ( ctx . inboxContext ? . user _name || '' ) . trim ( ) ;
const issue = { sub _type : 'verify_delivery' , label : '核实签收' } ;
if ( ! raw ) return { success : false , error : '请提供运单号' } ;
if ( ! warehouseId ) return { success : false , error : '无法获取仓库信息' } ;
if ( ! storeId ) return { success : false , error : '无法获取货主信息,请确认已在货主售后群上下文中操作' } ;
const keywords = raw . split ( /[,, \s\n]+/ ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
if ( keywords . length === 0 ) return { success : false , error : '未解析到有效运单号' } ;
const asLikeList = keywords . filter ( k => / ^ AS / i . test ( k ) ) ;
if ( asLikeList . length > 0 ) {
return { success : false , error : ` ${ asLikeList . join ( '、' ) } 是售后工单号而非运单号,请提供运单号 ` } ;
}
try {
// 原文(客户原始消息,写入工单明细)
let originalText = '' ;
try {
const mid = ctx . inboxContext ? . inbound _message _id ;
if ( mid ) {
const m = await ctx . model . InboxMessage . findByPk ( mid , { attributes : [ 'content' ] , raw : true } ) ;
if ( m && m . content ) originalText = String ( m . content ) ;
}
} catch ( e ) { /* ignore */ }
// 第一步:批量查询运单(限当前仓库 + 当前货主)
const expressList = await ctx . model . OrderExpress . findAll ( {
attributes : [ 'id' , 'waybill_code' , 'logistics_name' , 'store_id' , 'order_id' ,
'logistics_interface_id' , 'logistics_code' ] ,
where : {
waybill _code : { [ ctx . app . Sequelize . Op . in ] : keywords } ,
warehouse _id : warehouseId ,
store _id : storeId ,
} ,
raw : true ,
} ) ;
const foundCodes = new Set ( expressList . map ( e => e . waybill _code ) ) ;
const notFound = keywords . filter ( k => ! foundCodes . has ( k ) ) ;
if ( expressList . length === 0 ) {
return { success : false , error : ` 未找到当前货主在仓库中的运单「 ${ raw } 」,请核实单号后重试 ` } ;
}
// 第二步:幂等检查(同子类型未完结工单不重复建单)
const expressIds = expressList . map ( e => e . id ) ;
const existingASList = await ctx . model . AfterSale . findAll ( {
attributes : [ 'waybill_id' , 'after_sale_no' ] ,
where : {
waybill _id : { [ ctx . app . Sequelize . Op . in ] : expressIds } ,
type : 'order' ,
sub _type : issue . sub _type ,
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 ) ) ;
const alreadyExist = existingASList . map ( r => r . after _sale _no ) ;
const existedPairs = expressList
. filter ( e => existingWaybillIds . has ( e . id ) )
. map ( e => {
const row = existingASList . find ( r => Number ( r . waybill _id ) === Number ( e . id ) ) ;
return { waybill : e . waybill _code , as _no : ( row && row . after _sale _no ) || '' } ;
} )
. filter ( p => p . as _no ) ;
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
const createdNos = [ ] ;
const waybillToAsNo = { } ;
if ( toCreate . length > 0 ) {
const creatorLabel = [ groupName , userName ] . filter ( Boolean ) . join ( '-' ) || 'AI系统' ;
for ( const e of toCreate ) {
const afterSaleNo = await ctx . service . systemMethods . afterSale . generateAfterSaleNo ( warehouseId ) ;
const descParts = [
` 发起人: ${ creatorLabel } ` ,
` 运单号: ${ e . waybill _code } ` ,
` 快递公司: ${ e . logistics _name || '未知' } ` ,
` 诉求类型: ${ issue . label } ` ,
originalText ? ` 原文: ${ originalText } ` : '' ,
] . filter ( Boolean ) . join ( '\n' ) ;
await ctx . service . systems . afterSale . create ( {
warehouse _id : warehouseId ,
after _sale _no : afterSaleNo ,
type : 'order' ,
sub _type : issue . sub _type ,
title : ` [AI工单] ${ issue . label } - ${ e . waybill _code } ` ,
description : descParts ,
priority : 10 ,
creator _id : 0 ,
inbox _message _id : ctx . inboxContext ? . inbound _message _id || null ,
role _group : 'customer_service' ,
status : 'pending' ,
waybill _id : e . id ,
waybill _no : e . waybill _code ,
store _id : e . store _id || storeId ,
order _id : e . order _id || null ,
} ) ;
createdNos . push ( afterSaleNo ) ;
waybillToAsNo [ e . id ] = afterSaleNo ;
}
}
// 第四步:转发快递群(格式:运单号 + \n + 核实签收)
const expressByCode = { } ;
for ( const e of toCreate ) {
const code = e . logistics _code || '__unknown__' ;
if ( ! expressByCode [ code ] ) {
expressByCode [ code ] = { interfaceId : e . logistics _interface _id , waybills : [ ] } ;
}
expressByCode [ code ] . waybills . push ( e . waybill _code ) ;
}
let notifiedTotal = 0 ;
const notifiedWaybillIds = new Set ( ) ;
for ( const [ code , info ] of Object . entries ( expressByCode ) ) {
if ( code === '__unknown__' || ! info . interfaceId ) continue ;
try {
const { afterSalesGroups } = await ctx . service . systems . inbox . group . findGroupsByExpress ( {
expressInterfaceId : info . interfaceId ,
expressCode : code ,
warehouseId ,
} ) ;
if ( afterSalesGroups . length === 0 ) {
ctx . logger . info ( ` [inbox functions] 快递 ${ code } 未配置售后群,跳过转发 ` ) ;
continue ;
}
const forwardMsg = ` ${ 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 : forwardMsg ,
ext _data : g . ext _data || null ,
} ) ;
notifiedTotal += 1 ;
}
toCreate
. filter ( e => ( e . logistics _code || '__unknown__' ) === code )
. forEach ( e => notifiedWaybillIds . add ( e . id ) ) ;
} catch ( e ) {
ctx . logger . warn ( ` [inbox functions] 核实签收查快递群失败 code= ${ code } : ${ e . message } ` ) ;
}
}
// 第五步:有转发通知的工单升级 pending_feedback + 跟踪时限
const notifiedAsNos = createdNos . filter ( ( asNo , idx ) => notifiedWaybillIds . has ( toCreate [ idx ] . id ) ) ;
if ( notifiedAsNos . length > 0 ) {
try {
const hours = await ctx . service . systems . afterSale . _resolveFollowupHours (
warehouseId , 'order' , issue . sub _type
) ;
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 : { after _sale _no : { [ ctx . app . Sequelize . Op . in ] : notifiedAsNos } } }
) ;
} catch ( e ) {
ctx . logger . warn ( ` [inbox functions] 核实签收更新工单状态失败: ${ e . message } ` ) ;
}
}
// 第六步:客户回信模板(单号+诉求+工单)
const createdPairs = toCreate . map ( e => ( {
waybill : e . waybill _code ,
as _no : waybillToAsNo [ e . id ] || '' ,
} ) ) ;
const lines = [ ... createdPairs , ... existedPairs ] . map ( p => ` 运单 ${ p . waybill } ${ issue . label } 问题已登记,工单: ${ p . as _no } ` ) ;
if ( notFound . length > 0 ) {
lines . push ( ` 未找到运单: ${ notFound . join ( '、' ) } ,请核实单号 ` ) ;
}
ctx . logger . info (
` [inbox functions] 核实签收: total= ${ keywords . length } found= ${ expressList . length } created= ${ createdNos . length } notified= ${ notifiedTotal } `
) ;
return {
success : true ,
data : {
created : createdNos . length ,
existed : alreadyExist . length ,
after _sale _nos : [ ... createdNos , ... alreadyExist ] ,
notified _groups : notifiedTotal ,
not _found : notFound ,
message : ` ${ lines . join ( '\n' ) } ,稍后客服将人工核实跟进 ` ,
direct _reply : true ,
} ,
} ;
} catch ( error ) {
ctx . logger . error ( ` [inbox functions] 核实签收处理失败: ${ error . message } ` ) ;
return { success : false , error : ` 操作失败: ${ error . message } ` } ;
}
} ,
} ) ;
this . register ( 'changeExpress' , {
description : '货主售后群改快递。客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时调用。仅待处理表中未分配快递( post_status=none) 的订单可以修改快递; 已分配快递或不在待处理表的订单不能修改' ,
weight : 87 ,
keywords : [ '改快递' , '换快递' , '改圆通' , '改中通' , '改申通' , '改顺丰' , '改极兔' , '改韵达' , '改京东' , '改德邦' ] ,
params : {
keyword : { type : 'string' , required : true , description : '订单号(发货单号或平台单号),多个用逗号或空格分隔' } ,
express : { type : 'string' , required : true , description : '目标快递名称或编码,如 圆通/中通/顺丰,或系统编码如 YTO/STO/SF' } ,
} ,
groups : [ GROUP . BOUND _STORE _AFTER _SALES ] ,
handler : async ( params = { } ) => {
const { ctx } = this ;
const raw = String ( params . keyword || '' ) . trim ( ) ;
const expressRaw = String ( params . express || '' ) . trim ( ) ;
const storeId = Number ( ctx . inboxContext ? . store _id || 0 ) ;
const warehouseId = Number ( ctx . inboxContext ? . warehouse _id || 0 ) ;
const groupName = String ( ctx . inboxContext ? . group _name || '' ) . trim ( ) ;
const userName = String ( ctx . inboxContext ? . user _name || '' ) . trim ( ) ;
if ( ! raw ) return { success : false , error : '请提供订单号' } ;
if ( ! expressRaw ) return { success : false , error : '请提供目标快递(名称或编码),如 圆通/中通/顺丰' } ;
if ( ! warehouseId ) return { success : false , error : '无法获取仓库信息' } ;
if ( ! storeId ) return { success : false , error : '无法获取货主信息,请确认已在货主售后群上下文中操作' } ;
const keywords = raw . split ( /[,, \s\n]+/ ) . map ( s => s . trim ( ) ) . filter ( Boolean ) ;
if ( keywords . length === 0 ) return { success : false , error : '未解析到有效订单号' } ;
// 前置拦截: AS 开头为售后工单号,不是订单号
const asLikeList = keywords . filter ( k => / ^ AS / i . test ( k ) ) ;
if ( asLikeList . length > 0 ) {
return { success : false , error : ` ${ asLikeList . join ( '、' ) } 是售后工单号而非订单号,请提供发货单号或平台单号 ` } ;
}
try {
const { Op } = ctx . app . Sequelize ;
const factory = ctx . model . OrderDeliveryFactory ;
// 第一步:解析目标快递(兼容名称/别名/编码)。
// 快递列表服务依赖 ctx.user.store_id 作为仓库上下文,临时注入后恢复。
const originalUser = ctx . user ;
ctx . user = {
... ( originalUser || { } ) ,
store _id : warehouseId ,
employees _id : 0 ,
employees _name : [ groupName , userName ] . filter ( Boolean ) . join ( '-' ) || 'AI系统' ,
} ;
let expressList = [ ] ;
try {
expressList = await ctx . service . systems . express . getExpressList ( ) ;
} finally {
ctx . user = originalUser ;
}
const expressKey = expressRaw . toUpperCase ( ) ;
const list = Array . isArray ( expressList ) ? expressList : [ ] ;
// 第一轮:精确匹配(编码/名称/别名/系统编码)
let expressItem = list . find ( item => {
const code = String ( item . code || item . value || '' ) . trim ( ) . toUpperCase ( ) ;
const name = String ( item . name || '' ) . trim ( ) . toUpperCase ( ) ;
const alias = String ( item . alias || '' ) . trim ( ) . toUpperCase ( ) ;
const sysCode = String ( item . express _code || '' ) . trim ( ) . toUpperCase ( ) ;
return code === expressKey || name === expressKey || alias === expressKey || sysCode === expressKey ;
} ) ;
// 第二轮:模糊匹配(如客户说"圆通",列表名为"圆通快递")
if ( ! expressItem && expressKey . length >= 2 ) {
const fuzzy = list . filter ( item => {
const code = String ( item . code || item . value || '' ) . trim ( ) . toUpperCase ( ) ;
const name = String ( item . name || '' ) . trim ( ) . toUpperCase ( ) ;
const alias = String ( item . alias || '' ) . trim ( ) . toUpperCase ( ) ;
const fields = [ name , alias , code ] . filter ( Boolean ) ;
return fields . some ( f => f . includes ( expressKey ) || expressKey . includes ( f ) ) ;
} ) ;
if ( fuzzy . length === 1 ) {
expressItem = fuzzy [ 0 ] ;
} else if ( fuzzy . length > 1 ) {
const names = fuzzy . slice ( 0 , 10 )
. map ( item => ` ${ item . name || item . code || '' } ( ${ item . code || item . value || '' } ) ` )
. join ( '、' ) ;
return {
success : false ,
error : ` 快递「 ${ expressRaw } 」匹配到多个结果,请明确: ${ names } ` ,
} ;
}
}
if ( ! expressItem ) {
const names = list . slice ( 0 , 20 )
. map ( item => ` ${ item . name || item . code || '' } ( ${ item . code || item . value || '' } ) ` )
. join ( '、' ) ;
return {
success : false ,
error : ` 未找到快递「 ${ expressRaw } 」 ${ names ? ` ,当前仓库可选快递: ${ names } ` : '' } ` ,
} ;
}
// 第二步:查待处理表(仅当前货主)
const currentModel = await factory . getCurrentModel ( warehouseId ) ;
if ( ! currentModel ) {
return { success : false , error : ` 仓库 ${ warehouseId } 的待处理表不可用 ` } ;
}
const foundOrders = await currentModel . findAll ( {
attributes : [
'id' , 'delivery_order_code' , 'source_platform_code' , 'source_order_codes' ,
'post_status' , 'logistics_name' ,
] ,
where : {
store _id : storeId ,
[ Op . or ] : [
{ delivery _order _code : { [ Op . in ] : keywords } } ,
{ source _platform _code : { [ Op . in ] : keywords } } ,
... keywords . map ( k => ( { source _order _codes : { [ Op . like ] : ` % ${ k } % ` } } ) ) ,
] ,
} ,
raw : true ,
} ) ;
const foundCodes = new Set ( ) ;
for ( const o of foundOrders ) {
foundCodes . add ( o . delivery _order _code ) ;
foundCodes . add ( o . source _platform _code ) ;
for ( const sc of String ( o . source _order _codes || '' ) . split ( ',' ) ) {
if ( sc . trim ( ) ) foundCodes . add ( sc . trim ( ) ) ;
}
}
const missing = keywords . filter ( k => ! foundCodes . has ( k ) ) ;
// 第三步:未在待处理表找到的 → 查配送表/历史表,区分"不在待处理表"与"未找到"
const notInPending = [ ] ;
const notFound = [ ] ;
if ( missing . length > 0 ) {
const tableConfigs = [
{ getModel : ( f , wid ) => f . getDispatchModel ( wid ) } ,
{ getModel : ( f , wid ) => f . getHistoryModel ( wid ) } ,
] ;
const missingSet = new Set ( missing ) ;
for ( const cfg of tableConfigs ) {
if ( missingSet . size === 0 ) break ;
const model = await cfg . getModel ( factory , warehouseId ) ;
if ( ! model ) continue ;
const rows = await model . findAll ( {
attributes : [ 'delivery_order_code' , 'source_platform_code' , 'source_order_codes' ] ,
where : {
store _id : storeId ,
[ Op . or ] : [
{ delivery _order _code : { [ Op . in ] : [ ... missingSet ] } } ,
{ source _platform _code : { [ Op . in ] : [ ... missingSet ] } } ,
... [ ... missingSet ] . map ( k => ( { source _order _codes : { [ Op . like ] : ` % ${ k } % ` } } ) ) ,
] ,
} ,
raw : true ,
} ) ;
for ( const r of rows ) {
const codes = [
r . delivery _order _code ,
r . source _platform _code ,
... String ( r . source _order _codes || '' ) . split ( ',' ) ,
] . map ( s => String ( s || '' ) . trim ( ) ) . filter ( Boolean ) ;
for ( const k of [ ... missingSet ] ) {
if ( codes . includes ( k ) ) {
missingSet . delete ( k ) ;
notInPending . push ( k ) ;
}
}
}
}
for ( const k of missingSet ) notFound . push ( k ) ;
}
// 第四步: 区分可改( post_status=none) 与已分配快递
const eligible = foundOrders . filter ( o => String ( o . post _status || '' ) . trim ( ) === 'none' ) ;
const allocated = foundOrders . filter ( o => String ( o . post _status || '' ) . trim ( ) !== 'none' ) ;
// 第五步:逐个改快递(复用 updateOrderExpress, 内部自带 post_status=none 保护)
const expressCode = String ( expressItem . code || expressItem . value || '' ) . trim ( ) ;
const changed = [ ] ;
const unchanged = [ ] ;
for ( const o of eligible ) {
try {
const originalUser2 = ctx . user ;
ctx . user = {
... ( originalUser2 || { } ) ,
store _id : warehouseId ,
employees _id : 0 ,
employees _name : [ groupName , userName ] . filter ( Boolean ) . join ( '-' ) || 'AI系统' ,
} ;
let updateResult = null ;
try {
updateResult = await ctx . service . systemMethods . order . pendingOrder . updateOrderExpress ( {
order _ids : [ o . id ] ,
express _code : expressCode ,
} ) ;
} finally {
ctx . user = originalUser2 ;
}
const updated = Number ( updateResult && updateResult . updated _count ) || 0 ;
if ( updated > 0 ) {
changed . push ( o . delivery _order _code ) ;
} else {
unchanged . push ( o . delivery _order _code ) ;
}
} catch ( e ) {
ctx . logger . warn ( ` [inbox functions] 改快递失败 order= ${ o . delivery _order _code } : ${ e . message } ` ) ;
unchanged . push ( o . delivery _order _code ) ;
}
}
// 第六步:组装模板回复
const expressName = String ( expressItem . name || expressItem . code || expressRaw ) . trim ( ) ;
const lines = [ ] ;
if ( changed . length > 0 ) {
lines . push ( ` 已改快递为「 ${ expressName } 」: ${ changed . join ( '、' ) } ` ) ;
}
if ( allocated . length > 0 ) {
lines . push ( ` 已分配快递,不能修改: ${ allocated . map ( o => ` ${ o . delivery _order _code } ( ${ o . logistics _name || '已取号' } ) ` ) . join ( '、' ) } ` ) ;
}
if ( unchanged . length > 0 ) {
lines . push ( ` 改快递未生效(可能刚分配了快递),请核实: ${ unchanged . join ( '、' ) } ` ) ;
}
if ( notInPending . length > 0 ) {
lines . push ( ` 不在待处理表,不能修改: ${ notInPending . join ( '、' ) } ` ) ;
}
if ( notFound . length > 0 ) {
lines . push ( ` 未找到订单: ${ notFound . join ( '、' ) } ` ) ;
}
ctx . logger . info (
` [inbox functions] 改快递: total= ${ keywords . length } eligible= ${ eligible . length } ` +
` changed= ${ changed . length } allocated= ${ allocated . length } notInPending= ${ notInPending . length } notFound= ${ notFound . length } `
) ;
return {
success : true ,
data : {
changed : changed . length ,
allocated : allocated . length ,
not _in _pending : notInPending . length ,
not _found : notFound . length ,
express : expressName ,
message : lines . join ( '\n' ) ,
direct _reply : true ,
} ,
} ;
} catch ( error ) {
ctx . logger . error ( ` [inbox functions] 改快递失败: ${ error . message } ` ) ;
return { success : false , error : ` 操作失败: ${ error . message } ` } ;
}
} ,
} ) ;
this . register ( 'handleExpressFeedback' , {
description : '快递群售后通用反馈。传入运单号, 优先找已有售后工单追加记录, 无工单则按运单查订单并自动创建售后工单。AI 可根据快递反馈内容传入售后类型和子类型' ,
weight : 90 ,
@ -1915,6 +2810,80 @@ class InboxFunctionsService extends Service {
} ,
} ) ;
this . register ( 'queryWarehouseAddress' , {
description : '查询仓库收货地址(退货/退件寄回地址)。读取仓库配置中的 receiver_address。用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时调用。仅货主群和仓库群可用,快递群不可用' ,
weight : 80 ,
keywords : [ '仓库地址' , '收货地址' , '退货地址' , '退件地址' , '寄回地址' , '寄件地址' ] ,
params : { } ,
groups : [ GROUP . BOUND _STORE _WILDCARD , GROUP . BOUND _WAREHOUSE _WILDCARD ] ,
handler : async ( params = { } ) => {
const { ctx } = this ;
void params ;
const warehouseId = Number ( ctx . inboxContext ? . warehouse _id || 0 ) ;
if ( ! warehouseId ) {
return { success : false , error : '无法获取仓库信息' } ;
}
try {
const store = await ctx . model . Store . findByPk ( warehouseId , {
attributes : [ 'id' , 'subject_config' ] ,
raw : true ,
} ) ;
if ( ! store ) {
return { success : false , error : ` 仓库 ${ warehouseId } 不存在 ` } ;
}
// 读取仓库配置 subject_config.receiver_address( 兼容 JSON 字符串形态)
let config = store . subject _config ;
if ( typeof config === 'string' ) {
try {
config = JSON . parse ( config ) ;
} catch ( e ) {
config = null ;
}
}
if ( ! config || typeof config !== 'object' || Array . isArray ( config ) ) {
config = { } ;
}
const receiverAddress = String ( config . receiver _address || '' ) . trim ( ) ;
if ( ! receiverAddress ) {
return {
success : true ,
data : {
warehouse _id : warehouseId ,
receiver _address : '' ,
message : '当前仓库未配置收货地址,请联系仓管在仓库设置中维护「仓库收货地址」' ,
direct _reply : true ,
} ,
} ;
}
// 配置中可能存的是字面 \n, 转成真实换行便于群消息阅读
const displayAddress = receiverAddress
. replace ( /\\r\\n/g , '\n' )
. replace ( /\\n/g , '\n' )
. replace ( /\\r/g , '\n' ) ;
return {
success : true ,
data : {
warehouse _id : warehouseId ,
receiver _address : receiverAddress ,
message : ` 仓库收货地址: \n ${ displayAddress } ` ,
direct _reply : true ,
} ,
} ;
} catch ( error ) {
ctx . logger . error ( ` [inbox functions] 查询仓库收货地址失败: ${ error . message } ` ) ;
return { success : false , error : ` 查询仓库地址失败: ${ error . message } ` } ;
}
} ,
} ) ;
this . register ( 'listGroups' , {
description : '查询当前仓库的群列表,包含屏蔽状态(仅内部仓库群可用)' ,
params : { } ,