package controller import ( "electricity_bill_calc/model" "electricity_bill_calc/repository" "electricity_bill_calc/response" "electricity_bill_calc/security" "electricity_bill_calc/service" "net/http" "strconv" "time" "github.com/gin-gonic/gin" "github.com/shopspring/decimal" ) type _ChargesController struct { Router *gin.Engine } var ChargesController *_ChargesController func InitializeChargesController(router *gin.Engine) { ChargesController = &_ChargesController{ Router: router, } ChargesController.Router.GET("/charges", security.OPSAuthorize, listAllCharges) ChargesController.Router.POST("/charge", security.OPSAuthorize, recordNewCharge) ChargesController.Router.PUT("/charge/:uid/:seq", security.OPSAuthorize, modifyChargeState) } func listAllCharges(c *gin.Context) { result := response.NewResult(c) requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1")) if err != nil { result.NotAccept("查询参数[page]格式不正确。") return } requestKeyword := c.DefaultQuery("keyword", "") requestBeginDate := c.DefaultQuery("begin", "") requestEndDate := c.DefaultQuery("end", "") charges, total, err := repository.ChargeRepo.ListPagedChargeRecord(requestKeyword, requestBeginDate, requestEndDate, requestPage) if err != nil { result.NotFound(err.Error()) return } result.Json( http.StatusOK, "已获取到符合条件的计费记录。", response.NewPagedResponse(requestPage, total).ToMap(), gin.H{"records": charges}, ) } type _NewChargeFormData struct { UserId string `json:"userId" form:"userId"` Fee decimal.NullDecimal `json:"fee" form:"fee"` Discount decimal.NullDecimal `json:"discount" form:"discount"` Amount decimal.NullDecimal `json:"amount" form:"amount"` ChargeTo time.Time `json:"chargeTo" form:"chargeTo" time_format:"simple_date" time_location:"shanghai"` } func recordNewCharge(c *gin.Context) { result := response.NewResult(c) formData := new(_NewChargeFormData) c.BindJSON(formData) currentTime := time.Now() newRecord := &model.UserCharge{ UserId: formData.UserId, Fee: formData.Fee, Discount: formData.Discount, Amount: formData.Amount, Settled: true, SettledAt: ¤tTime, ChargeTo: formData.ChargeTo, } err := service.ChargeService.CreateChargeRecord(newRecord, true) if err != nil { result.Error(http.StatusInternalServerError, err.Error()) return } result.Success("指定用户的服务已延期。") } type _StateChangeFormData struct { Cancelled bool `json:"cancelled"` } func modifyChargeState(c *gin.Context) { result := response.NewResult(c) formData := new(_StateChangeFormData) c.BindJSON(formData) requestUserID := c.Param("uid") requestChargeSeq, err := strconv.Atoi(c.Param("seq")) if err != nil { result.Error(http.StatusNotAcceptable, "参数[记录流水号]解析错误。") return } err = service.ChargeService.CancelCharge(int64(requestChargeSeq), requestUserID) if err != nil { result.Error(http.StatusInternalServerError, err.Error()) return } result.Success("指定用户服务延期记录状态已经更新。") }