package credit_balance import ( "context" "github.com/suyuan32/simple-admin-common/msg/errormsg" "github.com/suyuan32/simple-admin-core/rpc/types/core" "github.com/zeromicro/go-zero/core/errorx" "wechat-api/ent/creditbalance" "wechat-api/internal/svc" "wechat-api/internal/types" "github.com/zeromicro/go-zero/core/logx" ) type OperateCreditBalanceLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewOperateCreditBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OperateCreditBalanceLogic { return &OperateCreditBalanceLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx} } func (l *OperateCreditBalanceLogic) OperateCreditBalance(req *types.CreditBalanceOperateReq) (*types.BaseMsgResp, error) { if req.Number == nil || *req.Number == 0 { return nil, errorx.NewInvalidArgumentError("Number参数非法") } if req.UserId == nil { return nil, errorx.NewInvalidArgumentError("UserId参数非法") } creditBalance, err := l.svcCtx.DB.CreditBalance.Query().Where(creditbalance.UserID(*req.UserId)).Only(l.ctx) if err != nil { l.Logger.Errorf("query credit_balance error:%v\n", err) return nil, errorx.NewInvalidArgumentError(err.Error()) } var ntype int if *req.Number > 0 { ntype = 2 } else { ntype = 1 } userInfo, err := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: *req.UserId}) if err != nil { l.Logger.Errorf("query user error:%v\n", err) return nil, errorx.NewInvalidArgumentError("用户不存在") } tx, err := l.svcCtx.DB.Tx(context.Background()) _, err = tx.CreditUsage.Create(). SetUserID(*req.UserId). SetNumber(*req.Number). SetNtype(ntype). SetNid(0). SetTable(""). SetReason(*req.Reason). SetOrganizationID(*userInfo.DepartmentId). Save(l.ctx) if err != nil { l.Logger.Errorf("create credit_usage error:%v\n", err) _ = tx.Rollback() return nil, errorx.NewInvalidArgumentError("创建用户积分明细失败,请重试") } if *req.Number > 0 { if creditBalance == nil { _, err = l.svcCtx.DB.CreditBalance.Create(). SetUserID(*req.UserId). SetBalance(*req.Number). Save(l.ctx) if err != nil { l.Logger.Errorf("create credit_balance error:%v\n", err) _ = tx.Rollback() return nil, errorx.NewInvalidArgumentError("创建用户积分余额失败,请重试") } } else { _, err = l.svcCtx.DB.CreditBalance.Update().Where(creditbalance.UserID(*req.UserId)).SetBalance(creditBalance.Balance + *req.Number).Save(l.ctx) if err != nil { l.Logger.Errorf("update credit_balance error:%v\n", err) _ = tx.Rollback() return nil, errorx.NewInvalidArgumentError("修改用户积分余额失败,请重试.") } } } else { _, err := l.svcCtx.DB.CreditBalance.Update().Where(creditbalance.UserID(*req.UserId)).SetBalance(creditBalance.Balance + *req.Number).Save(l.ctx) if err != nil { l.Logger.Errorf("update credit_balance error:%v\n", err) _ = tx.Rollback() return nil, errorx.NewInvalidArgumentError("修改用户积分余额失败,请重试...") } } _ = tx.Commit() return &types.BaseMsgResp{ Code: 0, Msg: errormsg.Success, }, nil }