package controller import ( "fmt" "net/http" "strconv" "ezops/model" "ezops/pkg/billingsync" "github.com/gin-gonic/gin" ) // syncBillingRequest 同步账单请求(可选指定账号) // Logan.Li type syncBillingRequest struct { AccountID *uint `json:"account_id"` Date string `json:"date"` // YYYY-MM-DD,默认昨日 } // SyncYesterdayBillings 从云账号 AK 同步指定日期(默认昨日)账单 // Logan.Li // POST /cloud-billings/sync func (h *BillingHandler) SyncYesterdayBillings(c *gin.Context) { var req syncBillingRequest _ = c.ShouldBindJSON(&req) billingDate := req.Date if billingDate == "" { billingDate = billingsync.Yesterday() } if len(billingDate) != 10 { c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "date 格式应为 YYYY-MM-DD"}) return } result := billingsync.SyncDate(h.db, billingDate, req.AccountID) if result.Accounts == 0 { c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "没有可同步的活跃云账号,请先在云账号管理中添加 AK"}) return } msg := fmt.Sprintf("同步完成:新增 %d 条,更新 %d 条", result.Created, result.Updated) if len(result.Errors) > 0 { msg += fmt.Sprintf(",%d 个账号失败", len(result.Errors)) } c.JSON(http.StatusOK, model.Response{ Code: 200, Message: msg, Data: result, }) } // SyncAccountBilling 同步单个云账号账单 // POST /cloud-accounts/:id/sync-billing func (h *BillingHandler) SyncAccountBilling(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) if id <= 0 { c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效账号 ID"}) return } var req struct { Date string `json:"date"` } _ = c.ShouldBindJSON(&req) billingDate := req.Date if billingDate == "" { billingDate = billingsync.Yesterday() } uid := uint(id) result := billingsync.SyncDate(h.db, billingDate, &uid) if result.Accounts == 0 { c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云账号不存在或未激活"}) return } msg := fmt.Sprintf("同步完成:新增 %d 条,更新 %d 条", result.Created, result.Updated) if len(result.Errors) > 0 { msg = "同步失败: " + result.Errors[0] } c.JSON(http.StatusOK, model.Response{Code: 200, Message: msg, Data: result}) }