Merge branch 'v3' into test

This commit is contained in:
renzhiyuan 2025-11-26 10:51:26 +08:00
commit 4619389f4f
23 changed files with 1367 additions and 151 deletions

View File

@ -55,6 +55,15 @@ tools:
enabled: true
api_key: "dingsbbntrkeiyazcfdg"
api_secret: "ObqxwyR20r9rVNhju0sCPQyQA98_FZSc32W4vgxnGFH_b02HZr1BPCJsOAF816nu"
zltxOrderAfterSaleDetail:
enabled: true
base_url: "https://revcl.1688sup.com/api/admin/afterSales/direct/%s"
api_key : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyQ2VudGVyIiwiZXhwIjoxNzU2MTgyNTM1LCJuYmYiOjE3NTYxODA3MzUsImp0aSI6IjEiLCJQaG9uZSI6IjE4MDAwMDAwMDAwIiwiVXNlck5hbWUiOiJsc3hkIiwiUmVhbE5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJBY2NvdW50VHlwZSI6MSwiR3JvdXBDb2RlcyI6IlZDTF9DQVNISUVSLFZDTF9PUEVSQVRFLFZDTF9BRE1JTixWQ0xfQUFBLFZDTF9WQ0xfT1BFUkFULFZDTF9JTlZPSUNFLENSTV9BRE1JTixMSUFOTElBTl9BRE1JTixNQVJLRVRNQUcyX0FETUlOLFBIT05FQklMTF9BRE1JTixRSUFOWkhVX1NVUFBFUl9BRE0sTUFSS0VUSU5HU0FBU19TVVBFUkFETUlOLENBUkRfQ09ERSxDQVJEX1BST0NVUkVNRU5ULE1BUktFVElOR1NZU1RFTV9TVVBFUixTVEFUSVNUSUNBTFNZU1RFTV9BRE1JTixaTFRYX0FETUlOLFpMVFhfT1BFUkFURSIsIkRpbmdVc2VySWQiOiIxNjIwMjYxMjMwMjg5MzM4MzQifQ.N1xv1PYbcO8_jR5adaczc16YzGsr4z101gwEZdulkRaREBJNYTOnFrvRxTFx3RJTooXsqTqroE1MR84v_1WPX6BS6kKonA-kC1Jgot6yrt5rFWhGNGb2Cpr9rKIFCCQYmiGd3AUgDazEeaQ0_sodv3E-EXg9VfE1SX8nMcck9Yjnc8NCy7RTWaBIaSeOdZcEl-JfCD0S6GSx3oErp_hk-U9FKGwf60wAuDGTY1R0BP4BYpcEqS-C2LSnsSGyURi54Cuk5xH8r1WuF0Dm5bwAj5d7Hvs77-N_sUF-C5ONqyZJRAEhYLgcmN9RX_WQZfizdQJxizlTczdpzYfy-v-1eQ"
zltxOrderAfterSalePreCheck:
enabled: true
base_url: "https://gateway.dev.cdlsxd.cn/zltx_api/admin/afterSales/reseller_pre"
api_key : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ1c2VyQ2VudGVyIiwiZXhwIjoxNzU2MTgyNTM1LCJuYmYiOjE3NTYxODA3MzUsImp0aSI6IjEiLCJQaG9uZSI6IjE4MDAwMDAwMDAwIiwiVXNlck5hbWUiOiJsc3hkIiwiUmVhbE5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJBY2NvdW50VHlwZSI6MSwiR3JvdXBDb2RlcyI6IlZDTF9DQVNISUVSLFZDTF9PUEVSQVRFLFZDTF9BRE1JTixWQ0xfQUFBLFZDTF9WQ0xfT1BFUkFULFZDTF9JTlZPSUNFLENSTV9BRE1JTixMSUFOTElBTl9BRE1JTixNQVJLRVRNQUcyX0FETUlOLFBIT05FQklMTF9BRE1JTixRSUFOWkhVX1NVUFBFUl9BRE0sTUFSS0VUSU5HU0FBU19TVVBFUkFETUlOLENBUkRfQ09ERSxDQVJEX1BST0NVUkVNRU5ULE1BUktFVElOR1NZU1RFTV9TVVBFUixTVEFUSVNUSUNBTFNZU1RFTV9BRE1JTixaTFRYX0FETUlOLFpMVFhfT1BFUkFURSIsIkRpbmdVc2VySWQiOiIxNjIwMjYxMjMwMjg5MzM4MzQifQ.N1xv1PYbcO8_jR5adaczc16YzGsr4z101gwEZdulkRaREBJNYTOnFrvRxTFx3RJTooXsqTqroE1MR84v_1WPX6BS6kKonA-kC1Jgot6yrt5rFWhGNGb2Cpr9rKIFCCQYmiGd3AUgDazEeaQ0_sodv3E-EXg9VfE1SX8nMcck9Yjnc8NCy7RTWaBIaSeOdZcEl-JfCD0S6GSx3oErp_hk-U9FKGwf60wAuDGTY1R0BP4BYpcEqS-C2LSnsSGyURi54Cuk5xH8r1WuF0Dm5bwAj5d7Hvs77-N_sUF-C5ONqyZJRAEhYLgcmN9RX_WQZfizdQJxizlTczdpzYfy-v-1eQ"
default_prompt:
img_recognize:

View File

@ -55,6 +55,12 @@ tools:
enabled: true
api_key: "dingsbbntrkeiyazcfdg"
api_secret: "ObqxwyR20r9rVNhju0sCPQyQA98_FZSc32W4vgxnGFH_b02HZr1BPCJsOAF816nu"
zltxOrderAfterSaleSupplier:
enabled: true
base_url: "https://revcl.1688sup.com/api/admin/afterSales/reseller_supplier"
zltxOrderAfterSaleReseller:
enabled: true
base_url: "https://revcl.1688sup.com/api/admin/afterSales/reseller_supplier"
default_prompt:
img_recognize:
@ -64,4 +70,7 @@ default_prompt:
提取出图片中对用户可能有用的关键信息(例如金额、日期、标题、编号、联系信息、商品名称等)。
若图片为文档类(如合同、发票、收据),请结构化输出关键字段(如客户名称、金额、开票日期等)。
'
user_prompt: '识别图片内容'
user_prompt: '识别图片内容'
# 权限配置
permissionConfig:
permission_url: "http://api.test.user.1688sup.cn:8001/v1/menu/myCodes?systemId="

View File

@ -6,10 +6,13 @@ import (
"ai_scheduler/internal/data/impl"
"ai_scheduler/internal/data/model"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/gateway"
"ai_scheduler/internal/pkg"
"ai_scheduler/tmpl/dataTemp"
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
@ -22,7 +25,7 @@ import (
)
type Do struct {
Ctx *entitys.RequireData
//Ctx *entitys.RequireData
sessionImpl *impl.SessionImpl
sysImpl *impl.SysImpl
taskImpl *impl.TaskImpl
@ -44,78 +47,125 @@ func NewDo(
}
}
func (d *Do) InitCtx(req *entitys.ChatSockRequest) *Do {
d.Ctx = &entitys.RequireData{
Req: req,
func (d *Do) DataAuth(ctx context.Context, client *gateway.Client, requireData *entitys.RequireData) (err error) {
// 1. 验证客户端数据
if err = d.validateClientData(client, requireData); err != nil {
return err
}
return d
// 2. 加载系统信息
if err = d.loadSystemInfo(ctx, client, requireData); err != nil {
return fmt.Errorf("获取系统信息失败: %w", err)
}
// 3. 加载任务列表
if err = d.loadTaskList(ctx, client, requireData); err != nil {
return fmt.Errorf("获取任务列表失败: %w", err)
}
// 4. 加载聊天历史
if err = d.loadChatHistory(ctx, requireData); err != nil {
return fmt.Errorf("获取历史记录失败: %w", err)
}
// 5. 加载图片数据
if err = d.getImgData(requireData); err != nil {
return err
}
// 6. 加载用户权限
if _, err = d.LoadUserPermission(client, requireData); err != nil {
return fmt.Errorf("获取用户权限失败: %w", err)
}
return nil
}
func (d *Do) DataAuth(c *websocket.Conn) (err error) {
d.Ctx.Session = c.Query("x-session", "")
if len(d.Ctx.Session) == 0 {
err = errors.SessionNotFound
return
}
d.Ctx.Auth = c.Query("x-authorization", "")
if len(d.Ctx.Auth) == 0 {
err = errors.AuthNotFound
return
}
d.Ctx.Key = c.Query("x-app-key", "")
if len(d.Ctx.Key) == 0 {
err = errors.KeyNotFound
return
// 提取数据验证为单独函数
func (d *Do) validateClientData(client *gateway.Client, requireData *entitys.RequireData) error {
requireData.Session = client.GetSession()
if len(requireData.Session) == 0 {
return errors.SessionNotFound
}
d.Ctx.Sys, err = d.getSysInfo()
if err != nil {
err = errors.SysErr("获取系统信息失败:%v", err.Error())
return
}
d.Ctx.Histories, err = d.getSessionChatHis()
if err != nil {
err = errors.SysErr("获取历史记录失败:%v", err.Error())
return
requireData.Auth = client.GetAuth()
if len(requireData.Auth) == 0 {
return errors.AuthNotFound
}
d.Ctx.Tasks, err = d.getTasks(d.Ctx.Sys.SysID)
if err != nil {
err = errors.SysErr("获取任务列表失败:%v", err.Error())
return
}
if err = d.getImgData(); err != nil {
return
requireData.Key = client.GetKey()
if len(requireData.Key) == 0 {
return errors.KeyNotFound
}
return
return nil
}
func (d *Do) MakeCh(c *websocket.Conn) (ctx context.Context, deferFunc func()) {
d.Ctx.Ch = make(chan entitys.Response)
// 获取系统信息的辅助函数
func (d *Do) loadSystemInfo(ctx context.Context, client *gateway.Client, requireData *entitys.RequireData) error {
if sysInfo := client.GetSysInfo(); sysInfo == nil {
sys, err := d.getSysInfo(requireData)
if err != nil {
return err
}
client.SetSysInfo(&sys)
requireData.Sys = sys
} else {
requireData.Sys = *sysInfo
}
return nil
}
// 获取任务列表的辅助函数
func (d *Do) loadTaskList(ctx context.Context, client *gateway.Client, requireData *entitys.RequireData) error {
if taskInfo := client.GetTasks(); len(taskInfo) == 0 {
tasks, err := d.getTasks(requireData.Sys.SysID)
if err != nil {
return err
}
requireData.Tasks = tasks
client.SetTasks(tasks)
} else {
requireData.Tasks = taskInfo
}
return nil
}
// 获取历史记录的辅助函数
func (d *Do) loadChatHistory(ctx context.Context, requireData *entitys.RequireData) error {
histories, err := d.getSessionChatHis(requireData)
if err != nil {
return err
}
requireData.Histories = histories
return nil
}
func (d *Do) MakeCh(c *websocket.Conn, requireData *entitys.RequireData) (ctx context.Context, deferFunc func()) {
requireData.Ch = make(chan entitys.Response)
ctx, cancel := context.WithCancel(context.Background())
done := d.startMessageHandler(ctx, c)
done := d.startMessageHandler(ctx, c, requireData)
return ctx, func() {
close(d.Ctx.Ch) //关闭主通道
<-done // 等待消息处理完成
close(requireData.Ch) //关闭主通道
<-done // 等待消息处理完成
cancel()
}
}
func (d *Do) getImgData() (err error) {
if len(d.Ctx.Req.Img) == 0 {
func (d *Do) getImgData(requireData *entitys.RequireData) (err error) {
if len(requireData.Req.Img) == 0 {
return
}
imgs := strings.Split(d.Ctx.Req.Img, ",")
imgs := strings.Split(requireData.Req.Img, ",")
if len(imgs) == 0 {
return
}
for k, img := range imgs {
baseErr := "获取第" + strconv.Itoa(k+1) + "张图片失败:"
entitys.ResLog(d.Ctx.Ch, "img_get_start", "正在获取第"+strconv.Itoa(k+1)+"张图片")
entitys.ResLog(requireData.Ch, "img_get_start", "正在获取第"+strconv.Itoa(k+1)+"张图片")
if err = pkg.ValidateImageURL(img); err != nil {
entitys.ResLog(d.Ctx.Ch, "", baseErr+"expected image content")
entitys.ResLog(requireData.Ch, "", baseErr+"expected image content")
continue
}
req := l_request.Request{
@ -128,20 +178,20 @@ func (d *Do) getImgData() (err error) {
}
res, _err := req.Send()
if _err != nil {
entitys.ResLog(d.Ctx.Ch, "", baseErr+_err.Error())
entitys.ResLog(requireData.Ch, "", baseErr+_err.Error())
continue
}
if _, ex := res.Headers["Content-Type"]; !ex {
entitys.ResLog(d.Ctx.Ch, "", baseErr+"Content-Type不存在")
entitys.ResLog(requireData.Ch, "", baseErr+"Content-Type不存在")
continue
}
if !strings.HasPrefix(res.Headers["Content-Type"], "image/") {
entitys.ResLog(d.Ctx.Ch, "", baseErr+"expected image content")
entitys.ResLog(requireData.Ch, "", baseErr+"expected image content")
continue
}
d.Ctx.ImgByte = append(d.Ctx.ImgByte, res.Content)
d.Ctx.ImgUrls = append(d.Ctx.ImgUrls, img)
entitys.ResLog(d.Ctx.Ch, "img_get_end", "第"+strconv.Itoa(k+1)+"张图片获取成功")
requireData.ImgByte = append(requireData.ImgByte, res.Content)
requireData.ImgUrls = append(requireData.ImgUrls, img)
entitys.ResLog(requireData.Ch, "img_get_end", "第"+strconv.Itoa(k+1)+"张图片获取成功")
}
return
@ -152,19 +202,19 @@ func (d *Do) getRequireData() (err error) {
return
}
func (d *Do) getSysInfo() (sysInfo model.AiSy, err error) {
func (d *Do) getSysInfo(requireData *entitys.RequireData) (sysInfo model.AiSy, err error) {
cond := builder.NewCond()
cond = cond.And(builder.Eq{"app_key": d.Ctx.Key})
cond = cond.And(builder.Eq{"app_key": requireData.Key})
cond = cond.And(builder.IsNull{"delete_at"})
cond = cond.And(builder.Eq{"status": 1})
err = d.sysImpl.GetOneBySearchToStrut(&cond, &sysInfo)
return
}
func (d *Do) getSessionChatHis() (his []model.AiChatHi, err error) {
func (d *Do) getSessionChatHis(requireData *entitys.RequireData) (his []model.AiChatHi, err error) {
cond := builder.NewCond()
cond = cond.And(builder.Eq{"session_id": d.Ctx.Session})
cond = cond.And(builder.Eq{"session_id": requireData.Session})
_, err = d.hisImpl.GetListToStruct(&cond, &dataTemp.ReqPageBo{Limit: d.conf.Sys.SessionLen}, &his, "his_id desc")
@ -186,7 +236,7 @@ func (d *Do) getTasks(sysId int32) (tasks []model.AiTask, err error) {
func (d *Do) startMessageHandler(
ctx context.Context,
c *websocket.Conn,
requireData *entitys.RequireData,
) <-chan struct{} {
done := make(chan struct{})
var chat []string
@ -200,10 +250,10 @@ func (d *Do) startMessageHandler(
)
if len(chat) > 0 {
AiRes := &model.AiChatHi{
SessionID: d.Ctx.Session,
Ques: d.Ctx.Req.Text,
SessionID: requireData.Session,
Ques: requireData.Req.Text,
Ans: strings.Join(chat, ""),
Files: d.Ctx.Req.Img,
Files: requireData.Req.Img,
}
d.hisImpl.AddWithData(AiRes)
hisLog.HisId = AiRes.HisID
@ -216,7 +266,7 @@ func (d *Do) startMessageHandler(
}()
for v := range d.Ctx.Ch { // 自动检测通道关闭
for v := range requireData.Ch { // 自动检测通道关闭
if err := sendWithTimeout(c, v, 2*time.Second); err != nil {
log.Errorf("Send error: %v", err)
return
@ -255,3 +305,51 @@ func sendWithTimeout(c *websocket.Conn, data entitys.Response, timeout time.Dura
return sendCtx.Err()
}
}
// 从统一登录平台获取用户权限
func (d *Do) LoadUserPermission(client *gateway.Client, requireData *entitys.RequireData) (codes []string, err error) {
if len(client.GetCodes()) > 0 {
return client.GetCodes(), nil
}
var (
request l_request.Request
)
// 构建请求URL
request.Url = d.conf.PermissionConfig.PermissionURL + strconv.Itoa(int(requireData.Sys.SysID))
request.Method = "GET"
request.Headers = map[string]string{
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "application/json, text/plain, */*",
"Authorization": "Bearer " + client.GetAuth(),
}
// 发送请求
res, err := request.Send()
if err != nil {
return
}
// 检查响应状态码
if res.StatusCode != http.StatusOK {
err = errors.SysErr("获取用户权限失败")
return
}
type resp struct {
Codes []string `json:"codes"`
}
// 解析响应体
var respBody resp
err = json.Unmarshal([]byte(res.Text), &respBody)
if err != nil {
return
}
// 设置客户端权限
client.SetCodes(respBody.Codes)
return respBody.Codes, nil
}

View File

@ -8,6 +8,7 @@ import (
"ai_scheduler/internal/data/impl"
"ai_scheduler/internal/data/model"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/gateway"
"ai_scheduler/internal/pkg"
"ai_scheduler/internal/pkg/l_request"
"ai_scheduler/internal/pkg/mapstructure"
@ -16,6 +17,7 @@ import (
"context"
"encoding/json"
"fmt"
"gorm.io/gorm/utils"
"strings"
)
@ -68,7 +70,7 @@ func (r *Handle) handleOtherTask(ctx context.Context, requireData *entitys.Requi
return
}
func (r *Handle) HandleMatch(ctx context.Context, requireData *entitys.RequireData) (err error) {
func (r *Handle) HandleMatch(ctx context.Context, client *gateway.Client, requireData *entitys.RequireData) (err error) {
if !requireData.Match.IsMatch {
if len(requireData.Match.Chat) != 0 {
@ -90,6 +92,13 @@ func (r *Handle) HandleMatch(ctx context.Context, requireData *entitys.RequireDa
if pointTask == nil || pointTask.Index == "other" {
return r.OtherTask(ctx, requireData)
}
// 校验用户权限
// if err = r.PermissionAuth(client, pointTask); err != nil {
// log.Errorf("权限验证失败: %s", err.Error())
// return
// }
switch constants.TaskType(pointTask.Type) {
case constants.TaskTypeApi:
return r.handleApiTask(ctx, requireData, pointTask)
@ -252,3 +261,13 @@ func (r *Handle) handleApiTask(ctx context.Context, requireData *entitys.Require
return
}
// 权限验证
func (r *Handle) PermissionAuth(client *gateway.Client, pointTask *model.AiTask) (err error) {
// 授权检查权限
if !utils.Contains(client.GetCodes(), pointTask.Index) {
return fmt.Errorf("用户权限不足: %s", pointTask.Name)
}
return nil
}

View File

@ -15,7 +15,7 @@ type LlmService interface {
// buildSystemPrompt 构建系统提示词
func buildSystemPrompt(prompt string) string {
if len(prompt) == 0 {
prompt = "[system] 你是一个智能路由系统,核心职责是 **精准解析用户意图并路由至对应任务模块**\n[rule]\n1.返回以下格式的JSON{ \"index\": \"工具索引index\", \"confidence\": 0.0-1.0,\"reasoning\": \"判断理由\"}\n2.严格返回字符串格式禁用markdown格式返回\n3.只返回json字符串不包含任何其他解释性文字\n4.当用户意图非常不清晰时使用,尝试进行追问具体希望查询内容"
prompt = "[system] 你是一个智能路由系统,核心职责是 **精准解析用户意图并路由至对应任务模块**\n[rule]\n1.返回以下格式的JSON{ \"index\": \"工具索引index\", \"confidence\": 0.0-1.0,\"reasoning\": \"判断理由\"}\n2.严格返回字符串格式禁用markdown格式返回\n3.只返回json字符串不包含任何其他解释性文字\n4.当用户意图非常不清晰时使用,尝试进行追问具体希望查询内容,\n当前时间是" + time.Now().Format(time.DateTime)
}
return prompt

View File

@ -2,11 +2,11 @@ package biz
import (
"ai_scheduler/internal/biz/do"
"ai_scheduler/internal/gateway"
"ai_scheduler/internal/entitys"
"github.com/gofiber/fiber/v2/log"
"github.com/gofiber/websocket/v2"
)
// AiRouterBiz 智能路由服务
@ -26,28 +26,45 @@ func NewAiRouterBiz(
}
}
func (r *AiRouterBiz) RouteWithSocket(c *websocket.Conn, req *entitys.ChatSockRequest) (err error) {
//必要数据验证和获取
dos := r.do.InitCtx(req)
// 路由处理WebSocket请求
//
// 参数:
// - client: 网关客户端
// - req: 聊天请求结构体
//
// 返回:
// - err: 错误信息
func (r *AiRouterBiz) RouteWithSocket(client *gateway.Client, req *entitys.ChatSockRequest) (err error) {
// 创建请求上下文数据
requireData := &entitys.RequireData{
Req: req,
}
// 获取WebSocket连接
conn := client.GetConn()
//初始化通道/上下文
ctx, clearFunc := dos.MakeCh(c)
defer clearFunc()
ctx, clearFunc := r.do.MakeCh(conn, requireData)
defer func() {
if err != nil {
entitys.ResError(requireData.Ch, "", err.Error())
}
clearFunc()
}()
//数据验证和收集
if err = dos.DataAuth(c); err != nil {
if err = r.do.DataAuth(ctx, client, requireData); err != nil {
log.Errorf("数据验证和收集失败: %s", err.Error())
return
}
//意图识别
if err = r.handle.Recognize(ctx, dos.Ctx); err != nil {
if err = r.handle.Recognize(ctx, requireData); err != nil {
log.Errorf("意图识别失败: %s", err.Error())
return
}
//向下传递
if err = r.handle.HandleMatch(ctx, dos.Ctx); err != nil {
if err = r.handle.HandleMatch(ctx, client, requireData); err != nil {
log.Errorf("任务处理失败: %s", err.Error())
return
}

View File

@ -1,10 +1,18 @@
package biz
import (
"ai_scheduler/internal/data/constants"
errors "ai_scheduler/internal/data/error"
"ai_scheduler/internal/data/impl"
"ai_scheduler/internal/data/model"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/pkg/l_request"
"context"
"encoding/json"
"net/http"
"strconv"
"gorm.io/gorm/utils"
"xorm.io/builder"
@ -24,12 +32,62 @@ func NewTaskBiz(conf *config.Config, taskRepo *impl.TaskImpl) *TaskBiz {
}
// taskList 功能列表
func (t *TaskBiz) TaskList(ctx context.Context, req *entitys.TaskRequest) (list []model.AiTask, err error) {
func (t *TaskBiz) TaskList(ctx context.Context, req *entitys.TaskRequest, auth string) (list []model.AiTask, err error) {
tasks := make([]model.AiTask, 0)
cond := builder.NewCond()
cond = cond.And(builder.Eq{"status": 1})
cond = cond.And(builder.Eq{"status": constants.Enable})
cond = cond.And(builder.Eq{"sys_id": req.SysId})
err = t.taskRepo.GetRangeToMapStruct(&cond, &list)
cond = cond.And(builder.Eq{"is_show": constants.IsSHOW})
err = t.taskRepo.GetRangeToMapStruct(&cond, &tasks)
codes, err := t.GetUserPermission(req, auth)
if err != nil {
return
}
// 检查用户是否有权限
for _, task := range tasks {
if utils.Contains(codes, task.Index) {
list = append(list, task)
}
}
return
}
// 从统一登录平台获取用户权限
func (t *TaskBiz) GetUserPermission(req *entitys.TaskRequest, auth string) (codes []string, err error) {
request := l_request.Request{
Method: "GET",
Url: t.conf.PermissionConfig.PermissionURL + strconv.Itoa(int(req.SysId)),
Headers: map[string]string{
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept": "application/json, text/plain, */*",
"Authorization": auth,
},
}
// 发送请求
res, err := request.Send()
if err != nil {
return
}
// 检查响应状态码
if res.StatusCode != http.StatusOK {
err = errors.SysErr("获取用户权限失败")
return
}
type resp struct {
Codes []string `json:"codes"`
}
// 解析响应体s
var respBody resp
err = json.Unmarshal([]byte(res.Text), &respBody)
if err != nil {
return
}
return respBody.Codes, nil
}

View File

@ -9,14 +9,15 @@ import (
// Config 应用配置
type Config struct {
Server ServerConfig `mapstructure:"server"`
Ollama OllamaConfig `mapstructure:"ollama"`
Sys SysConfig `mapstructure:"sys"`
Tools ToolsConfig `mapstructure:"tools"`
Logging LoggingConfig `mapstructure:"logging"`
Redis Redis `mapstructure:"redis"`
DB DB `mapstructure:"db"`
DefaultPrompt SysPrompt `mapstructure:"default_prompt"`
Server ServerConfig `mapstructure:"server"`
Ollama OllamaConfig `mapstructure:"ollama"`
Sys SysConfig `mapstructure:"sys"`
Tools ToolsConfig `mapstructure:"tools"`
Logging LoggingConfig `mapstructure:"logging"`
Redis Redis `mapstructure:"redis"`
DB DB `mapstructure:"db"`
DefaultPrompt SysPrompt `mapstructure:"default_prompt"`
PermissionConfig PermissionConfig `mapstructure:"permissionConfig"`
// LLM *LLM `mapstructure:"llm"`
}
@ -89,6 +90,14 @@ type ToolsConfig struct {
//通过账号获取订单统计信息
ZltxOrderStatistics ToolConfig `mapstructure:"zltxOrderStatistics"`
DingTalkBot ToolConfig `mapstructure:"dingTalkBot"`
//上游售后订单流水详情
ZltxOrderAfterSaleDetail ToolConfig `mapstructure:"zltxOrderAfterSaleDetail"`
//下游订单预检
ZltxOrderAfterSalePreCheck ToolConfig `mapstructure:"zltxOrderAfterSalePreCheck"`
// 上游订单售后
ZltxOrderAfterSaleSupplier ToolConfig `mapstructure:"zltxOrderAfterSaleSupplier"`
// 下游订单售后
ZltxOrderAfterSaleReseller ToolConfig `mapstructure:"zltxOrderAfterSaleReseller"`
}
// ToolConfig 单个工具配置
@ -107,6 +116,12 @@ type LoggingConfig struct {
Format string `mapstructure:"format"`
}
// PermissionConfig 权限校验配置
type PermissionConfig struct {
// 获取权限的地址
PermissionURL string `mapstructure:"permission_url"`
}
// LoadConfig 加载配置
func LoadConfig(configPath string) (*Config, error) {
viper.SetConfigFile(configPath)

View File

@ -0,0 +1,11 @@
package constants
const (
IsSHOW = 1
NotShow = 2
)
const (
Enable = 1
Disable = 2
)

View File

@ -13,6 +13,7 @@ var (
AuthNotFound = &BusinessErr{code: 408, message: "身份验证失败"}
KeyNotFound = &BusinessErr{code: 409, message: "身份验证失败"}
SysNotFound = &BusinessErr{code: 410, message: "未找到系统信息"}
SysCodeNotFound = &BusinessErr{code: 411, message: "未找到系统编码"}
InvalidParam = &BusinessErr{code: InvalidParamCode, message: "无效参数"}
)

View File

@ -12,17 +12,21 @@ const TableNameAiTask = "ai_task"
// AiTask mapped from table <ai_task>
type AiTask struct {
TaskID int32 `gorm:"column:task_id;primaryKey" json:"task_id"`
SysID int32 `gorm:"column:sys_id;not null" json:"sys_id"`
Name string `gorm:"column:name;not null" json:"name"`
Index string `gorm:"column:index;not null" json:"index"`
Desc string `gorm:"column:desc;not null" json:"desc"`
Type int32 `gorm:"column:type;not null;comment:类型1api,2:知识库" json:"type"` // 类型1api,2:知识库
Config string `gorm:"column:config" json:"config"`
CreateAt time.Time `gorm:"column:create_at;default:CURRENT_TIMESTAMP" json:"create_at"`
UpdateAt time.Time `gorm:"column:update_at;default:CURRENT_TIMESTAMP" json:"update_at"`
Status int32 `gorm:"column:status;not null;default:1" json:"status"`
DeleteAt time.Time `gorm:"column:delete_at" json:"delete_at"`
TaskID int32 `gorm:"column:task_id;primaryKey;autoIncrement:true" json:"task_id"`
SysID int32 `gorm:"column:sys_id;not null" json:"sys_id"`
Name string `gorm:"column:name;not null" json:"name"`
Index string `gorm:"column:index;not null" json:"index"`
Desc string `gorm:"column:desc;not null" json:"desc"`
UseCase string `gorm:"column:use_case;not null;comment:适用场景" json:"use_case"` // 适用场景
TempPrompt string `gorm:"column:temp_prompt;not null;comment:提示词模板" json:"temp_prompt"` // 提示词模板
Type int32 `gorm:"column:type;not null;default:1;comment:类型1api,2:知识库" json:"type"` // 类型1api,2:知识库
Config string `gorm:"column:config" json:"config"`
TagType int32 `gorm:"column:tag_type;comment:标签类型1.AI日常 2.AI查询 3.AI执行" json:"tag_type"` // 标签类型1.AI日常 2.AI查询 3.AI执行
CreateAt time.Time `gorm:"column:create_at;default:CURRENT_TIMESTAMP" json:"create_at"`
UpdatedAt time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP" json:"updated_at"`
IsShow int32 `gorm:"column:is_show;not null;default:1;comment:是否展示1为展示2为不展示" json:"is_show"` // 是否展示1为展示2为不展示
Status int32 `gorm:"column:status;not null;default:1" json:"status"`
DeleteAt time.Time `gorm:"column:delete_at" json:"delete_at"`
}
// TableName AiTask's table name

View File

@ -2,7 +2,6 @@ package entitys
import (
"encoding/json"
"github.com/gofiber/websocket/v2"
)
@ -68,6 +67,13 @@ func ResLoading(ch chan Response, index string, content string) {
Type: ResponseLoading,
}
}
func ResError(ch chan Response, index string, content string) {
ch <- Response{
Index: index,
Content: content,
Type: ResponseErr,
}
}
type ResponseData struct {
Done bool

138
internal/gateway/client.go Normal file
View File

@ -0,0 +1,138 @@
package gateway
import (
errors "ai_scheduler/internal/data/error"
"ai_scheduler/internal/data/model"
"encoding/hex"
"fmt"
"github.com/gofiber/websocket/v2"
"math/rand"
"time"
)
var (
ErrConnClosed = errors.SysErr("连接不存在或已关闭")
)
type Client struct {
id string // 客户端唯一ID
conn *websocket.Conn // WebSocket 连接
session string // 会话ID
key string // 应用密钥
auth string // 用户凭证token
codes []string // 用户权限code
sysInfo *model.AiSy // 系统信息
tasks []model.AiTask // 任务列表
sysCode string // 系统编码
}
func NewClient(conn *websocket.Conn) *Client {
return &Client{
id: generateClientID(),
conn: conn,
}
}
// GetID 获取客户端的唯一ID
func (c *Client) GetID() string {
return c.id
}
// GetConn 获取客户端的 WebSocket 连接
func (c *Client) GetConn() *websocket.Conn {
return c.conn
}
// GetSession 获取会话ID
func (c *Client) GetSession() string {
return c.session
}
// GetKey 获取应用密钥
func (c *Client) GetKey() string {
return c.key
}
// GetAuth 获取用户凭证token
func (c *Client) GetAuth() string {
return c.auth
}
// GetCodes 获取用户权限code
func (c *Client) GetCodes() []string {
return c.codes
}
// GetSysCode 获取系统编码
func (c *Client) GetSysCode() string {
return c.sysCode
}
// GetSysInfo 获取系统信息
func (c *Client) GetSysInfo() *model.AiSy {
return c.sysInfo
}
// SetSysInfo 设置系统信息
func (c *Client) SetSysInfo(sysInfo *model.AiSy) {
c.sysInfo = sysInfo
}
// GetTasks 获取任务列表
func (c *Client) GetTasks() []model.AiTask {
return c.tasks
}
// SetTasks 设置任务列表
func (c *Client) SetTasks(tasks []model.AiTask) {
c.tasks = tasks
}
// 设置用户权限code
func (c *Client) SetCodes(codes []string) {
c.codes = codes
}
// SendFunc 发送消息到客户端
func (c *Client) SendFunc(msg []byte) error {
if c.conn != nil {
return c.conn.WriteMessage(websocket.TextMessage, msg)
}
return ErrConnClosed
}
// 生成唯一的客户端ID
func generateClientID() string {
// 使用时间戳+随机数确保唯一性
timestamp := time.Now().UnixNano()
randomBytes := make([]byte, 4)
rand.Read(randomBytes)
randomStr := hex.EncodeToString(randomBytes)
return fmt.Sprintf("%d%s", timestamp, randomStr)
}
// 连接数据验证和收集
func (c *Client) DataAuth() (err error) {
c.session = c.conn.Query("x-session", "")
if len(c.session) == 0 {
err = errors.SessionNotFound
return
}
c.auth = c.conn.Query("x-authorization", "")
if len(c.auth) == 0 {
err = errors.AuthNotFound
return
}
c.key = c.conn.Query("x-app-key", "")
if len(c.key) == 0 {
err = errors.KeyNotFound
return
}
// 系统编码
c.sysCode = c.conn.Query("x-sys-code", "")
if len(c.sysCode) == 0 {
err = errors.SysCodeNotFound
return
}
return
}

View File

@ -5,11 +5,6 @@ import (
"sync"
)
type Client struct {
ID string
SendFunc func(data []byte) error
}
type Gateway struct {
mu sync.RWMutex
clients map[string]*Client // clientID -> Client
@ -26,7 +21,7 @@ func NewGateway() *Gateway {
func (g *Gateway) AddClient(c *Client) {
g.mu.Lock()
defer g.mu.Unlock()
g.clients[c.ID] = c
g.clients[c.GetID()] = c
}
func (g *Gateway) RemoveClient(clientID string) {

View File

@ -2,16 +2,13 @@ package services
import (
"ai_scheduler/internal/biz"
"ai_scheduler/internal/config"
"ai_scheduler/internal/data/constants"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/gateway"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"math/rand"
"sync"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
@ -23,6 +20,7 @@ type ChatService struct {
Gw *gateway.Gateway
mu sync.Mutex
ChatHis *biz.ChatHistoryBiz
cfg *config.Config
}
// NewChatHandler 创建聊天处理器
@ -30,11 +28,13 @@ func NewChatService(
routerService *biz.AiRouterBiz,
chatHis *biz.ChatHistoryBiz,
gw *gateway.Gateway,
cfg *config.Config,
) *ChatService {
return &ChatService{
routerBiz: routerService,
Gw: gw,
ChatHis: chatHis,
cfg: cfg,
}
}
@ -60,36 +60,52 @@ func (h *ChatService) ChatFail(c *websocket.Conn, content string) {
_ = c.Close()
}
func generateClientID() string {
// 使用时间戳+随机数确保唯一性
timestamp := time.Now().UnixNano()
randomBytes := make([]byte, 4)
rand.Read(randomBytes)
randomStr := hex.EncodeToString(randomBytes)
return fmt.Sprintf("%d%s", timestamp, randomStr)
}
// Chat 处理WebSocket聊天连接
// 这是WebSocket处理的主入口函数
func (h *ChatService) Chat(c *websocket.Conn) {
// 创建新的客户端实例
h.mu.Lock()
clientID := generateClientID()
client := gateway.NewClient(c)
h.mu.Unlock()
client := &gateway.Client{
ID: clientID,
SendFunc: func(data []byte) error {
return c.WriteMessage(websocket.TextMessage, data)
},
}
// 将客户端添加到网关管理
h.Gw.AddClient(client)
log.Println("client connected:", clientID)
log.Println("client connected:", client.GetID())
log.Println("客户端已连接")
// 绑定会话ID
uid := c.Query("x-session")
if uid != "" {
if err := h.Gw.BindUid(client.GetID(), uid); err != nil {
log.Println("绑定UID错误:", err)
}
log.Printf("bind %s -> uid:%s\n", client.GetID(), uid)
}
// 验证并收集连接数据,后续对话中会使用
if err := client.DataAuth(); err != nil {
log.Println("数据验证错误:", err)
h.ChatFail(c, err.Error())
return
}
// 确保在函数返回时移除客户端并关闭连接
defer func() {
h.Gw.RemoveClient(client.GetID())
_ = c.Close()
log.Println("client disconnected:", client.GetID())
}()
// 循环读取客户端消息
for {
// 读取消息
messageType, message, err := c.ReadMessage()
if err != nil {
log.Println("读取错误:", err)
break
}
// 处理消息
msg, chatType := h.handleMessageToString(c, messageType, message)
if chatType == constants.ConnStatusClosed {
break
@ -99,39 +115,31 @@ func (h *ChatService) Chat(c *websocket.Conn) {
}
log.Printf("收到消息: %s", string(msg))
// 解析请求
var req entitys.ChatSockRequest
if err := json.Unmarshal(msg, &req); err != nil {
if err = json.Unmarshal(msg, &req); err != nil {
log.Println("JSON parse error:", err)
continue
}
//简单协议bind:<uid>
// if c.Headers("Sec-Websocket-Protocol") == "bind" && req.SessionID != "" {
// uid := c.Query("x-session")
// _ = h.Gw.BindUid(clientID, req.SessionID)
// log.Printf("bind %s -> uid:%s\n", clientID, uid)
// }
uid := c.Query("x-session")
if uid != "" {
_ = h.Gw.BindUid(clientID, uid)
log.Printf("bind %s -> uid:%s\n", clientID, uid)
}
err = h.routerBiz.RouteWithSocket(c, &req)
// 路由处理请求
err = h.routerBiz.RouteWithSocket(client, &req)
if err != nil {
log.Println("处理失败:", err)
entitys.MsgSend(c, entitys.Response{
Content: err.Error(),
Type: entitys.ResponseText,
})
}
}
h.Gw.RemoveClient(clientID)
_ = c.Close()
log.Println("client disconnected:", clientID)
}
// handleMessageToString 处理不同类型的WebSocket消息
// 参数:
// - c: WebSocket连接
// - msgType: 消息类型
// - msg: 消息内容
//
// 返回:
// - text: 处理后的文本内容
// - chatType: 连接状态
func (h *ChatService) handleMessageToString(c *websocket.Conn, msgType int, msg any) (text []byte, chatType constants.ConnStatus) {
switch msgType {
case websocket.TextMessage:

View File

@ -3,7 +3,6 @@ package services
import (
"ai_scheduler/internal/biz"
"ai_scheduler/internal/entitys"
"github.com/gofiber/fiber/v2"
)
@ -25,7 +24,15 @@ func (s *TaskService) Tasks(c *fiber.Ctx) error {
return err
}
result, err := s.taskBiz.TaskList(c.Context(), req)
auth := ""
if auths := c.GetReqHeaders()["Authorization"]; len(auths) > 0 {
auth = auths[0]
}
if auth == "" {
return fiber.ErrUnauthorized
}
result, err := s.taskBiz.TaskList(c.Context(), req, auth)
if err != nil {
return err

View File

@ -70,10 +70,28 @@ func NewManager(config *config.Config, llm *utils_ollama.Client) *Manager {
m.tools[knowledgeTool.Name()] = knowledgeTool
}
if config.Tools.Knowledge.Enabled {
knowledgeTool := NewKnowledgeBaseTool(config.Tools.Knowledge)
m.tools[knowledgeTool.Name()] = knowledgeTool
//注册直连天下售后订单详情工具
if config.Tools.ZltxOrderAfterSaleDetail.Enabled {
zltxOrderAfterSaleDetailTool := NewZltxOrderAfterSaleDetailTool(config.Tools.ZltxOrderAfterSaleDetail)
m.tools[zltxOrderAfterSaleDetailTool.Name()] = zltxOrderAfterSaleDetailTool
}
//注册直连天下售后订单预检工具
if config.Tools.ZltxOrderAfterSalePreCheck.Enabled {
zltxOrderAfterSalePreCheckTool := NewZltxOrderAfterSalePreCheckTool(config.Tools.ZltxOrderAfterSalePreCheck)
m.tools[zltxOrderAfterSalePreCheckTool.Name()] = zltxOrderAfterSalePreCheckTool
}
// 注册直连天下上游售后订单工具
if config.Tools.ZltxOrderAfterSaleSupplier.Enabled {
zltxOrderAfterSaleSupplierTool := NewZltxOrderAfterSaleSupplierTool(config.Tools.ZltxOrderAfterSaleSupplier)
m.tools[zltxOrderAfterSaleSupplierTool.Name()] = zltxOrderAfterSaleSupplierTool
}
// 注册直连天下下游售后订单工具
if config.Tools.ZltxOrderAfterSaleReseller.Enabled {
zltxOrderAfterSaleResellerTool := NewZltxOrderAfterSaleResellerTool(config.Tools.ZltxOrderAfterSaleReseller)
m.tools[zltxOrderAfterSaleResellerTool.Name()] = zltxOrderAfterSaleResellerTool
}
// 普通对话
chat := NewNormalChatTool(m.llm, config)
m.tools[chat.Name()] = chat

View File

@ -0,0 +1,119 @@
package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/pkg/l_request"
"context"
"encoding/json"
"fmt"
)
type ZltxOrderAfterSaleDetailTool struct {
config config.ToolConfig
}
// NewZltxOrderAfterSaleDetailTool 创建售后订单详情工具
func NewZltxOrderAfterSaleDetailTool(config config.ToolConfig) *ZltxOrderAfterSaleDetailTool {
return &ZltxOrderAfterSaleDetailTool{config: config}
}
// Definition 返回工具定义
func (this *ZltxOrderAfterSaleDetailTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: this.Name(),
Description: this.Description(),
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"direct_order_number": map[string]interface{}{
"type": "string",
"description": "售后订单号",
},
},
"required": []string{"direct_order_number"},
},
},
}
}
type ZltxOrderAfterSaleDetailRequest struct {
DirectOrderNumber string `json:"direct_order_number"`
}
type ZltxOrderAfterSaleDetailResponse struct {
Code int `json:"code"`
Data struct {
AfterSaleOrder ZltxOrderAfterSaleDetailData `json:"afterSaleOrder"`
} `json:"data"`
Error string `json:"error"`
}
type ZltxOrderAfterSaleDetailData struct {
SerialNumber string `json:"serialNumber"`
PlatformName string `json:"platformName"`
SignCompany int `json:"signCompany"`
PlatformProductName string `json:"platformProductName"`
PlatformPrice float64 `json:"platformPrice"`
TerminalAccount string `json:"terminalAccount"`
Status int `json:"status"`
PlatformProductID int `json:"platformProductId"`
PlatformID int `json:"platformId"`
SignCompanyName string `json:"signCompanyName"`
ExecuteTime int `json:"executeTime"`
}
func (this *ZltxOrderAfterSaleDetailTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
var req ZltxOrderAfterSaleDetailRequest
if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
return err
}
if req.DirectOrderNumber == "" {
return fmt.Errorf("direct_order_number is required")
}
return this.getZltxOrderAfterSaleDetail(ctx, requireData, req.DirectOrderNumber)
}
func (this *ZltxOrderAfterSaleDetailTool) getZltxOrderAfterSaleDetail(ctx context.Context, requireData *entitys.RequireData, directOrderNumber string) error {
//查询订单详情
url := fmt.Sprintf("%s%s", this.config.BaseURL, directOrderNumber)
req := l_request.Request{
Url: url,
Headers: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
},
Method: "GET",
}
res, err := req.Send()
var resData ZltxOrderAfterSaleDetailResponse
if err != nil {
return err
}
if err := json.Unmarshal(res.Content, &resData); err != nil {
return err
}
if resData.Code != 200 {
return fmt.Errorf("为获取到数据,请检查权限: %s", string(res.Content))
}
jsonByte, err := json.Marshal(resData)
if err != nil {
return err
}
entitys.ResJson(requireData.Ch, this.Name(), string(jsonByte))
return nil
}
func (this *ZltxOrderAfterSaleDetailTool) GetConfig() config.ToolConfig {
return this.config
}
// Name 工具名称
func (this *ZltxOrderAfterSaleDetailTool) Name() string {
return "zltx_order_after_sale_detail"
}
func (this *ZltxOrderAfterSaleDetailTool) Description() string {
return "查询直连天下上游售后订单详情"
}

View File

@ -0,0 +1,125 @@
package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"ai_scheduler/internal/pkg/l_request"
"context"
"encoding/json"
"fmt"
)
type ZltxOrderAfterSalePreCheckTool struct {
config config.ToolConfig
}
// NewZltxOrderAfterSalePreCheckTool 创建售后订单预检工具
func NewZltxOrderAfterSalePreCheckTool(config config.ToolConfig) *ZltxOrderAfterSalePreCheckTool {
return &ZltxOrderAfterSalePreCheckTool{config: config}
}
// Name 返回工具名称
func (t *ZltxOrderAfterSalePreCheckTool) Name() string {
return "zltxOrderAfterSalePreCheck"
}
func (t *ZltxOrderAfterSalePreCheckTool) Description() string {
return "直连天下售后订单预检工具"
}
func (t *ZltxOrderAfterSalePreCheckTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: t.Name(),
Description: t.Description(),
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"orderType": map[string]interface{}{
"type": "integer",
"description": "售后订单类型",
},
"orderNumber": map[string]interface{}{
"type": "string",
"description": "售后订单号",
},
},
"required": []string{"orderType", "orderNumber"},
},
},
}
}
type ZltxOrderAfterSalePreCheckRequest struct {
OrderType int `json:"orderType"`
OrderNumber string `json:"orderNumber"`
}
type ZltxOrderAfterSalePreCheckResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
CheckResult bool `json:"checkResult"`
} `json:"data"`
}
type CheckResult struct {
OrderType int `json:"orderType"`
OrderNumber string `json:"orderNumber"`
OrderAmount float64 `json:"orderAmount"`
OrderPrice float64 `json:"orderPrice"`
SignCompany int `json:"signCompany"`
OrderQuantity int `json:"orderQuantity"`
ResellerID int `json:"resellerId"`
ResellerName string `json:"resellerName"`
OurProductID int `json:"ourProductId"`
OurProductTitle string `json:"ourProductTitle"`
Account []string `json:"account"`
Platforms struct {
Num4 string `json:"4"`
} `json:"platforms"`
}
func (t *ZltxOrderAfterSalePreCheckTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
var req ZltxOrderAfterSalePreCheckRequest
if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
return err
}
if req.OrderType == 0 || req.OrderNumber == "" {
return fmt.Errorf("orderType and orderNumber are required")
}
return t.checkZltxOrderAfterSalePreCheck(req.OrderType, req.OrderNumber, requireData)
}
func (t *ZltxOrderAfterSalePreCheckTool) checkZltxOrderAfterSalePreCheck(orderType int, orderNumber string, requireData *entitys.RequireData) error {
req := l_request.Request{
Url: t.config.BaseURL,
Headers: map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
},
Method: "POST",
Data: map[string]string{
"orderType": fmt.Sprintf("%d", orderType),
"orderNumber": orderNumber,
},
}
res, err := req.Send()
if err != nil {
return err
}
// 解析响应
var resp ZltxOrderAfterSalePreCheckResponse
if err := json.Unmarshal(res.Content, &resp); err != nil {
return err
}
if resp.Code != 0 {
return fmt.Errorf("check failed: %s", resp.Msg)
}
jsonByte, err := json.Marshal(resp)
if err != nil {
return err
}
entitys.ResJson(requireData.Ch, t.Name(), string(jsonByte))
return nil
}

View File

@ -0,0 +1,190 @@
package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"context"
"encoding/json"
"fmt"
)
type ZltxOrderAfterSaleResellerTool struct {
config config.ToolConfig
}
// NewZltxOrderAfterSaleResellerTool 创建售后订单预检工具
func NewZltxOrderAfterSaleResellerTool(config config.ToolConfig) *ZltxOrderAfterSaleResellerTool {
return &ZltxOrderAfterSaleResellerTool{config: config}
}
// Name 返回工具名称
func (t *ZltxOrderAfterSaleResellerTool) Name() string {
return "zltxOrderAfterSaleReseller"
}
func (t *ZltxOrderAfterSaleResellerTool) Description() string {
return "直连天下下游分销商普充订单售后工具"
}
func (t *ZltxOrderAfterSaleResellerTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: t.Name(),
Description: t.Description(),
Parameters: map[string]interface{}{
// "type": "object",
// "properties": map[string]interface{}{
// "orderType": map[string]interface{}{
// "type": "integer",
// "description": "售后订单类型",
// },
// "orderNumber": map[string]interface{}{
// "type": "string",
// "description": "售后订单号",
// },
// },
// "required": []string{"orderType", "orderNumber"},
},
},
}
}
type ZltxOrderAfterSaleResellerRequest struct {
OrderNumber []string `json:"orderNumber"` // 订单号
Account string `json:"account"` // 充值账号
OrderTimeStart string `json:"orderTimeStart"` // 订单执行开始时间
OrderTimeEnd string `json:"orderTimeEnd"` // 订单执行结束时间
AfterType int `json:"afterType"` // 处理方式 1.退款 2.扣款
AfterSalesPrice string `json:"afterSalesPrice"` // 售后金额
AfterSalesReason string `json:"afterSalesReason"` // 售后原因
ResponsibleType int `json:"responsibleType"` // 费用承担者 1.供应商 2.商务 3.公司 4.无
ResponsiblePerson string `json:"responsiblePerson"` // 费用承担供应商
}
type ZltxOrderAfterSaleResellerResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data []ZltxOrderAfterSaleResellerData `json:"data"`
}
type ZltxOrderAfterSaleResellerData struct {
OrderType int `json:"orderType"`
OrderNumber string `json:"orderNumber"`
OrderAmount float64 `json:"orderAmount"`
OrderPrice float64 `json:"orderPrice"`
SignCompany int `json:"signCompany"`
OrderQuantity int `json:"orderQuantity"`
ResellerID int `json:"resellerId"`
ResellerName string `json:"resellerName"`
OurProductID int `json:"ourProductId"`
OurProductTitle string `json:"ourProductTitle"`
Account []string `json:"account"`
Platforms map[int]string `json:"platforms"`
AfterType int `json:"afterType"` // 处理方式 1.退款 2.扣款
Remark string `json:"remark"` // 售后原因
AfterAmount float64 `json:"afterAmount"` // 售后金额
ResponsibleType int `json:"responsibleType"` // 费用承担者 1.供应商 2.商务 3.公司 4.无
ResponsiblePerson string `json:"responsiblePerson"` // 费用承担供应商
IsExistsAfterSale bool `json:"isExistsAfterSale"` // 是否已存在售后
}
func (t *ZltxOrderAfterSaleResellerTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
var req ZltxOrderAfterSaleResellerRequest
if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
return err
}
if len(req.OrderNumber) == 0 && (req.Account == "" || req.OrderTimeStart == "") {
return fmt.Errorf("订单号 和 充值账号&订单执行时间 不能同时为空")
}
entitys.ResLog(requireData.Ch, t.Name(), "正在拉取售后订单信息")
return t.checkZltxOrderAfterSaleReseller(req, requireData)
}
func (t *ZltxOrderAfterSaleResellerTool) checkZltxOrderAfterSaleReseller(req ZltxOrderAfterSaleResellerRequest, requireData *entitys.RequireData) error {
// req := l_request.Request{
// Url: t.config.BaseURL,
// Headers: map[string]string{
// "Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
// },
// Method: "POST",
// Data: map[string]string{
// // "orderType": fmt.Sprintf("%d", orderType),
// "orderNumber": orderNumber,
// },
// }
// res, err := req.Send()
// if err != nil {
// return err
// }
// // 解析响应
// var resp ZltxOrderAfterSaleResellerResponse
// if err := json.Unmarshal(res.Content, &resp); err != nil {
// return err
// }
// if resp.Code != 0 {
// return fmt.Errorf("check failed: %s", resp.Msg)
// }
// === mock start ===
resp := ZltxOrderAfterSaleResellerResponse{
Code: 0,
Msg: "success",
Data: []ZltxOrderAfterSaleResellerData{
{
OrderType: 1,
OrderNumber: "846784115378364417",
OrderAmount: 0.1,
OrderPrice: 0.1,
SignCompany: 1,
OrderQuantity: 1,
ResellerID: 23329,
ResellerName: "分销商23329",
OurProductID: 106,
OurProductTitle: "爱奇艺黄金会员周卡",
Account: []string{"15516353308"},
Platforms: map[int]string{4: "爱奇艺"},
AfterType: 1,
Remark: "测试售后",
AfterAmount: 50,
ResponsibleType: 1,
IsExistsAfterSale: false,
},
{
OrderType: 101,
OrderNumber: "846052057729867777",
OrderAmount: 23,
OrderPrice: 23,
SignCompany: 1,
OrderQuantity: 1,
ResellerID: 25629,
ResellerName: "二期财务分销商简称",
OurProductID: 104,
OurProductTitle: "优酷年卡",
Account: []string{"18380416326"},
Platforms: map[int]string{1: "爱瓦力"},
AfterType: 2,
Remark: "测试售后2",
AfterAmount: 30,
ResponsibleType: 2,
IsExistsAfterSale: false,
},
},
}
if len(req.OrderNumber) == 1 {
resp.Data = resp.Data[:1]
}
// === mock end ===
jsonByte, err := json.Marshal(resp)
if err != nil {
return err
}
entitys.ResLog(requireData.Ch, t.Name(), "售后订单信息拉取完成")
entitys.ResJson(requireData.Ch, t.Name(), string(jsonByte))
return nil
}

View File

@ -0,0 +1,187 @@
package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"context"
"encoding/json"
"fmt"
)
type ZltxOrderAfterSaleResellerBatchTool struct {
config config.ToolConfig
}
// NewZltxOrderAfterSaleResellerBatchTool 创建售后订单预检工具
func NewZltxOrderAfterSaleResellerBatchTool(config config.ToolConfig) *ZltxOrderAfterSaleResellerBatchTool {
return &ZltxOrderAfterSaleResellerBatchTool{config: config}
}
// Name 返回工具名称
func (t *ZltxOrderAfterSaleResellerBatchTool) Name() string {
return "zltxOrderAfterSaleResellerBatch"
}
func (t *ZltxOrderAfterSaleResellerBatchTool) Description() string {
return "直连天下下游分销商批充订单售后工具"
}
func (t *ZltxOrderAfterSaleResellerBatchTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: t.Name(),
Description: t.Description(),
Parameters: map[string]interface{}{
// "type": "object",
// "properties": map[string]interface{}{
// "orderType": map[string]interface{}{
// "type": "integer",
// "description": "售后订单类型",
// },
// "orderNumber": map[string]interface{}{
// "type": "string",
// "description": "售后订单号",
// },
// },
// "required": []string{"orderType", "orderNumber"},
},
},
}
}
type ZltxOrderAfterSaleResellerBatchRequest struct {
OrderNumber []string `json:"orderNumber"` // 订单号
AfterType int `json:"afterType"` // 处理方式 1.退款 2.扣款
AfterSalesPrice string `json:"afterSalesPrice"` // 售后金额
AfterSalesReason string `json:"afterSalesReason"` // 售后原因
ResponsibleType int `json:"responsibleType"` // 费用承担者 1.供应商 2.商务 3.公司 4.无
ResponsiblePerson string `json:"responsiblePerson"` // 费用承担供应商
}
type ZltxOrderAfterSaleResellerBatchResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data []ZltxOrderAfterSaleResellerBatchData `json:"data"`
}
type ZltxOrderAfterSaleResellerBatchData struct {
OrderType int `json:"orderType"`
OrderNumber string `json:"orderNumber"`
OrderAmount float64 `json:"orderAmount"`
OrderPrice float64 `json:"orderPrice"`
SignCompany int `json:"signCompany"`
OrderQuantity int `json:"orderQuantity"`
ResellerID int `json:"resellerId"`
ResellerName string `json:"resellerName"`
OurProductID int `json:"ourProductId"`
OurProductTitle string `json:"ourProductTitle"`
Account []string `json:"account"`
Platforms map[int]string `json:"platforms"`
AfterType int `json:"afterType"` // 处理方式 1.退款 2.扣款
Remark string `json:"remark"` // 售后原因
AfterAmount float64 `json:"afterAmount"` // 售后金额
ResponsibleType int `json:"responsibleType"` // 费用承担者 1.供应商 2.商务 3.公司 4.无
ResponsiblePerson string `json:"responsiblePerson"` // 费用承担供应商
IsExistsAfterSale bool `json:"isExistsAfterSale"` // 是否已存在售后
}
func (t *ZltxOrderAfterSaleResellerBatchTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
var req ZltxOrderAfterSaleResellerBatchRequest
if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
return err
}
if len(req.OrderNumber) == 0 {
return fmt.Errorf("批充订单号不能为空")
}
entitys.ResLog(requireData.Ch, t.Name(), "正在拉取售后订单信息")
return t.checkZltxOrderAfterSaleResellerBatch(req, requireData)
}
func (t *ZltxOrderAfterSaleResellerBatchTool) checkZltxOrderAfterSaleResellerBatch(req ZltxOrderAfterSaleResellerBatchRequest, requireData *entitys.RequireData) error {
// req := l_request.Request{
// Url: t.config.BaseURL,
// Headers: map[string]string{
// "Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
// },
// Method: "POST",
// Data: map[string]string{
// // "orderType": fmt.Sprintf("%d", orderType),
// "orderNumber": orderNumber,
// },
// }
// res, err := req.Send()
// if err != nil {
// return err
// }
// // 解析响应
// var resp ZltxOrderAfterSaleResellerBatchResponse
// if err := json.Unmarshal(res.Content, &resp); err != nil {
// return err
// }
// if resp.Code != 0 {
// return fmt.Errorf("check failed: %s", resp.Msg)
// }
// === mock start ===
resp := ZltxOrderAfterSaleResellerBatchResponse{
Code: 0,
Msg: "success",
Data: []ZltxOrderAfterSaleResellerBatchData{
{
OrderType: 1,
OrderNumber: "846784115378364417",
OrderAmount: 0.1,
OrderPrice: 0.1,
SignCompany: 1,
OrderQuantity: 1,
ResellerID: 23329,
ResellerName: "分销商23329",
OurProductID: 106,
OurProductTitle: "爱奇艺黄金会员周卡",
Account: []string{"15516353308"},
Platforms: map[int]string{4: "爱奇艺"},
AfterType: 1,
Remark: "测试售后",
AfterAmount: 50,
ResponsibleType: 1,
IsExistsAfterSale: false,
},
{
OrderType: 101,
OrderNumber: "846052057729867777",
OrderAmount: 23,
OrderPrice: 23,
SignCompany: 1,
OrderQuantity: 1,
ResellerID: 25629,
ResellerName: "二期财务分销商简称",
OurProductID: 104,
OurProductTitle: "优酷年卡",
Account: []string{"18380416326"},
Platforms: map[int]string{1: "爱瓦力"},
AfterType: 2,
Remark: "测试售后2",
AfterAmount: 30,
ResponsibleType: 2,
IsExistsAfterSale: false,
},
},
}
if len(req.OrderNumber) == 1 {
resp.Data = resp.Data[:1]
}
// === mock end ===
jsonByte, err := json.Marshal(resp)
if err != nil {
return err
}
entitys.ResLog(requireData.Ch, t.Name(), "售后订单信息拉取完成")
entitys.ResJson(requireData.Ch, t.Name(), string(jsonByte))
return nil
}

View File

@ -0,0 +1,181 @@
package tools
import (
"ai_scheduler/internal/config"
"ai_scheduler/internal/entitys"
"context"
"encoding/json"
"fmt"
)
type ZltxOrderAfterSaleSupplierTool struct {
config config.ToolConfig
}
// NewZltxOrderAfterSaleSupplierTool 创建售后订单预检工具
func NewZltxOrderAfterSaleSupplierTool(config config.ToolConfig) *ZltxOrderAfterSaleSupplierTool {
return &ZltxOrderAfterSaleSupplierTool{config: config}
}
// Name 返回工具名称
func (t *ZltxOrderAfterSaleSupplierTool) Name() string {
return "zltxOrderAfterSaleSupplier"
}
func (t *ZltxOrderAfterSaleSupplierTool) Description() string {
return "直连天下上游供应商售后工具"
}
func (t *ZltxOrderAfterSaleSupplierTool) Definition() entitys.ToolDefinition {
return entitys.ToolDefinition{
Type: "function",
Function: entitys.FunctionDef{
Name: t.Name(),
Description: t.Description(),
Parameters: map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"orderType": map[string]interface{}{
"type": "integer",
"description": "售后订单类型",
},
"orderNumber": map[string]interface{}{
"type": "string",
"description": "售后订单号",
},
},
// "required": []string{"orderType", "orderNumber"},
},
},
}
}
type ZltxOrderAfterSaleSupplierRequest struct {
SerialNumber []string `json:"serialNumber"` // 流水号
Account string `json:"account"` // 充值账号
OrderTimeStart string `json:"orderTimeStart"` // 订单执行开始时间
OrderTimeEnd string `json:"orderTimeEnd"` // 订单执行结束时间
AfterSalesReason string `json:"afterSalesReason"` // 售后原因
AfterSalesPrice string `json:"afterSalesPrice"` // 售后金额
AfterType int `json:"afterType"` // 售后类型 1.加款 2.扣款
}
type ZltxOrderAfterSaleSupplierResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data []ZltxOrderAfterSaleSupplierData `json:"data"`
}
type ZltxOrderAfterSaleSupplierData struct {
SerialNumber string `json:"serialNumber"` // 流水号
PlatformName string `json:"platformName"` // 供应商名称
SignCompany int `json:"signCompany"` // 签约主体
PlatformProductName string `json:"platformProductName"` // 商品名称
PlatformPrice float64 `json:"platformPrice"` // 上游价格
TerminalAccount string `json:"terminalAccount"` // 充值账号
Status int `json:"status"` // 充值状态
PlatformProductID int `json:"platformProductId"` // 上有商品id
PlatformID int `json:"platformId"` // 上游平台id
SignCompanyName string `json:"signCompanyName"` // 签约主体名称
ExecuteTime int `json:"executeTime"` // 订单执行时间
Reason string `json:"reason"` // 售后原因
SalePrice float64 `json:"salePrice"` // 售后金额
SaleType int `json:"saleType"` // 处理方式 1.加款 2.扣款
IsExistsAfterSale bool `json:"isExistsAfterSale"` // 是否已存在售后
}
func (t *ZltxOrderAfterSaleSupplierTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
var req ZltxOrderAfterSaleSupplierRequest
if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
return err
}
if len(req.SerialNumber) == 0 && (req.Account == "" || req.OrderTimeStart == "") {
return fmt.Errorf("充值流水号 和 充值账号&订单执行时间 不能同时为空")
}
entitys.ResLog(requireData.Ch, t.Name(), "正在拉取售后订单信息")
return t.checkZltxOrderAfterSaleSupplier(req, requireData)
}
func (t *ZltxOrderAfterSaleSupplierTool) checkZltxOrderAfterSaleSupplier(req ZltxOrderAfterSaleSupplierRequest, requireData *entitys.RequireData) error {
// req := l_request.Request{
// Url: t.config.BaseURL,
// Headers: map[string]string{
// "Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
// },
// Method: "POST",
// Data: map[string]string{
// // "orderType": fmt.Sprintf("%d", orderType),
// "orderNumber": orderNumber,
// },
// }
// res, err := req.Send()
// if err != nil {
// return err
// }
// // 解析响应
// var resp ZltxOrderAfterSaleSupplierResponse
// if err := json.Unmarshal(res.Content, &resp); err != nil {
// return err
// }
// if resp.Code != 0 {
// return fmt.Errorf("check failed: %s", resp.Msg)
// }
// === mock start ===
resp := ZltxOrderAfterSaleSupplierResponse{
Code: 0,
Msg: "success",
Data: []ZltxOrderAfterSaleSupplierData{
{
SerialNumber: "847465394004430849",
PlatformName: "爱奇艺",
SignCompany: 1,
PlatformProductName: "爱奇艺官方周卡",
PlatformPrice: 6,
TerminalAccount: "15516353308",
Status: 1,
PlatformProductID: 2,
PlatformID: 4,
SignCompanyName: "成都蓝色兄弟网络科技有限公司",
ExecuteTime: 1763961931,
Reason: "测试售后",
SalePrice: 50,
SaleType: 1,
IsExistsAfterSale: false,
},
{
SerialNumber: "843493448012140545",
PlatformName: "卓望别名1",
SignCompany: 1,
PlatformProductName: "卓望--别名商品1",
PlatformPrice: 897.7765,
TerminalAccount: "18380416326",
Status: -1,
PlatformProductID: 7497,
PlatformID: 15,
SignCompanyName: "成都蓝色兄弟网络科技有限公司",
ExecuteTime: 1763014914,
Reason: "测试售后2",
SalePrice: 30,
SaleType: 2,
IsExistsAfterSale: true,
},
},
}
if len(req.SerialNumber) == 1 {
resp.Data = resp.Data[:1]
}
// === mock end ===
jsonByte, err := json.Marshal(resp)
if err != nil {
return err
}
entitys.ResLog(requireData.Ch, t.Name(), "售后订单信息拉取完成")
entitys.ResJson(requireData.Ch, t.Name(), string(jsonByte))
return nil
}

View File

@ -17,6 +17,7 @@ type BotTool struct {
llm *utils_ollama.Client
sessionImpl *impl.SessionImpl
taskMap map[string]string // task_id -> session_id
// zltxOrderAfterSaleTool tools.ZltxOrderAfterSaleTool
}
// NewBotTool 创建直连天下订单详情工具