Jelajahi Sumber

fix:edit api

jimmyyem 2 bulan lalu
induk
melakukan
2551edeebc

+ 20 - 2
desc/wechat/chat_records.api

@@ -135,6 +135,16 @@ type (
 		CreatedAt *int `json:"createdAt"`
 		Inputs interface{} `json:"inputs"`
 	}
+
+	GptsDeleteSessionReq {
+		AgentId *uint64 `json:"agentId"`
+		ConversationId *string `json:"conversationId"`
+	}
+	GptsRenameSessionReq {
+		AgentId *uint64 `json:"agentId"`
+		ConversationId *string `json:"conversationId"`
+		Name *string `json:"name"`
+	}
 )
 
 @server(
@@ -146,13 +156,21 @@ service Wechat {
 	@handler gptsSubmitApiChat
 	post /gpts/chat/submit (GptChatReq)
 
-	// Create chat records information | 创建ChatRecords
+	// Get chat message list | 获取聊天历史
 	@handler gptsGetApiMessage
 	post /gpts/chat/message (GptMessageReq) returns (GptMessageResp)
 
-	// Create chat records information | 创建ChatRecords
+	// Get chat session list | 获取会话列表
 	@handler gptsGetApiSession
 	post /gpts/chat/session (GptsSessionReq) returns (GptsSessionResp)
+
+	// Create chat records information | 创建ChatRecords
+	@handler gptsDeleteApiSession
+	post /gpts/chat/session/delete (GptsDeleteSessionReq) returns (BaseMsgResp)
+
+	// Create chat records information | 创建ChatRecords
+	@handler gptsRenameApiSession
+	post /gpts/chat/session/rename (GptsRenameSessionReq) returns (BaseMsgResp)
 }
 
 @server(

+ 4 - 0
desc/wechat/user.api

@@ -162,6 +162,10 @@ service Wechat {
 	@handler getGptsUserInfo
 	post /gpts/user/info () returns (UserInfoResp)
 
+	// Update user basic information | 修改用户基本信息
+	@handler updateGptsUserInfo
+	post /gpts/user/update (UserInfo) returns (BaseDataInfo)
+
 	// Get user balance information | 获取用户余额信息
 	@handler getGptsUserBalance
 	post /gpts/user/balance () returns (UserBalanceResp)

+ 54 - 1
hook/dify/dify.go

@@ -36,6 +36,18 @@ type History struct {
 	CreatedAt      int64  `json:"created_at"`
 }
 
+type DeleteSessionResponse struct {
+	Result string `json:"result"`
+}
+
+type RenameSessionResp struct {
+	ID           string `json:"id"`
+	Name         string `json:"name"`
+	Inputs       Inputs `json:"inputs"`
+	Introduction string `json:"introduction"`
+	CreatedAt    int64  `json:"created_at"`
+}
+
 // GetSessionList 获取会话列表
 func GetSessionList(baseUrl, token, user, lastId, limit string) (*SessionResponse, error) {
 	data := &SessionResponse{}
@@ -58,6 +70,47 @@ func GetSessionList(baseUrl, token, user, lastId, limit string) (*SessionRespons
 	return data, nil
 }
 
+// DeleteSession 删除会话
+func DeleteSession(baseUrl, token, user, conversationId string) (*DeleteSessionResponse, error) {
+	data := &DeleteSessionResponse{}
+	body := make(map[string]string)
+	body["user"] = user
+	_, err := NewDifyResty(baseUrl, token).
+		R().
+		SetResult(&data).
+		SetBody(body).
+		Delete("/conversations/" + conversationId)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return data, nil
+}
+
+// RenameSession 会话重命名
+func RenameSession(baseUrl, token, user, name, conversationId string) (*DeleteSessionResponse, error) {
+	data := &DeleteSessionResponse{}
+	body := make(map[string]string)
+	body["user"] = user
+	body["name"] = name
+	resp, err := NewDifyResty(baseUrl, token).
+		R().
+		SetResult(&data).
+		SetBody(body).
+		Post("/conversations/" + conversationId + "/name")
+
+	if err != nil {
+		return nil, err
+	}
+
+	if resp.IsError() {
+		return nil, errors.New(resp.String())
+	}
+
+	return data, nil
+}
+
 // GetChatHistory 获取历史会话
 func GetChatHistory(baseUrl, token, user, conversationId, firstId, limit string) (*HistoryResponse, error) {
 	data := &HistoryResponse{}
@@ -81,7 +134,7 @@ func GetChatHistory(baseUrl, token, user, conversationId, firstId, limit string)
 	return data, nil
 }
 
-// NewResty 实例化dify实例
+// NewDifyResty 实例化dify实例
 func NewDifyResty(baseUrl, token string) *resty.Client {
 	client := resty.New()
 	client.SetRetryCount(2).

+ 45 - 0
internal/handler/User/update_gpts_user_info_handler.go

@@ -0,0 +1,45 @@
+package User
+
+import (
+	"net/http"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"github.com/zeromicro/go-zero/rest/httpx"
+
+	"wechat-api/internal/logic/User"
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+)
+
+// swagger:route post /gpts/user/update User UpdateGptsUserInfo
+//
+// Update user basic information | 修改用户基本信息
+//
+// Update user basic information | 修改用户基本信息
+//
+// Parameters:
+//  + name: body
+//    require: true
+//    in: body
+//    type: UserInfo
+//
+// Responses:
+//  200: BaseDataInfo
+
+func UpdateGptsUserInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		var req types.UserInfo
+		if err := httpx.Parse(r, &req, true); err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+			return
+		}
+		tokenStr := jwtutils.StripBearerPrefixFromToken(r.Header.Get("Authorization"))
+		l := User.NewUpdateGptsUserInfoLogic(r.Context(), svcCtx)
+		resp, err := l.UpdateGptsUserInfo(&req, tokenStr)
+		if err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+		} else {
+			httpx.OkJsonCtx(r.Context(), w, resp)
+		}
+	}
+}

+ 46 - 0
internal/handler/chatrecords/gpts_delete_api_session_handler.go

@@ -0,0 +1,46 @@
+package chatrecords
+
+import (
+	"net/http"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"github.com/zeromicro/go-zero/rest/httpx"
+
+	"wechat-api/internal/logic/chatrecords"
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+)
+
+// swagger:route post /gpts/chat/session/delete chatrecords GptsDeleteApiSession
+//
+// Create chat records information | 创建ChatRecords
+//
+// Create chat records information | 创建ChatRecords
+//
+// Parameters:
+//  + name: body
+//    require: true
+//    in: body
+//    type: GptsDeleteSessionReq
+//
+// Responses:
+//  200: BaseMsgResp
+
+func GptsDeleteApiSessionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		var req types.GptsDeleteSessionReq
+		if err := httpx.Parse(r, &req, true); err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+			return
+		}
+
+		tokenStr := jwtutils.StripBearerPrefixFromToken(r.Header.Get("Authorization"))
+		l := chatrecords.NewGptsDeleteApiSessionLogic(r.Context(), svcCtx)
+		resp, err := l.GptsDeleteApiSession(&req, tokenStr)
+		if err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+		} else {
+			httpx.OkJsonCtx(r.Context(), w, resp)
+		}
+	}
+}

+ 46 - 0
internal/handler/chatrecords/gpts_rename_api_session_handler.go

@@ -0,0 +1,46 @@
+package chatrecords
+
+import (
+	"net/http"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"github.com/zeromicro/go-zero/rest/httpx"
+
+	"wechat-api/internal/logic/chatrecords"
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+)
+
+// swagger:route post /gpts/chat/session/rename chatrecords GptsRenameApiSession
+//
+// Create chat records information | 创建ChatRecords
+//
+// Create chat records information | 创建ChatRecords
+//
+// Parameters:
+//  + name: body
+//    require: true
+//    in: body
+//    type: GptsRenameSessionReq
+//
+// Responses:
+//  200: BaseMsgResp
+
+func GptsRenameApiSessionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		var req types.GptsRenameSessionReq
+		if err := httpx.Parse(r, &req, true); err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+			return
+		}
+
+		tokenStr := jwtutils.StripBearerPrefixFromToken(r.Header.Get("Authorization"))
+		l := chatrecords.NewGptsRenameApiSessionLogic(r.Context(), svcCtx)
+		resp, err := l.GptsRenameApiSession(&req, tokenStr)
+		if err != nil {
+			httpx.ErrorCtx(r.Context(), w, err)
+		} else {
+			httpx.OkJsonCtx(r.Context(), w, resp)
+		}
+	}
+}

+ 15 - 0
internal/handler/routes.go

@@ -702,6 +702,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
 			},
 			{
 				Method:  http.MethodPost,
+				Path:    "/gpts/user/update",
+				Handler: User.UpdateGptsUserInfoHandler(serverCtx),
+			},
+			{
+				Method:  http.MethodPost,
 				Path:    "/gpts/user/balance",
 				Handler: User.GetGptsUserBalanceHandler(serverCtx),
 			},
@@ -1125,6 +1130,16 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
 				Path:    "/gpts/chat/session",
 				Handler: chatrecords.GptsGetApiSessionHandler(serverCtx),
 			},
+			{
+				Method:  http.MethodPost,
+				Path:    "/gpts/chat/session/delete",
+				Handler: chatrecords.GptsDeleteApiSessionHandler(serverCtx),
+			},
+			{
+				Method:  http.MethodPost,
+				Path:    "/gpts/chat/session/rename",
+				Handler: chatrecords.GptsRenameApiSessionHandler(serverCtx),
+			},
 		},
 	)
 

+ 2 - 2
internal/logic/User/get_gpts_user_info_logic.go

@@ -45,11 +45,11 @@ func (l *GetGptsUserInfoLogic) GetGptsUserInfo(tokenStr string) (*types.UserInfo
 		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
 	}
 
-	//department, _ := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: uint64(departmentId)})
-	//resp.Data = fmt.Sprintf("userId=%v departmentId=%v departmentName=%v ", userId, departmentId, *department.Name)
 	resp.Data.Username = userInfo.Username
 	resp.Data.Nickname = userInfo.Nickname
 	resp.Data.Id = &userId
 	resp.Data.Status = userInfo.Status
+	resp.Data.Mobile = userInfo.Mobile
+	resp.Data.Email = userInfo.Email
 	return &resp, nil
 }

+ 69 - 0
internal/logic/User/update_gpts_user_info_logic.go

@@ -0,0 +1,69 @@
+package User
+
+import (
+	"context"
+	"github.com/suyuan32/simple-admin-core/rpc/types/core"
+	"github.com/zeromicro/go-zero/core/errorx"
+	"wechat-api/internal/utils"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+
+	"github.com/zeromicro/go-zero/core/logx"
+)
+
+type UpdateGptsUserInfoLogic struct {
+	logx.Logger
+	ctx    context.Context
+	svcCtx *svc.ServiceContext
+}
+
+func NewUpdateGptsUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateGptsUserInfoLogic {
+	return &UpdateGptsUserInfoLogic{
+		Logger: logx.WithContext(ctx),
+		ctx:    ctx,
+		svcCtx: svcCtx}
+}
+
+func (l *UpdateGptsUserInfoLogic) UpdateGptsUserInfo(req *types.UserInfo, tokenStr string) (*types.BaseDataInfo, error) {
+	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError("用户未登录")
+	}
+
+	userId, ok := claims["userId"].(string)
+
+	if !ok || userId == "" {
+		return nil, errorx.NewInvalidArgumentError("用户需要登录")
+	}
+
+	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
+	valid := utils.CheckGptLogin(userInfo.RoleIds)
+	if !valid {
+		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
+	}
+
+	resp := types.BaseDataInfo{}
+	var mobile, nickname, email string
+	if req.Email != nil && *req.Email != "" {
+		email = *req.Email
+	}
+	if req.Mobile != nil && *req.Mobile != "" {
+		mobile = *req.Mobile
+	}
+	if req.Nickname != nil && *req.Nickname != "" {
+		nickname = *req.Nickname
+	}
+	_, err = l.svcCtx.CoreRpc.UpdateUser(l.ctx, &core.UserInfo{
+		Id:       &userId,
+		Mobile:   &mobile,
+		Nickname: &nickname,
+		Email:    &email,
+	})
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError(err.Error())
+	}
+
+	return &resp, nil
+}

+ 73 - 0
internal/logic/chatrecords/gpts_delete_api_session_logic.go

@@ -0,0 +1,73 @@
+package chatrecords
+
+import (
+	"context"
+	"fmt"
+	"github.com/suyuan32/simple-admin-core/rpc/types/core"
+	"github.com/zeromicro/go-zero/core/errorx"
+	"wechat-api/ent/employee"
+	"wechat-api/hook/dify"
+	"wechat-api/internal/utils"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+
+	"github.com/zeromicro/go-zero/core/logx"
+)
+
+type GptsDeleteApiSessionLogic struct {
+	logx.Logger
+	ctx    context.Context
+	svcCtx *svc.ServiceContext
+}
+
+func NewGptsDeleteApiSessionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GptsDeleteApiSessionLogic {
+	return &GptsDeleteApiSessionLogic{
+		Logger: logx.WithContext(ctx),
+		ctx:    ctx,
+		svcCtx: svcCtx}
+}
+
+func (l *GptsDeleteApiSessionLogic) GptsDeleteApiSession(req *types.GptsDeleteSessionReq, tokenStr string) (*types.BaseMsgResp, error) {
+	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError("用户未登录")
+	}
+	userId, ok := claims["userId"].(string)
+
+	if !ok || userId == "" {
+		return nil, errorx.NewInvalidArgumentError("用户需要登录")
+	}
+
+	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
+	valid := utils.CheckGptLogin(userInfo.RoleIds)
+	if !valid {
+		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
+	}
+
+	resp := types.BaseMsgResp{}
+	var conversationId string
+	var agentId uint64
+	if req.ConversationId != nil && *req.ConversationId != "" {
+		conversationId = *req.ConversationId
+	}
+	if conversationId == "" {
+		return nil, errorx.NewInvalidArgumentError("conversationId is empty")
+	}
+	if req.AgentId != nil && *req.AgentId > 0 {
+		agentId = *req.AgentId
+	}
+	employeeItem, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(agentId)).Only(l.ctx)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError("智能体不存在")
+	}
+
+	user := fmt.Sprintf("%s-%d", userId, agentId)
+	_, err = dify.DeleteSession(employeeItem.APIBase, employeeItem.APIKey, user, conversationId)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError(err.Error())
+	}
+
+	return &resp, nil
+}

+ 76 - 0
internal/logic/chatrecords/gpts_rename_api_session_logic.go

@@ -0,0 +1,76 @@
+package chatrecords
+
+import (
+	"context"
+	"fmt"
+	"github.com/suyuan32/simple-admin-core/rpc/types/core"
+	"github.com/zeromicro/go-zero/core/errorx"
+	"wechat-api/ent/employee"
+	"wechat-api/hook/dify"
+	"wechat-api/internal/utils"
+	jwtutils "wechat-api/internal/utils/jwt"
+
+	"wechat-api/internal/svc"
+	"wechat-api/internal/types"
+
+	"github.com/zeromicro/go-zero/core/logx"
+)
+
+type GptsRenameApiSessionLogic struct {
+	logx.Logger
+	ctx    context.Context
+	svcCtx *svc.ServiceContext
+}
+
+func NewGptsRenameApiSessionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GptsRenameApiSessionLogic {
+	return &GptsRenameApiSessionLogic{
+		Logger: logx.WithContext(ctx),
+		ctx:    ctx,
+		svcCtx: svcCtx}
+}
+
+func (l *GptsRenameApiSessionLogic) GptsRenameApiSession(req *types.GptsRenameSessionReq, tokenStr string) (*types.BaseMsgResp, error) {
+	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError("用户未登录")
+	}
+	userId, ok := claims["userId"].(string)
+
+	if !ok || userId == "" {
+		return nil, errorx.NewInvalidArgumentError("用户需要登录")
+	}
+
+	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
+	valid := utils.CheckGptLogin(userInfo.RoleIds)
+	if !valid {
+		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
+	}
+
+	resp := types.BaseMsgResp{}
+	var conversationId, name string
+	var agentId uint64
+	if req.ConversationId != nil && *req.ConversationId != "" {
+		conversationId = *req.ConversationId
+	}
+	if req.Name != nil && *req.Name != "" {
+		name = *req.Name
+	}
+	if conversationId == "" {
+		return nil, errorx.NewInvalidArgumentError("conversationId is empty")
+	}
+	if req.AgentId != nil && *req.AgentId > 0 {
+		agentId = *req.AgentId
+	}
+	employeeItem, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(agentId)).Only(l.ctx)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError("智能体不存在")
+	}
+
+	user := fmt.Sprintf("%s-%d", userId, agentId)
+	_, err = dify.RenameSession(employeeItem.APIBase, employeeItem.APIKey, user, name, conversationId)
+	if err != nil {
+		return nil, errorx.NewInvalidArgumentError(err.Error())
+	}
+
+	return &resp, nil
+}

+ 13 - 0
internal/types/types.go

@@ -2438,6 +2438,19 @@ type Session struct {
 	Inputs    interface{} `json:"inputs"`
 }
 
+// swagger:model GptsDeleteSessionReq
+type GptsDeleteSessionReq struct {
+	AgentId        *uint64 `json:"agentId"`
+	ConversationId *string `json:"conversationId"`
+}
+
+// swagger:model GptsRenameSessionReq
+type GptsRenameSessionReq struct {
+	AgentId        *uint64 `json:"agentId"`
+	ConversationId *string `json:"conversationId"`
+	Name           *string `json:"name"`
+}
+
 // The data of chat session information | ChatSession信息
 // swagger:model ChatSessionInfo
 type ChatSessionInfo struct {