From c23bad822748ed1cf0d9709c93b6be2081553578 Mon Sep 17 00:00:00 2001 From: Jiahui <4543bxy@gmail.com> Date: Thu, 19 Sep 2024 16:18:23 +0800 Subject: [PATCH] Fix/get invoice payment (#5088) * fix get payment with invoice arg * remove old version verification process * fix get transfer * fix deploy account service in cloud scripts * swag --- .../pkg/database/cockroach/accountv2.go | 17 +- deploy/cloud/scripts/init.sh | 2 +- service/account/api/api.go | 163 +++--------------- service/account/dao/interface.go | 16 +- service/account/dao/interface_test.go | 4 +- service/account/docs/docs.go | 140 +++++++-------- service/account/docs/swagger.json | 140 +++++++-------- service/account/docs/swagger.yaml | 96 +++++------ service/account/helper/request.go | 16 +- service/account/router/router.go | 6 + 10 files changed, 222 insertions(+), 378 deletions(-) diff --git a/controllers/pkg/database/cockroach/accountv2.go b/controllers/pkg/database/cockroach/accountv2.go index 19233ebd91a..5f5fe47e449 100644 --- a/controllers/pkg/database/cockroach/accountv2.go +++ b/controllers/pkg/database/cockroach/accountv2.go @@ -231,7 +231,7 @@ func (c *Cockroach) GetTransfer(ops *types.GetTransfersReq) (*types.GetTransfers func (c *Cockroach) performTransferQuery(ops *types.GetTransfersReq, limit, offset int, start, end time.Time, transfers *[]types.Transfer, count *int64) error { var err error - query := c.DB.Limit(limit).Offset(offset). + query := c.DB.Model(&types.Transfer{}).Limit(limit).Offset(offset). Where("created_at BETWEEN ? AND ?", start, end) countQuery := c.DB.Model(&types.Transfer{}). Where("created_at BETWEEN ? AND ?", start, end) @@ -243,13 +243,13 @@ func (c *Cockroach) performTransferQuery(ops *types.GetTransfersReq, limit, offs } else { switch ops.Type { case types.TypeTransferIn: - userCondition = `"toUserUid" = ? AND "toUserId" = ?` + userCondition = `"toUserUid" = ? OR "toUserId" = ?` args = append(args, ops.UID, ops.ID) case types.TypeTransferOut: - userCondition = `"fromUserUid" = ? AND "fromUserId" = ?` + userCondition = `"fromUserUid" = ? OR "fromUserId" = ?` args = append(args, ops.UID, ops.ID) default: - userCondition = `("fromUserUid" = ? AND "fromUserId" = ?) OR ("toUserUid" = ? AND "toUserId" = ?)` + userCondition = `"fromUserUid" = ? OR "fromUserId" = ? OR "toUserUid" = ? OR "toUserId" = ?` args = append(args, ops.UID, ops.ID, ops.UID, ops.ID) } } @@ -257,6 +257,7 @@ func (c *Cockroach) performTransferQuery(ops *types.GetTransfersReq, limit, offs query = query.Where(userCondition, args...) countQuery = countQuery.Where(userCondition, args...) + query = query.Order("created_at DESC") err = query.Find(transfers).Error if err != nil { return fmt.Errorf("failed to get transfer: %v", err) @@ -651,7 +652,7 @@ func (c *Cockroach) GetPaymentWithID(paymentID string) (*types.Payment, error) { return &payment, nil } -func (c *Cockroach) GetPaymentWithLimit(ops *types.UserQueryOpts, req types.LimitReq, invoiced bool) ([]types.Payment, types.LimitResp, error) { +func (c *Cockroach) GetPaymentWithLimit(ops *types.UserQueryOpts, req types.LimitReq, invoiced *bool) ([]types.Payment, types.LimitResp, error) { var payment []types.Payment var total int64 var limitResp types.LimitResp @@ -662,10 +663,10 @@ func (c *Cockroach) GetPaymentWithLimit(ops *types.UserQueryOpts, req types.Limi } queryPayment := types.Payment{PaymentRaw: types.PaymentRaw{UserUID: userUID}} - if invoiced { - queryPayment.InvoicedAt = true - } query := c.DB.Model(&types.Payment{}).Where(queryPayment) + if invoiced != nil { + query = query.Where("invoiced_at = ?", *invoiced) + } if !req.StartTime.IsZero() { query = query.Where("created_at >= ?", req.StartTime) } diff --git a/deploy/cloud/scripts/init.sh b/deploy/cloud/scripts/init.sh index 2105457a035..a46e384c9d8 100644 --- a/deploy/cloud/scripts/init.sh +++ b/deploy/cloud/scripts/init.sh @@ -213,7 +213,7 @@ function sealos_run_controller { --env LOCAL_COCKROACH_URI="$cockroachdbLocalUri" \ --env LOCAL_REGION="$localRegionUID" - sealos run tars/account-service.tar + sealos run tars/account-service.tar --env cloudDomain="$cloudDomain" --env cloudPort="$cloudPort" # run license controller sealos run tars/license.tar diff --git a/service/account/api/api.go b/service/account/api/api.go index 665b1d3d05e..a14a04ece92 100644 --- a/service/account/api/api.go +++ b/service/account/api/api.go @@ -9,9 +9,8 @@ import ( "io" "net/http" "os" - "strings" - auth2 "github.com/labring/sealos/service/pkg/auth" + "gorm.io/gorm" "github.com/labring/sealos/controllers/pkg/resources" @@ -242,7 +241,7 @@ func GetPayment(c *gin.Context) { c.JSON(http.StatusUnauthorized, helper.ErrorMessage{Error: fmt.Sprintf("authenticate error : %v", err)}) return } - payment, limitResp, err := dao.DBClient.GetPayment(&types.UserQueryOpts{Owner: req.Auth.Owner}, req) + payment, limitResp, err := dao.DBClient.GetPayment(&types.UserQueryOpts{ID: req.Auth.UserID}, req) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to get payment : %v", err)}) return @@ -265,14 +264,14 @@ func GetPayment(c *gin.Context) { // @Tags RechargeAmount // @Accept json // @Produce json -// @Param request body helper.UserBaseReq true "User recharge amount request" +// @Param request body helper.UserTimeRangeReq true "User recharge amount request" // @Success 200 {object} map[string]interface{} "successfully retrieved user recharge amount" // @Failure 400 {object} map[string]interface{} "failed to parse user recharge amount request" // @Failure 401 {object} map[string]interface{} "authenticate error" // @Failure 500 {object} map[string]interface{} "failed to get user recharge amount" // @Router /account/v1alpha1/costs/recharge [post] func GetRechargeAmount(c *gin.Context) { - req, err := helper.ParseUserBaseReq(c) + req, err := helper.ParseUserTimeRangeReq(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to parse user recharge amount request: %v", err)}) return @@ -281,7 +280,7 @@ func GetRechargeAmount(c *gin.Context) { c.JSON(http.StatusUnauthorized, helper.ErrorMessage{Error: fmt.Sprintf("authenticate error : %v", err)}) return } - amount, err := dao.DBClient.GetRechargeAmount(types.UserQueryOpts{Owner: req.Auth.Owner}, req.TimeRange.StartTime, req.TimeRange.EndTime) + amount, err := dao.DBClient.GetRechargeAmount(types.UserQueryOpts{ID: req.Auth.UserID}, req.TimeRange.StartTime, req.TimeRange.EndTime) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to get recharge amount : %v", err)}) return @@ -297,14 +296,14 @@ func GetRechargeAmount(c *gin.Context) { // @Tags PropertiesUsedAmount // @Accept json // @Produce json -// @Param request body helper.UserBaseReq true "User properties used amount request" +// @Param request body helper.UserTimeRangeReq true "User properties used amount request" // @Success 200 {object} map[string]interface{} "successfully retrieved user properties used amount" // @Failure 400 {object} map[string]interface{} "failed to parse user properties used amount request" // @Failure 401 {object} map[string]interface{} "authenticate error" // @Failure 500 {object} map[string]interface{} "failed to get user properties used amount" // @Router /account/v1alpha1/costs/properties [post] func GetPropertiesUsedAmount(c *gin.Context) { - req, err := helper.ParseUserBaseReq(c) + req, err := helper.ParseUserTimeRangeReq(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to parse user properties used amount request: %v", err)}) return @@ -332,6 +331,7 @@ type CostsResultData struct { Costs common.TimeCostsMap `json:"costs" bson:"costs"` } +// GetCosts // @Summary Get user costs // @Description Get user costs within a specified time range // @Tags Costs @@ -370,22 +370,17 @@ func GetCosts(c *gin.Context) { // @Tags Account // @Accept json // @Produce json -// @Param request body helper.Auth true "auth request" // @Success 200 {object} map[string]interface{} "successfully retrieved user account" // @Failure 401 {object} map[string]interface{} "authenticate error" // @Failure 500 {object} map[string]interface{} "failed to get user account" // @Router /account/v1alpha1/account [post] func GetAccount(c *gin.Context) { - req, err := helper.ParseUserBaseReq(c) - if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to parse user hour costs amount request: %v", err)}) - return - } + req := &helper.AuthBase{} if err := authenticateRequest(c, req); err != nil { c.JSON(http.StatusUnauthorized, helper.ErrorMessage{Error: fmt.Sprintf("authenticate error : %v", err)}) return } - account, err := dao.DBClient.GetAccount(types.UserQueryOpts{Owner: req.Auth.Owner}) + account, err := dao.DBClient.GetAccount(types.UserQueryOpts{ID: req.Auth.UserID}) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to get account : %v", err)}) return @@ -486,7 +481,7 @@ func GetTransfer(c *gin.Context) { return } ops := types.GetTransfersReq{ - UserQueryOpts: &types.UserQueryOpts{Owner: req.Auth.Owner}, + UserQueryOpts: &types.UserQueryOpts{ID: req.Auth.UserID}, Type: types.TransferType(req.Type), LimitReq: types.LimitReq{ Page: req.Page, @@ -546,18 +541,13 @@ func GetAPPCosts(c *gin.Context) { // @Tags Permission // @Accept json // @Produce json -// @Param request body helper.UserBaseReq true "Check permission request" // @Success 200 {object} map[string]interface{} "successfully check permission" // @Failure 400 {object} map[string]interface{} "failed to parse check permission request" // @Failure 401 {object} map[string]interface{} "authenticate error" // @Failure 500 {object} map[string]interface{} "failed to check permission" // @Router /account/v1alpha1/check-permission [post] func CheckPermission(c *gin.Context) { - req, err := helper.ParseUserBaseReq(c) - if err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": fmt.Sprintf("failed to parse check permission request: %v", err)}) - return - } + req := &helper.AuthBase{} if err := authenticateRequest(c, req); err != nil { c.JSON(http.StatusUnauthorized, helper.ErrorMessage{Error: fmt.Sprintf("authenticate error : %v", err)}) return @@ -674,7 +664,7 @@ func GetAppTypeList(c *gin.Context) { // @Failure 400 {object} map[string]interface{} "failed to parse basic cost distribution request" // @Failure 401 {object} map[string]interface{} "authenticate error" // @Failure 500 {object} map[string]interface{} "failed to get basic cost distribution" -// @Router /account/v1alpha1/basic-cost-distribution [post] +// @Router /account/v1alpha1/cost-basic-distribution [post] func GetBasicCostDistribution(c *gin.Context) { req, err := helper.ParseGetCostAppListReq(c) if err != nil { @@ -727,12 +717,15 @@ func GetAppCostTimeRange(c *gin.Context) { }) } -func ParseAuthTokenUser(c *gin.Context) (*helper.Auth, error) { +func ParseAuthTokenUser(c *gin.Context) (auth *helper.Auth, err error) { user, err := dao.JwtMgr.ParseUser(c) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to parse user: %v", err) } - auth := &helper.Auth{ + if user.UserID == "" { + return nil, fmt.Errorf("invalid user: %v", user) + } + auth = &helper.Auth{ Owner: user.UserCrName, UserID: user.UserID, } @@ -740,13 +733,13 @@ func ParseAuthTokenUser(c *gin.Context) (*helper.Auth, error) { if dao.DBClient.GetLocalRegion().UID.String() != user.RegionUID { auth.Owner, err = dao.DBClient.GetUserCrName(types.UserQueryOpts{ID: user.UserID}) if err != nil { - return nil, fmt.Errorf("get user cr name error: %v", err) + if errors.Is(err, gorm.ErrRecordNotFound) { + fmt.Printf("failed to get user cr name: %v\n", err) + return auth, nil + } } } - if auth.Owner == "" || auth.UserID == "" { - return nil, fmt.Errorf("invalid user: %v", user) - } - return auth, nil + return } func checkInvoiceToken(token string) error { @@ -837,18 +830,9 @@ func authenticateRequest(c *gin.Context, req helper.AuthReq) error { if req.GetAuth() != nil && req.GetAuth().Token != "" { return checkInvoiceToken(req.GetAuth().Token) } - auth, err := ParseAuthTokenUser(c) - if err == nil { - req.SetAuth(auth) - return nil - } - - if !errors.Is(err, helper.ErrNullAuth) { - return err - } - - return CheckAuthAndCalibrate(req.GetAuth()) + req.SetAuth(auth) + return err } // SetStatusInvoice @@ -992,98 +976,3 @@ func UserUsage(c *gin.Context) { "data": usage, }) } - -func CheckAuthAndCalibrate(auth *helper.Auth) (err error) { - if auth == nil { - return helper.ErrNullAuth - } - if !dao.Debug || auth.KubeConfig != "" { - if err = checkAuth(auth); err != nil { - return fmt.Errorf("check auth error: %v", err) - } - } - auth.Owner, err = dao.DBClient.GetUserCrName(types.UserQueryOpts{ID: auth.UserID}) - if err != nil { - return fmt.Errorf("get user cr name error: %v", err) - } - return nil -} - -func checkAuth(auth *helper.Auth) error { - if err := helper.AuthenticateKC(*auth); err != nil { - return fmt.Errorf("authenticate error : %v", err) - } - host, err := auth2.GetKcHost(auth.KubeConfig) - if err != nil { - return fmt.Errorf("failed to get kc host: %v", err) - } - host = strings.TrimPrefix(strings.TrimPrefix(host, "https://"), "http://") - if !strings.Contains(host, dao.Cfg.LocalRegionDomain) { - if err := CalibrateRegionAuth(auth, host); err != nil { - return fmt.Errorf("calibrate region auth error: %v", err) - } - } else { - user, err := auth2.GetKcUser(auth.KubeConfig) - if err != nil { - return fmt.Errorf("failed to get kc user: %v", err) - } - userID, err := dao.DBClient.GetUserID(types.UserQueryOpts{Owner: user}) - if err != nil { - return fmt.Errorf("get user id error: %v", err) - } - auth.UserID = userID - } - auth.Owner, err = dao.DBClient.GetUserCrName(types.UserQueryOpts{ID: auth.UserID}) - if err != nil { - return fmt.Errorf("get user cr name error: %v", err) - } - return nil -} - -func CalibrateRegionAuth(auth *helper.Auth, kcHost string) error { - for i := range dao.Cfg.Regions { - reg := dao.Cfg.Regions[i] - if !strings.Contains(kcHost, reg.Domain) { - continue - } - svcURL := fmt.Sprintf("https://%s%s%s", reg.AccountSvc, helper.GROUP, helper.CheckPermission) - - authBody, err := json.Marshal(auth) - if err != nil { - return fmt.Errorf("failed to marshal auth: %v", err) - } - tr := &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: os.Getenv("INSECURE_VERIFY") != "true", MinVersion: tls.VersionTLS13}, - } - client := &http.Client{Transport: tr} - resp, err := client.Post(svcURL, "application/json", bytes.NewBuffer(authBody)) - if err != nil { - return fmt.Errorf("failed to post request: %v", err) - } - defer resp.Body.Close() - - responseBody := new(bytes.Buffer) - _, err = responseBody.ReadFrom(resp.Body) - if err != nil { - return fmt.Errorf("failed to read response body: %v", err) - } - var respMap map[string]interface{} - if err = json.Unmarshal(responseBody.Bytes(), &respMap); err != nil { - return fmt.Errorf("failed to unmarshal response body: %v", err) - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("failed to check permission: %v, error: %s", resp, respMap["error"]) - } - _userID, ok := respMap["userID"] - if !ok { - return fmt.Errorf("failed to get userID from response: %v", respMap) - } - userID, ok := _userID.(string) - if !ok { - return fmt.Errorf("failed to convert userID to string: %v", _userID) - } - auth.UserID = userID - return nil - } - return fmt.Errorf("failed to calibrate region auth") -} diff --git a/service/account/dao/interface.go b/service/account/dao/interface.go index 2f0d7a17e99..16f72c12284 100644 --- a/service/account/dao/interface.go +++ b/service/account/dao/interface.go @@ -107,7 +107,7 @@ func (g *Cockroach) GetUserID(ops types.UserQueryOpts) (string, error) { func (g *Cockroach) GetUserCrName(ops types.UserQueryOpts) (string, error) { user, err := g.ck.GetUserCr(&ops) if err != nil { - return "", fmt.Errorf("failed to get user: %v", err) + return "", err } return user.CrName, nil } @@ -1055,11 +1055,21 @@ func (m *MongoDB) getAppStoreList(req helper.GetCostAppListReq, skip, pageSize i return } -func (m *MongoDB) Disconnect(ctx context.Context) error { +func (m *Account) Disconnect(ctx context.Context) error { if m == nil { return nil } - return m.Client.Disconnect(ctx) + if m.MongoDB != nil && m.MongoDB.Client != nil { + if err := m.MongoDB.Client.Disconnect(ctx); err != nil { + return fmt.Errorf("failed to close mongodb client: %v", err) + } + } + if m.Cockroach != nil && m.Cockroach.ck != nil { + if err := m.ck.Close(); err != nil { + return fmt.Errorf("failed to close cockroach client: %v", err) + } + } + return nil } func (m *MongoDB) GetConsumptionAmount(req helper.ConsumptionRecordReq) (int64, error) { diff --git a/service/account/dao/interface_test.go b/service/account/dao/interface_test.go index 96c80dac85c..9b8bc417c72 100644 --- a/service/account/dao/interface_test.go +++ b/service/account/dao/interface_test.go @@ -35,7 +35,7 @@ func TestMongoDB_GetAppCosts(t *testing.T) { return } appCosts, err := db.GetAppCosts(&helper.AppCostsReq{ - UserBaseReq: helper.UserBaseReq{ + UserTimeRangeReq: helper.UserTimeRangeReq{ TimeRange: helper.TimeRange{ StartTime: time.Now().Add(-24 * time.Hour * 30), EndTime: time.Now(), @@ -465,7 +465,7 @@ func TestMongoDB_GetAppCost1(t *testing.T) { } }() req := &helper.AppCostsReq{ - UserBaseReq: helper.UserBaseReq{ + UserTimeRangeReq: helper.UserTimeRangeReq{ TimeRange: helper.TimeRange{ StartTime: time.Now().Add(-24 * time.Hour * 30), EndTime: time.Now(), diff --git a/service/account/docs/docs.go b/service/account/docs/docs.go index ca2a62c8375..84e5ede0e7e 100644 --- a/service/account/docs/docs.go +++ b/service/account/docs/docs.go @@ -31,17 +31,6 @@ const docTemplate = `{ "Account" ], "summary": "Get user account", - "parameters": [ - { - "description": "auth request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.Auth" - } - } - ], "responses": { "200": { "description": "successfully retrieved user account", @@ -67,62 +56,6 @@ const docTemplate = `{ } } }, - "/account/v1alpha1/basic-cost-distribution": { - "post": { - "description": "Get basic cost distribution", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "BasicCostDistribution" - ], - "summary": "Get basic cost distribution", - "parameters": [ - { - "description": "Basic cost distribution request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.GetCostAppListReq" - } - } - ], - "responses": { - "200": { - "description": "successfully get basic cost distribution", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "failed to parse basic cost distribution request", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "401": { - "description": "authenticate error", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "500": { - "description": "failed to get basic cost distribution", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, "/account/v1alpha1/check-permission": { "post": { "description": "Check permission", @@ -136,17 +69,6 @@ const docTemplate = `{ "Permission" ], "summary": "Check permission", - "parameters": [ - { - "description": "Check permission request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.UserBaseReq" - } - } - ], "responses": { "200": { "description": "successfully check permission", @@ -321,6 +243,62 @@ const docTemplate = `{ } } }, + "/account/v1alpha1/cost-basic-distribution": { + "post": { + "description": "Get basic cost distribution", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BasicCostDistribution" + ], + "summary": "Get basic cost distribution", + "parameters": [ + { + "description": "Basic cost distribution request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/helper.GetCostAppListReq" + } + } + ], + "responses": { + "200": { + "description": "successfully get basic cost distribution", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "failed to parse basic cost distribution request", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "authenticate error", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "500": { + "description": "failed to get basic cost distribution", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, "/account/v1alpha1/cost-overview": { "post": { "description": "Get cost overview", @@ -676,7 +654,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/helper.UserBaseReq" + "$ref": "#/definitions/helper.UserTimeRangeReq" } } ], @@ -732,7 +710,7 @@ const docTemplate = `{ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/helper.UserBaseReq" + "$ref": "#/definitions/helper.UserTimeRangeReq" } } ], @@ -2085,7 +2063,7 @@ const docTemplate = `{ } } }, - "helper.UserBaseReq": { + "helper.UserTimeRangeReq": { "type": "object", "properties": { "endTime": { diff --git a/service/account/docs/swagger.json b/service/account/docs/swagger.json index ee7611ec57e..09004ed4bdc 100644 --- a/service/account/docs/swagger.json +++ b/service/account/docs/swagger.json @@ -24,17 +24,6 @@ "Account" ], "summary": "Get user account", - "parameters": [ - { - "description": "auth request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.Auth" - } - } - ], "responses": { "200": { "description": "successfully retrieved user account", @@ -60,62 +49,6 @@ } } }, - "/account/v1alpha1/basic-cost-distribution": { - "post": { - "description": "Get basic cost distribution", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "BasicCostDistribution" - ], - "summary": "Get basic cost distribution", - "parameters": [ - { - "description": "Basic cost distribution request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.GetCostAppListReq" - } - } - ], - "responses": { - "200": { - "description": "successfully get basic cost distribution", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "failed to parse basic cost distribution request", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "401": { - "description": "authenticate error", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "500": { - "description": "failed to get basic cost distribution", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, "/account/v1alpha1/check-permission": { "post": { "description": "Check permission", @@ -129,17 +62,6 @@ "Permission" ], "summary": "Check permission", - "parameters": [ - { - "description": "Check permission request", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/helper.UserBaseReq" - } - } - ], "responses": { "200": { "description": "successfully check permission", @@ -314,6 +236,62 @@ } } }, + "/account/v1alpha1/cost-basic-distribution": { + "post": { + "description": "Get basic cost distribution", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "BasicCostDistribution" + ], + "summary": "Get basic cost distribution", + "parameters": [ + { + "description": "Basic cost distribution request", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/helper.GetCostAppListReq" + } + } + ], + "responses": { + "200": { + "description": "successfully get basic cost distribution", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "failed to parse basic cost distribution request", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "authenticate error", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "500": { + "description": "failed to get basic cost distribution", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, "/account/v1alpha1/cost-overview": { "post": { "description": "Get cost overview", @@ -669,7 +647,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/helper.UserBaseReq" + "$ref": "#/definitions/helper.UserTimeRangeReq" } } ], @@ -725,7 +703,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/helper.UserBaseReq" + "$ref": "#/definitions/helper.UserTimeRangeReq" } } ], @@ -2078,7 +2056,7 @@ } } }, - "helper.UserBaseReq": { + "helper.UserTimeRangeReq": { "type": "object", "properties": { "endTime": { diff --git a/service/account/docs/swagger.yaml b/service/account/docs/swagger.yaml index 09962ac40f9..5cb9689df76 100644 --- a/service/account/docs/swagger.yaml +++ b/service/account/docs/swagger.yaml @@ -608,7 +608,7 @@ definitions: example: user-123 type: string type: object - helper.UserBaseReq: + helper.UserTimeRangeReq: properties: endTime: example: "2021-12-01T00:00:00Z" @@ -674,13 +674,6 @@ paths: consumes: - application/json description: Get user account - parameters: - - description: auth request - in: body - name: request - required: true - schema: - $ref: '#/definitions/helper.Auth' produces: - application/json responses: @@ -702,56 +695,11 @@ paths: summary: Get user account tags: - Account - /account/v1alpha1/basic-cost-distribution: - post: - consumes: - - application/json - description: Get basic cost distribution - parameters: - - description: Basic cost distribution request - in: body - name: request - required: true - schema: - $ref: '#/definitions/helper.GetCostAppListReq' - produces: - - application/json - responses: - "200": - description: successfully get basic cost distribution - schema: - additionalProperties: true - type: object - "400": - description: failed to parse basic cost distribution request - schema: - additionalProperties: true - type: object - "401": - description: authenticate error - schema: - additionalProperties: true - type: object - "500": - description: failed to get basic cost distribution - schema: - additionalProperties: true - type: object - summary: Get basic cost distribution - tags: - - BasicCostDistribution /account/v1alpha1/check-permission: post: consumes: - application/json description: Check permission - parameters: - - description: Check permission request - in: body - name: request - required: true - schema: - $ref: '#/definitions/helper.UserBaseReq' produces: - application/json responses: @@ -874,6 +822,44 @@ paths: summary: Get app type list tags: - AppTypeList + /account/v1alpha1/cost-basic-distribution: + post: + consumes: + - application/json + description: Get basic cost distribution + parameters: + - description: Basic cost distribution request + in: body + name: request + required: true + schema: + $ref: '#/definitions/helper.GetCostAppListReq' + produces: + - application/json + responses: + "200": + description: successfully get basic cost distribution + schema: + additionalProperties: true + type: object + "400": + description: failed to parse basic cost distribution request + schema: + additionalProperties: true + type: object + "401": + description: authenticate error + schema: + additionalProperties: true + type: object + "500": + description: failed to get basic cost distribution + schema: + additionalProperties: true + type: object + summary: Get basic cost distribution + tags: + - BasicCostDistribution /account/v1alpha1/cost-overview: post: consumes: @@ -1112,7 +1098,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/helper.UserBaseReq' + $ref: '#/definitions/helper.UserTimeRangeReq' produces: - application/json responses: @@ -1150,7 +1136,7 @@ paths: name: request required: true schema: - $ref: '#/definitions/helper.UserBaseReq' + $ref: '#/definitions/helper.UserTimeRangeReq' produces: - application/json responses: diff --git a/service/account/helper/request.go b/service/account/helper/request.go index ffda39c369c..a798ae3c474 100644 --- a/service/account/helper/request.go +++ b/service/account/helper/request.go @@ -2,7 +2,6 @@ package helper import ( "fmt" - "strings" "time" "github.com/labring/sealos/service/account/common" @@ -92,7 +91,7 @@ type ConsumptionRecordReq struct { AppName string `json:"appName,omitempty" bson:"appName" example:"app"` } -type UserBaseReq struct { +type UserTimeRangeReq struct { // @Summary Start and end time for the request // @Description Start and end time for the request @@ -111,7 +110,7 @@ type AppCostsReq struct { // @JSONSchema OrderID string `json:"orderID,omitempty" bson:"orderID" example:"order-id-1"` - UserBaseReq `json:",inline" bson:",inline"` + UserTimeRangeReq `json:",inline" bson:",inline"` // @Summary Namespace // @Description Namespace @@ -142,7 +141,7 @@ type GetPaymentReq struct { // @Summary Invoiced // @Description Invoiced // @JSONSchema - Invoiced bool `json:"invoiced,omitempty" bson:"invoiced" example:"true"` + Invoiced *bool `json:"invoiced,omitempty" bson:"invoiced" example:"true"` // @Summary Authentication information // @Description Authentication information @@ -358,13 +357,12 @@ func ParseConsumptionRecordReq(c *gin.Context) (*ConsumptionRecordReq, error) { return consumptionRecord, nil } -func ParseUserBaseReq(c *gin.Context) (*UserBaseReq, error) { - userCosts := &UserBaseReq{} +func ParseUserTimeRangeReq(c *gin.Context) (*UserTimeRangeReq, error) { + userCosts := &UserTimeRangeReq{} if err := c.ShouldBindJSON(userCosts); err != nil { return nil, fmt.Errorf("bind json error: %v", err) } setDefaultTimeRange(&userCosts.TimeRange) - userCosts.Owner = strings.TrimPrefix(userCosts.Owner, "ns-") return userCosts, nil } @@ -388,12 +386,11 @@ func ParseAppCostsReq(c *gin.Context) (*AppCostsReq, error) { return nil, fmt.Errorf("bind json error: %v", err) } setDefaultTimeRange(&userCosts.TimeRange) - userCosts.Owner = strings.TrimPrefix(userCosts.Owner, "ns-") return userCosts, nil } type GetTransferRecordReq struct { - UserBaseReq `json:",inline" bson:",inline"` + UserTimeRangeReq `json:",inline" bson:",inline"` // 0: all, 1: in, 2: out // @Summary Type of the request @@ -419,7 +416,6 @@ func ParseGetTransferRecordReq(c *gin.Context) (*GetTransferRecordReq, error) { return nil, fmt.Errorf("bind json error: %v", err) } setDefaultTimeRange(&transferReq.TimeRange) - transferReq.Auth.Owner = strings.TrimPrefix(transferReq.Auth.Owner, "ns-") return transferReq, nil } diff --git a/service/account/router/router.go b/service/account/router/router.go index 653199e8b11..9f57c470d4d 100644 --- a/service/account/router/router.go +++ b/service/account/router/router.go @@ -1,6 +1,7 @@ package router import ( + "context" "fmt" "log" "os" @@ -29,6 +30,11 @@ func RegisterPayRouter() { if err := dao.InitDB(); err != nil { log.Fatalf("Error initializing database: %v", err) } + defer func() { + if err := dao.DBClient.Disconnect(context.Background()); err != nil { + log.Fatalf("Error disconnecting database: %v", err) + } + }() // /account/v1alpha1/{/namespaces | /properties | {/costs | /costs/recharge | /costs/consumption | /costs/properties}} router.Group(helper.GROUP). POST(helper.GetHistoryNamespaces, api.GetBillingHistoryNamespaceList).