Bläddra i källkod

Merge branch 'yhg_250102' into debug

jimmyyem 2 månader sedan
förälder
incheckning
5a37e5b6d2

+ 2 - 8
desc/wechat/credit_usage.api

@@ -22,6 +22,7 @@ type (
 
         // organization_id | 租户ID 
         OrganizationId  *uint64 `json:"organizationId,optional"`
+		OrganizationName  *string `json:"organizationName,optional"`
 
         // nid | 积分变化关联信息ID 
         Nid  *uint64 `json:"nid,optional"`
@@ -53,14 +54,7 @@ type (
     CreditUsageListReq {
         PageInfo
 
-        // user_id | 用户ID 
-        UserId  *string `json:"userId,optional"`
-
-        // table | 积分变化表名 
-        Table  *string `json:"table,optional"`
-
-        // reason | 积分变动原因 
-        Reason  *string `json:"reason,optional"`
+		OrganizationId  *uint64 `json:"organizationId,optional"`
     }
 
     // CreditUsage information response | CreditUsage信息返回体

+ 12 - 28
internal/logic/chatrecords/gpts_submit_api_chat_logic.go

@@ -80,9 +80,8 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 	// 先查用户的积分余额,如果不足 则查租户的积分余额
 	var switcher bool
 	var balance float32
-	var balanceOwner string
 	//switcher = true	//TODO 打开这里就是开始计费,并且会记录使用积分和token的信息
-	creditBalance, err := l.svcCtx.DB.CreditBalance.Query().Where(creditbalance.UserID(userId)).Only(l.ctx)
+	creditBalance, err := l.svcCtx.DB.CreditBalance.Query().Where(creditbalance.OrganizationID(*userInfo.DepartmentId)).Only(l.ctx)
 	if switcher {
 		if err != nil {
 			if !ent.IsNotFound(err) {
@@ -92,20 +91,7 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 		} else {
 			if creditBalance.Balance > 0 {
 				balance = creditBalance.Balance
-				balanceOwner = "user"
-			} else {
-				creditBalance, err = l.svcCtx.DB.CreditBalance.Query().Where(creditbalance.OrganizationID(*userInfo.DepartmentId)).Only(l.ctx)
-				if err != nil {
-					if !ent.IsNotFound(err) {
-						l.Logger.Errorf("query user balance failed:%v\n", err)
-						return
-					}
-				} else {
-					if creditBalance.Balance > 0 {
-						balance = creditBalance.Balance
-						balanceOwner = "organization"
-					}
-				}
+
 			}
 		}
 
@@ -211,6 +197,7 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 
 			if finish {
 				if switcher {
+					tx, err := l.svcCtx.DB.Tx(context.Background())
 					// 构造 original_data
 					originalData := custom_types.OriginalData{}
 					originalData.Request = chatReq
@@ -218,7 +205,7 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 
 					agentId := strconv.Itoa(int(*req.AgentId))
 					// 记录Token使用信息
-					usageDetailItem, err := l.svcCtx.DB.UsageDetail.Create().
+					usageDetailItem, err := tx.UsageDetail.Create().
 						SetType(3).            //1-微信 2-名片 3-智能体
 						SetBotID(agentId).     //智能体ID
 						SetReceiverID(userId). //接收者userID
@@ -233,6 +220,7 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 						Save(l.ctx)
 
 					if err != nil {
+						_ = tx.Rollback()
 						l.Logger.Errorf("save data to usage_detail error:%v\n", err)
 					}
 
@@ -240,7 +228,7 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 					// 根据1:1000 根据Token换算积分使用量
 					change := float64(chatData.Metadata.Usage.TotalTokens) / float64(1000)
 					number := float32(math.Round(change*1000) / 1000)
-					_, err = l.svcCtx.DB.CreditUsage.Create().
+					_, err = tx.CreditUsage.Create().
 						SetUserID(userId).
 						SetNumber(number).
 						SetNtype(1).
@@ -249,21 +237,17 @@ func (l *GptsSubmitApiChatLogic) GptsSubmitApiChat(tokenStr string, req *types.G
 						SetOrganizationID(*userInfo.DepartmentId).
 						Save(l.ctx)
 					if err != nil {
+						_ = tx.Rollback()
 						l.Logger.Errorf("save data to credit_usage error:%v\n", err)
 					}
 
 					// 减积分
-					if balanceOwner == "user" {
-						_, err := l.svcCtx.DB.CreditBalance.Update().Where(creditbalance.UserID(userId)).SetBalance(creditBalance.Balance - number).Save(l.ctx)
-						if err != nil {
-							l.Logger.Errorf("update user:%v balance error:%v\n", userId, err)
-						}
-					} else {
-						_, err := l.svcCtx.DB.CreditBalance.Update().Where(creditbalance.OrganizationID(*userInfo.DepartmentId)).SetBalance(creditBalance.Balance - number).Save(l.ctx)
-						if err != nil {
-							l.Logger.Errorf("update organization:%v balance error:%v\n", *userInfo.DepartmentId, err)
-						}
+					_, err = tx.CreditBalance.Update().Where(creditbalance.OrganizationID(*userInfo.DepartmentId)).SetBalance(creditBalance.Balance - number).Save(l.ctx)
+					if err != nil {
+						_ = tx.Rollback()
+						l.Logger.Errorf("update organization:%v balance error:%v\n", *userInfo.DepartmentId, err)
 					}
+					_ = tx.Commit()
 				}
 				break
 			}

+ 18 - 17
internal/logic/credit_usage/get_credit_usage_list_logic.go

@@ -2,6 +2,7 @@ package credit_usage
 
 import (
 	"context"
+	"github.com/suyuan32/simple-admin-core/rpc/types/core"
 
 	"wechat-api/ent/creditusage"
 	"wechat-api/ent/predicate"
@@ -31,14 +32,8 @@ func NewGetCreditUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext)
 
 func (l *GetCreditUsageListLogic) GetCreditUsageList(req *types.CreditUsageListReq) (*types.CreditUsageListResp, error) {
 	var predicates []predicate.CreditUsage
-	if req.UserId != nil {
-		predicates = append(predicates, creditusage.UserID(*req.UserId))
-	}
-	if req.Table != nil {
-		predicates = append(predicates, creditusage.TableEQ(*req.Table))
-	}
-	if req.Reason != nil {
-		predicates = append(predicates, creditusage.ReasonContains(*req.Reason))
+	if req.OrganizationId != nil {
+		predicates = append(predicates, creditusage.OrganizationID(*req.OrganizationId))
 	}
 	data, err := l.svcCtx.DB.CreditUsage.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)
 
@@ -50,6 +45,11 @@ func (l *GetCreditUsageListLogic) GetCreditUsageList(req *types.CreditUsageListR
 	resp.Msg = errormsg.Success
 	resp.Data.Total = data.PageDetails.Total
 
+	departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: *req.OrganizationId})
+	if err != nil {
+		return nil, err
+	}
+
 	for _, v := range data.List {
 		resp.Data.Data = append(resp.Data.Data,
 			types.CreditUsageInfo{
@@ -58,15 +58,16 @@ func (l *GetCreditUsageListLogic) GetCreditUsageList(req *types.CreditUsageListR
 					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
 					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
 				},
-				UserId:         &v.UserID,
-				Number:         &v.Number,
-				Status:         &v.Status,
-				Ntype:          &v.Ntype,
-				Table:          &v.Table,
-				OrganizationId: &v.OrganizationID,
-				Nid:            &v.Nid,
-				Reason:         &v.Reason,
-				Operator:       &v.Operator,
+				UserId:           &v.UserID,
+				Number:           &v.Number,
+				Status:           &v.Status,
+				Ntype:            &v.Ntype,
+				Table:            &v.Table,
+				OrganizationId:   &v.OrganizationID,
+				OrganizationName: departmentInfo.Name,
+				Nid:              &v.Nid,
+				Reason:           &v.Reason,
+				Operator:         &v.Operator,
 			})
 	}
 

+ 3 - 7
internal/types/types.go

@@ -3313,7 +3313,8 @@ type CreditUsageInfo struct {
 	// table | 积分变化表名
 	Table *string `json:"table,optional"`
 	// organization_id | 租户ID
-	OrganizationId *uint64 `json:"organizationId,optional"`
+	OrganizationId   *uint64 `json:"organizationId,optional"`
+	OrganizationName *string `json:"organizationName,optional"`
 	// nid | 积分变化关联信息ID
 	Nid *uint64 `json:"nid,optional"`
 	// reason | 积分变动原因
@@ -3342,12 +3343,7 @@ type CreditUsageListInfo struct {
 // swagger:model CreditUsageListReq
 type CreditUsageListReq struct {
 	PageInfo
-	// user_id | 用户ID
-	UserId *string `json:"userId,optional"`
-	// table | 积分变化表名
-	Table *string `json:"table,optional"`
-	// reason | 积分变动原因
-	Reason *string `json:"reason,optional"`
+	OrganizationId *uint64 `json:"organizationId,optional"`
 }
 
 // CreditUsage information response | CreditUsage信息返回体