Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Region amount api #5070

Merged
merged 3 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 102 additions & 1 deletion service/account/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -76,7 +77,7 @@ func GetProperties(c *gin.Context) {
// Get the properties from the database
properties, err := dao.DBClient.GetProperties()
if err != nil {
c.JSON(http.StatusInternalServerError, fmt.Errorf(fmt.Sprintf("failed to get properties: %v", err)))
c.JSON(http.StatusInternalServerError, fmt.Errorf("failed to get properties: %v", err))
return
}
c.JSON(http.StatusOK, helper.GetPropertiesResp{
Expand Down Expand Up @@ -119,6 +120,106 @@ func GetConsumptionAmount(c *gin.Context) {
})
}

// GetAllRegionConsumptionAmount
// @Summary Get all region consumption amount
// @Description Get all region consumption amount within a specified time range
// @Tags ConsumptionAmount
// @Accept json
// @Produce json
// @Param request body helper.ConsumptionRecordReq true "All region consumption amount request"
// @Success 200 {object} map[string]interface{} "successfully retrieved all region consumption amount"
// @Failure 400 {object} map[string]interface{} "failed to parse all region consumption amount request"
// @Failure 401 {object} map[string]interface{} "authenticate error"
// @Failure 500 {object} map[string]interface{} "failed to get all region consumption amount"
// @Router /account/v1alpha1/costs/all-region-consumption [post]
func GetAllRegionConsumptionAmount(c *gin.Context) {
req, err := helper.ParseConsumptionRecordReq(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to parse all region consumption amount request: %v", err)})
return
}
if err := authenticateRequest(c, req); err != nil {
c.JSON(http.StatusUnauthorized, helper.ErrorMessage{Error: fmt.Sprintf("authenticate error : %v", err)})
return
}
regionAmount := make(map[string]int64)
allAmount := int64(0)
for _, region := range dao.Cfg.Regions {
if region.Domain == dao.Cfg.LocalRegionDomain {
amount, err := dao.DBClient.GetConsumptionAmount(*req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to get consumption amount : %v", err)})
return
}
regionAmount[region.Domain] = amount
allAmount += amount
continue
}
svc := region.AccountSvc
url := fmt.Sprintf("https://%s%s%s", svc, helper.GROUP, helper.GetConsumptionAmount)
body, err := json.Marshal(&helper.ConsumptionRecordReq{
TimeRange: req.TimeRange,
AppType: req.AppType,
Namespace: req.Namespace,
AppName: req.AppName,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to marshal request: %v", err)})
return
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: os.Getenv("INSECURE_VERIFY") != "true", MinVersion: tls.VersionTLS13},
}
client := &http.Client{Transport: tr}
req2, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to create request: %v", err)})
return
}
token, err := dao.JwtMgr.GenerateToken(helper.JwtUser{
UserID: req.GetAuth().UserID,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to generate token: %v", err)})
return
}
req2.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req2.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req2)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to send request: %v", err)})
return
}
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read response body: %v", err)})
return
}
var respData map[string]interface{}
err = json.Unmarshal(body, &respData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to unmarshal response body: %v", err)})
return
}
if resp.StatusCode != http.StatusOK {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to get response, status code: %d, msg: %s", resp.StatusCode, respData["error"])})
return
}
amountResp, ok := respData["amount"].(float64)
if !ok {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("amount is not an integer, is %T", respData["amount"])})
return
}
regionAmount[region.Domain] = int64(amountResp)
allAmount += int64(amountResp)
}
c.JSON(http.StatusOK, gin.H{
"regionAmount": regionAmount,
"allAmount": allAmount,
})
}

// GetPayment
// @Summary Get user payment
// @Description Get user payment within a specified time range
Expand Down
16 changes: 8 additions & 8 deletions service/account/dao/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func (m *MongoDB) GetCosts(req helper.ConsumptionRecordReq) (common.TimeCostsMap
}

pipeline := bson.A{
bson.D{{Key: "$match", Value: matchValue}},
bson.D{primitive.E{Key: "$match", Value: matchValue}},
}

project := bson.D{
Expand All @@ -217,15 +217,15 @@ func (m *MongoDB) GetCosts(req helper.ConsumptionRecordReq) (common.TimeCostsMap
}
if appType != "" && appName != "" && appType != resources.AppStore {
pipeline = append(pipeline,
bson.D{{Key: "$unwind", Value: "$app_costs"}},
bson.D{{Key: "$match", Value: bson.D{{Key: "app_costs.name", Value: appName}}}},
bson.D{primitive.E{Key: "$unwind", Value: "$app_costs"}},
bson.D{primitive.E{Key: "$match", Value: bson.D{{Key: "app_costs.name", Value: appName}}}},
)
project[1] = primitive.E{Key: "amount", Value: "$app_costs.amount"}
}

pipeline = append(pipeline,
bson.D{{Key: "$sort", Value: bson.D{{Key: "time", Value: 1}}}},
bson.D{{Key: "$project", Value: project}},
bson.D{primitive.E{Key: "$sort", Value: bson.D{{Key: "time", Value: 1}}}},
bson.D{primitive.E{Key: "$project", Value: project}},
)

cursor, err := m.getBillingCollection().Aggregate(context.Background(), pipeline)
Expand Down Expand Up @@ -1343,7 +1343,7 @@ func (m *Account) ApplyInvoice(req *helper.ApplyInvoiceReq) (invoice types.Invoi
return
}
amount := int64(0)
var paymentIds []string
var paymentIDs []string
var invoicePayments []types.InvoicePayment
id, err := gonanoid.New(12)
if err != nil {
Expand All @@ -1352,7 +1352,7 @@ func (m *Account) ApplyInvoice(req *helper.ApplyInvoiceReq) (invoice types.Invoi
}
for i := range payments {
amount += payments[i].Amount
paymentIds = append(paymentIds, payments[i].ID)
paymentIDs = append(paymentIDs, payments[i].ID)
invoicePayments = append(invoicePayments, types.InvoicePayment{
PaymentID: payments[i].ID,
Amount: payments[i].Amount,
Expand All @@ -1371,7 +1371,7 @@ func (m *Account) ApplyInvoice(req *helper.ApplyInvoiceReq) (invoice types.Invoi
// save invoice with transaction
if err = m.ck.DB.Transaction(
func(tx *gorm.DB) error {
if err = m.ck.SetPaymentInvoiceWithDB(&types.UserQueryOpts{ID: req.UserID}, paymentIds, tx); err != nil {
if err = m.ck.SetPaymentInvoiceWithDB(&types.UserQueryOpts{ID: req.UserID}, paymentIDs, tx); err != nil {
return fmt.Errorf("failed to set payment invoice: %v", err)
}
if err = m.ck.CreateInvoiceWithDB(&invoice, tx); err != nil {
Expand Down
76 changes: 73 additions & 3 deletions service/account/docs/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,62 @@ const docTemplate = `{
}
}
},
"/account/v1alpha1/costs/all-region-consumption": {
"post": {
"description": "Get all region consumption amount within a specified time range",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"ConsumptionAmount"
],
"summary": "Get all region consumption amount",
"parameters": [
{
"description": "All region consumption amount request",
"name": "request",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/helper.ConsumptionRecordReq"
}
}
],
"responses": {
"200": {
"description": "successfully retrieved all region consumption amount",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"400": {
"description": "failed to parse all region consumption amount request",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"401": {
"description": "authenticate error",
"schema": {
"type": "object",
"additionalProperties": true
}
},
"500": {
"description": "failed to get all region consumption amount",
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
},
"/account/v1alpha1/costs/app": {
"post": {
"description": "Get app costs within a specified time range",
Expand Down Expand Up @@ -1712,6 +1768,11 @@ const docTemplate = `{
"type": "string",
"example": "2021-12-01T00:00:00Z"
},
"invoiced": {
"description": "@Summary Invoiced\n@Description Invoiced\n@JSONSchema",
"type": "boolean",
"example": true
},
"kubeConfig": {
"type": "string"
},
Expand Down Expand Up @@ -1868,8 +1929,7 @@ const docTemplate = `{
"type": "object",
"required": [
"invoiceIDList",
"status",
"token"
"status"
],
"properties": {
"invoiceIDList": {
Expand All @@ -1883,15 +1943,25 @@ const docTemplate = `{
"\"invoice-id-2\"]"
]
},
"kubeConfig": {
"type": "string"
},
"owner": {
"type": "string",
"example": "admin"
},
"status": {
"description": "Invoice status\n@Summary Invoice status\n@Description Invoice status\n@JSONSchema required",
"type": "string",
"example": "COMPLETED,REJECTED,PENDING"
},
"token": {
"description": "@Summary Authentication token\n@Description Authentication token\n@JSONSchema required",
"type": "string",
"example": "token"
},
"userID": {
"type": "string",
"example": "admin"
}
}
},
Expand Down
Loading
Loading