diff --git a/controller/abstract.go b/controller/abstract.go index 749244e..8d34e1c 100644 --- a/controller/abstract.go +++ b/controller/abstract.go @@ -4,12 +4,12 @@ import ( "electricity_bill_calc/exceptions" "electricity_bill_calc/model" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" ) -func _retreiveSession(c *gin.Context) (*model.Session, error) { - session, exists := c.Get("session") - if !exists { +func _retreiveSession(c *fiber.Ctx) (*model.Session, error) { + session := c.Locals("session") + if session == nil { return nil, exceptions.NewUnauthorizedError("用户会话不存在") } userSession, ok := session.(*model.Session) diff --git a/controller/charge.go b/controller/charge.go index a62c2fd..a2b8d43 100644 --- a/controller/charge.go +++ b/controller/charge.go @@ -80,7 +80,7 @@ func modifyChargeState(c *fiber.Ctx) error { if err := c.BodyParser(formData); err != nil { return result.UnableToParse("无法解析提交的数据。") } - requestUserID := c.Params("uid", "") + requestUserID := c.Params("uid") requestChargeSeq, err := strconv.Atoi(c.Params("seq", "-1")) if err != nil || requestChargeSeq == -1 { return result.Error(http.StatusNotAcceptable, "参数[记录流水号]解析错误。") diff --git a/controller/end_user.go b/controller/end_user.go index 269c538..9bb6449 100644 --- a/controller/end_user.go +++ b/controller/end_user.go @@ -12,77 +12,70 @@ import ( "net/http" "strconv" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" "github.com/samber/lo" "github.com/shopspring/decimal" ) -func InitializeEndUserController(router *gin.Engine) { - router.GET("/report/:rid/submeter", security.EnterpriseAuthorize, fetchEndUserInReport) - router.GET("/report/:rid/meter/template", downloadEndUserRegisterTemplate) - router.POST("/report/:rid/meter/batch", security.EnterpriseAuthorize, uploadEndUserRegisterTemplate) - router.PUT("/report/:rid/submeter/:pid/:mid", security.EnterpriseAuthorize, modifyEndUserRegisterRecord) - router.GET("/end/user/adjusts", security.MustAuthenticated, statEndUserInPeriod) +func InitializeEndUserController(router *fiber.App) { + router.Get("/report/:rid/submeter", security.EnterpriseAuthorize, fetchEndUserInReport) + router.Get("/report/:rid/meter/template", downloadEndUserRegisterTemplate) + router.Post("/report/:rid/meter/batch", security.EnterpriseAuthorize, uploadEndUserRegisterTemplate) + router.Put("/report/:rid/submeter/:pid/:mid", security.EnterpriseAuthorize, modifyEndUserRegisterRecord) + router.Get("/end/user/adjusts", security.MustAuthenticated, statEndUserInPeriod) } -func fetchEndUserInReport(c *gin.Context) { +func fetchEndUserInReport(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } - keyword := c.DefaultQuery("keyword", "") - requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1")) + keyword := c.Query("keyword") + requestPage, err := strconv.Atoi(c.Query("page", "1")) if err != nil { - result.NotAccept("查询参数[page]格式不正确。") - return + return result.NotAccept("查询参数[page]格式不正确。") } endUsers, totalItem, err := service.EndUserService.SearchEndUserRecord(requestReportId, keyword, requestPage) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Json( + return result.Json( http.StatusOK, "已获取到符合条件的终端用户集合", response.NewPagedResponse(requestPage, totalItem).ToMap(), - gin.H{"meters": endUsers}, + fiber.Map{"meters": endUsers}, ) } -func downloadEndUserRegisterTemplate(c *gin.Context) { +func downloadEndUserRegisterTemplate(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") + requestReportId := c.Params("rid") users, err := service.EndUserService.AllEndUserRecord(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } reportIndex, err := service.ReportService.RetreiveReportIndex(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } park, err := service.ParkService.FetchParkDetail(reportIndex.ParkId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } meterType, err := service.ReportService.RetreiveParkEndUserMeterType(requestReportId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if meterType == -1 { - result.NotFound("未能确定用户表计类型。") - return + return result.NotFound("未能确定用户表计类型。") } c.Status(http.StatusOK) - c.Header("Content-Type", "application/octet-stream") - c.Header("Content-Transfer-Encoding", "binary") - c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=抄表记录-%s-%s.xlsx", park.Name, reportIndex.Period.Format("2006-01"))) + c.Set("Content-Type", "application/octet-stream") + c.Set("Content-Transfer-Encoding", "binary") + c.Set("Content-Disposition", fmt.Sprintf("attachment; filename=抄表记录-%s-%s.xlsx", park.Name, reportIndex.Period.Format("2006-01"))) gen := lo.Ternary[excel.ExcelTemplateGenerator]( meterType == 0, @@ -91,50 +84,45 @@ func downloadEndUserRegisterTemplate(c *gin.Context) { ) defer gen.Close() gen.WriteMeterData(users) - gen.WriteTo(c.Writer) + gen.WriteTo(c.Response().BodyWriter()) + return nil } -func uploadEndUserRegisterTemplate(c *gin.Context) { +func uploadEndUserRegisterTemplate(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } meterType, err := service.ReportService.RetreiveParkEndUserMeterType(requestReportId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if meterType == -1 { - result.NotFound("未能确定用户表计类型。") - return + return result.NotFound("未能确定用户表计类型。") } uploadedFile, err := c.FormFile("data") if err != nil { - result.NotAccept("没有接收到上传的档案文件。") - return + return result.NotAccept("没有接收到上传的档案文件。") } archiveFile, err := uploadedFile.Open() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if meterType == 0 { errs := service.EndUserService.BatchImportNonPVRegister(requestReportId, archiveFile) if errs.Len() > 0 { - result.Json(http.StatusInternalServerError, "上传抄表文件存在解析错误", gin.H{"errors": errs.Errs}) - return + return result.Json(http.StatusInternalServerError, "上传抄表文件存在解析错误", fiber.Map{"errors": errs.Errs}) } } else { errs := service.EndUserService.BatchImportPVRegister(requestReportId, archiveFile) if errs.Len() > 0 { - result.Json(http.StatusInternalServerError, "上传抄表文件存在解析错误", gin.H{"errors": errs.Errs}) - return + return result.Json(http.StatusInternalServerError, "上传抄表文件存在解析错误", fiber.Map{"errors": errs.Errs}) } } - result.Json(http.StatusOK, "已经成功完成抄表记录的导入。", gin.H{"errors": make([]error, 0)}) + return result.Json(http.StatusOK, "已经成功完成抄表记录的导入。", fiber.Map{"errors": make([]error, 0)}) } type ModifyEndUserRegisterFormData struct { @@ -148,29 +136,28 @@ type ModifyEndUserRegisterFormData struct { AdjustValley decimal.NullDecimal `json:"adjustValley" form:"adjustValley"` } -func modifyEndUserRegisterRecord(c *gin.Context) { +func modifyEndUserRegisterRecord(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } meterType, err := service.ReportService.RetreiveParkEndUserMeterType(requestReportId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if meterType == -1 { - result.NotFound("未能确定用户表计类型。") - return + return result.NotFound("未能确定用户表计类型。") } - requestParkId := c.Param("pid") - requestMeterId := c.Param("mid") + requestParkId := c.Params("pid") + requestMeterId := c.Params("mid") formData := new(ModifyEndUserRegisterFormData) - c.BindJSON(formData) + if err := c.BodyParser(formData); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } meter, err := service.EndUserService.FetchSpecificEndUserRecord(requestReportId, requestParkId, requestMeterId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } if formData.CurrentPeriodOverall.Valid { meter.CurrentPeriodOverall = formData.CurrentPeriodOverall.Decimal @@ -198,61 +185,53 @@ func modifyEndUserRegisterRecord(c *gin.Context) { } valid, err := meter.Validate() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if !valid { - result.NotAccept("抄表数据合法性验证失败。") - return + return result.NotAccept("抄表数据合法性验证失败。") } ctx, cancel := global.TimeoutContext() defer cancel() tx, err := global.DB.BeginTx(ctx, &sql.TxOptions{}) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } err = service.EndUserService.UpdateEndUserRegisterRecord(&tx, &ctx, *meter) if err != nil { tx.Rollback() - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } err = tx.Commit() if err != nil { tx.Rollback() - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success("指定终端用户抄表记录已经更新。") + return result.Success("指定终端用户抄表记录已经更新。") } -func statEndUserInPeriod(c *gin.Context) { +func statEndUserInPeriod(c *fiber.Ctx) error { result := response.NewResult(c) session, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } requestUser := lo. If(session.Type == model.USER_TYPE_ENT, session.Uid). - Else(c.DefaultQuery("user", "")) - requestPark := c.DefaultQuery("park", "") + Else(c.Query("user")) + requestPark := c.Query("park") if len(requestPark) > 0 && session.Type == model.USER_TYPE_ENT { - if !ensureParkBelongs(c, result, requestPark) { - result.Unauthorized("不能获取不属于自己的园区。") - return + if ensure, err := ensureParkBelongs(c, &result, requestPark); !ensure { + return err } } - startDate := c.DefaultQuery("start", "") - endDate := c.DefaultQuery("end", "") + startDate := c.Query("start") + endDate := c.Query("end") stat, err := service.EndUserService.StatEndUserRecordInPeriod(requestUser, requestPark, startDate, endDate) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success( + return result.Success( "已经完成终端用户的费用统计", - gin.H{"details": stat}, + fiber.Map{"details": stat}, ) } diff --git a/controller/region.go b/controller/region.go index dfb35b6..f509c54 100644 --- a/controller/region.go +++ b/controller/region.go @@ -5,40 +5,36 @@ import ( "electricity_bill_calc/service" "net/http" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" ) -func InitializeRegionController(router *gin.Engine) { - router.GET("/region/:rid", fetchRegions) - router.GET("/regions/:rid", fetchAllLeveledRegions) +func InitializeRegionController(router *fiber.App) { + router.Get("/region/:rid", fetchRegions) + router.Get("/regions/:rid", fetchAllLeveledRegions) } -func fetchRegions(c *gin.Context) { +func fetchRegions(c *fiber.Ctx) error { result := response.NewResult(c) - requestParentId := c.Param("rid") + requestParentId := c.Params("rid") regions, err := service.RegionService.FetchSubRegions(requestParentId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if len(regions) == 0 { - result.Json(http.StatusNotFound, "未能获取到相关的行政区划。", gin.H{"regions": make([]string, 0)}) - return + return result.Json(http.StatusNotFound, "未能获取到相关的行政区划。", fiber.Map{"regions": make([]string, 0)}) } - result.Json(http.StatusOK, "已经获取到相关的行政区划。", gin.H{"regions": regions}) + return result.Json(http.StatusOK, "已经获取到相关的行政区划。", fiber.Map{"regions": regions}) } -func fetchAllLeveledRegions(c *gin.Context) { +func fetchAllLeveledRegions(c *fiber.Ctx) error { result := response.NewResult(c) - requestRegionCode := c.Param("rid") + requestRegionCode := c.Params("rid") regions, err := service.RegionService.FetchAllParentRegions(requestRegionCode) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if len(regions) == 0 { - result.Json(http.StatusNotFound, "未能获取到相关的行政区划。", gin.H{"regions": make([]string, 0)}) - return + return result.Json(http.StatusNotFound, "未能获取到相关的行政区划。", fiber.Map{"regions": make([]string, 0)}) } - result.Json(http.StatusOK, "以及获取到相关的行政区划。", gin.H{"regions": regions}) + return result.Json(http.StatusOK, "以及获取到相关的行政区划。", fiber.Map{"regions": regions}) } diff --git a/controller/report.go b/controller/report.go index 63a91ca..6cf63c0 100644 --- a/controller/report.go +++ b/controller/report.go @@ -11,124 +11,111 @@ import ( "strconv" "time" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" "github.com/jinzhu/copier" "github.com/samber/lo" "github.com/shopspring/decimal" ) -func InitializeReportController(router *gin.Engine) { - router.GET("/reports/with/drafts", security.EnterpriseAuthorize, fetchNewestReportOfParkWithDraft) - router.POST("/park/:pid/report", security.EnterpriseAuthorize, initializeNewReport) - router.GET("/report/:rid/step/state", security.EnterpriseAuthorize, fetchReportStepStates) - router.GET("/report/:rid/summary", security.EnterpriseAuthorize, fetchReportParkSummary) - router.PUT("/report/:rid/summary", security.EnterpriseAuthorize, fillReportSummary) - router.GET("/report/:rid/summary/calculate", security.EnterpriseAuthorize, testCalculateReportSummary) - router.POST("/report/:rid/summary/calculate", security.EnterpriseAuthorize, progressReportSummary) - router.PUT("/report/:rid/step/meter/register", security.EnterpriseAuthorize, progressEndUserRegister) - router.POST("/report/:rid/publish", security.EnterpriseAuthorize, publishReport) - router.GET("/reports", security.MustAuthenticated, searchReports) - router.GET("/report/:rid", security.MustAuthenticated, fetchReportPublicity) - router.POST("/report/:rid/calculate", security.EnterpriseAuthorize, calculateReport) +func InitializeReportController(router *fiber.App) { + router.Get("/reports/with/drafts", security.EnterpriseAuthorize, fetchNewestReportOfParkWithDraft) + router.Post("/park/:pid/report", security.EnterpriseAuthorize, initializeNewReport) + router.Get("/report/:rid/step/state", security.EnterpriseAuthorize, fetchReportStepStates) + router.Get("/report/:rid/summary", security.EnterpriseAuthorize, fetchReportParkSummary) + router.Put("/report/:rid/summary", security.EnterpriseAuthorize, fillReportSummary) + router.Get("/report/:rid/summary/calculate", security.EnterpriseAuthorize, testCalculateReportSummary) + router.Post("/report/:rid/summary/calculate", security.EnterpriseAuthorize, progressReportSummary) + router.Put("/report/:rid/step/meter/register", security.EnterpriseAuthorize, progressEndUserRegister) + router.Post("/report/:rid/publish", security.EnterpriseAuthorize, publishReport) + router.Get("/reports", security.MustAuthenticated, searchReports) + router.Get("/report/:rid", security.MustAuthenticated, fetchReportPublicity) + router.Post("/report/:rid/calculate", security.EnterpriseAuthorize, calculateReport) } -func ensureReportBelongs(c *gin.Context, result *response.Result, requestReportId string) bool { +func ensureReportBelongs(c *fiber.Ctx, result *response.Result, requestReportId string) (bool, error) { _, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return false + return false, result.Unauthorized(err.Error()) } requestReport, err := service.ReportService.RetreiveReportIndex(requestReportId) if err != nil { - result.NotFound(err.Error()) - return false + return false, result.NotFound(err.Error()) } if requestReport == nil { - result.NotFound("指定报表未能找到。") - return false + return false, result.NotFound("指定报表未能找到。") } return ensureParkBelongs(c, result, requestReport.ParkId) } -func fetchNewestReportOfParkWithDraft(c *gin.Context) { +func fetchNewestReportOfParkWithDraft(c *fiber.Ctx) error { result := response.NewResult(c) userSession, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } parks, err := service.ReportService.FetchParksWithNewestReport(userSession.Uid) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Json(http.StatusOK, "已获取到指定用户下所有园区的最新报表记录。", gin.H{"parks": parks}) + return result.Json(http.StatusOK, "已获取到指定用户下所有园区的最新报表记录。", fiber.Map{"parks": parks}) } -func initializeNewReport(c *gin.Context) { +func initializeNewReport(c *fiber.Ctx) error { result := response.NewResult(c) - requestParkId := c.Param("pid") + requestParkId := c.Params("pid") userSession, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } - if !ensureParkBelongs(c, result, requestParkId) { - return + if ensure, err := ensureParkBelongs(c, &result, requestParkId); !ensure { + return err } requestPeriod := c.Query("period") reportPeriod, err := time.Parse("2006-01", requestPeriod) if err != nil { - result.NotAccept("提供的初始化期数格式不正确。") - return + return result.NotAccept("提供的初始化期数格式不正确。") } valid, err := service.ReportService.IsNewPeriodValid(userSession.Uid, requestParkId, reportPeriod) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if !valid { - result.NotAccept("只能初始化已发布报表下一个月份的新报表。") - return + return result.NotAccept("只能初始化已发布报表下一个月份的新报表。") } newId, err := service.ReportService.InitializeNewReport(requestParkId, reportPeriod) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Created("新一期报表初始化成功。", gin.H{"reportId": newId}) + return result.Created("新一期报表初始化成功。", fiber.Map{"reportId": newId}) } -func fetchReportStepStates(c *gin.Context) { +func fetchReportStepStates(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } requestReport, err := service.ReportService.RetreiveReportIndex(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Json(http.StatusOK, "已经获取到指定报表的填写状态。", gin.H{"steps": requestReport.StepState}) + return result.Json(http.StatusOK, "已经获取到指定报表的填写状态。", fiber.Map{"steps": requestReport.StepState}) } -func fetchReportParkSummary(c *gin.Context) { +func fetchReportParkSummary(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } summary, err := service.ReportService.RetreiveReportSummary(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } if summary == nil { - result.NotFound("指定报表未能找到。") - return + return result.NotFound("指定报表未能找到。") } - result.Json(http.StatusOK, "已经获取到指定报表中的园区概况。", gin.H{"summary": summary}) + return result.Json(http.StatusOK, "已经获取到指定报表中的园区概况。", fiber.Map{"summary": summary}) } type ReportSummaryFormData struct { @@ -144,176 +131,171 @@ type ReportSummaryFormData struct { AdjustFee decimal.Decimal `json:"adjustFee" from:"adjustFee"` } -func fillReportSummary(c *gin.Context) { +func fillReportSummary(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } formData := new(ReportSummaryFormData) - c.BindJSON(formData) + if err := c.BodyParser(formData); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } originSummary, err := service.ReportService.RetreiveReportSummary(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } copier.Copy(originSummary, formData) originSummary.ReportId = requestReportId err = service.ReportService.UpdateReportSummary(originSummary) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Updated("指定电费公示报表中的园区概况基本数据已经完成更新。") + return result.Updated("指定电费公示报表中的园区概况基本数据已经完成更新。") } -func testCalculateReportSummary(c *gin.Context) { +func testCalculateReportSummary(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } summary, err := service.ReportService.RetreiveReportSummary(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } summary.CalculatePrices() calcResults := tools.ConvertStructToMap(summary) - result.Json(http.StatusOK, "已完成园区概况的试计算。", gin.H{"result": lo.PickByKeys(calcResults, []string{"overallPrice", "criticalPrice", "peakPrice", "flat", "flatFee", "flatPrice", "valleyPrice", "consumptionFee"})}) + return result.Json( + http.StatusOK, + "已完成园区概况的试计算。", + fiber.Map{ + "result": lo.PickByKeys( + calcResults, + []string{"overallPrice", "criticalPrice", "peakPrice", "flat", "flatFee", "flatPrice", "valleyPrice", "consumptionFee"}, + ), + }, + ) } -func progressReportSummary(c *gin.Context) { +func progressReportSummary(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } err := service.ReportService.CalculateSummaryAndFinishStep(requestReportId) if err != nil { if nfErr, ok := err.(exceptions.NotFoundError); ok { - result.NotFound(nfErr.Error()) + return result.NotFound(nfErr.Error()) } else { - result.Error(http.StatusInternalServerError, err.Error()) + return result.Error(http.StatusInternalServerError, err.Error()) } - return } - result.Success("已经完成园区概况的计算,并可以进行到下一步骤。") + return result.Success("已经完成园区概况的计算,并可以进行到下一步骤。") } -func progressEndUserRegister(c *gin.Context) { +func progressEndUserRegister(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } report, err := service.ReportService.RetreiveReportIndex(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } err = service.ReportService.ProgressReportRegisterEndUser(*report) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success("终端用户抄表编辑步骤已经完成。") + return result.Success("终端用户抄表编辑步骤已经完成。") } -func publishReport(c *gin.Context) { +func publishReport(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } report, err := service.ReportService.RetreiveReportIndex(requestReportId) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } err = service.ReportService.PublishReport(*report) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success("指定的公示报表已经发布。") + return result.Success("指定的公示报表已经发布。") } -func searchReports(c *gin.Context) { +func searchReports(c *fiber.Ctx) error { result := response.NewResult(c) session, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } requestUser := lo. If(session.Type == model.USER_TYPE_ENT, session.Uid). - Else(c.DefaultQuery("user", "")) - requestPark := c.DefaultQuery("park", "") + Else(c.Query("user")) + requestPark := c.Query("park") if len(requestPark) > 0 && session.Type == model.USER_TYPE_ENT { - if !ensureParkBelongs(c, result, requestPark) { - return + if ensure, err := ensureParkBelongs(c, &result, requestPark); !ensure { + return err } } - requestPeriodString := c.DefaultQuery("period", "") + requestPeriodString := c.Query("period") var requestPeriod *time.Time = nil if len(requestPeriodString) > 0 { parsedPeriod, err := time.Parse("2006-01", requestPeriodString) if err != nil { - result.NotAccept("参数[period]的格式不正确。") - return + return result.NotAccept("参数[period]的格式不正确。") } requestPeriod = lo.ToPtr(parsedPeriod) } - requestKeyword := c.DefaultQuery("keyword", "") - requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1")) + requestKeyword := c.Query("keyword") + requestPage, err := strconv.Atoi(c.Query("page", "1")) if err != nil { - result.NotAccept("查询参数[page]格式不正确。") - return + return result.NotAccept("查询参数[page]格式不正确。") } - requestAllReports, err := strconv.ParseBool(c.DefaultQuery("all", "false")) + requestAllReports, err := strconv.ParseBool(c.Query("all", "false")) if err != nil { - result.NotAccept("查询参数[all]格式不正确。") - return + return result.NotAccept("查询参数[all]格式不正确。") } records, totalItems, err := service.ReportService.SearchReport(requestUser, requestPark, requestKeyword, requestPeriod, requestPage, !requestAllReports) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Success( + return result.Success( "已经取得符合条件的公示报表记录。", response.NewPagedResponse(requestPage, totalItems).ToMap(), - gin.H{"reports": records}, + fiber.Map{"reports": records}, ) } -func fetchReportPublicity(c *gin.Context) { +func fetchReportPublicity(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") + requestReportId := c.Params("rid") publicity, err := service.ReportService.AssembleReportPublicity(requestReportId) if err != nil { if nfErr, ok := err.(exceptions.NotFoundError); ok { - result.NotFound(nfErr.Error()) - return + return result.NotFound(nfErr.Error()) } else { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } - result.Success("已经取得指定公示报表的发布版本。", tools.ConvertStructToMap(publicity)) + return result.Success("已经取得指定公示报表的发布版本。", tools.ConvertStructToMap(publicity)) } -func calculateReport(c *gin.Context) { +func calculateReport(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("rid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } err := service.CalculateService.ComprehensivelyCalculateReport(requestReportId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success("指定公示报表中的数据已经计算完毕。") + return result.Success("指定公示报表中的数据已经计算完毕。") } diff --git a/controller/statistics.go b/controller/statistics.go index 9a783b7..413efeb 100644 --- a/controller/statistics.go +++ b/controller/statistics.go @@ -7,34 +7,32 @@ import ( "electricity_bill_calc/service" "net/http" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" ) -func InitializeStatisticsController(router *gin.Engine) { - router.GET("/audits", security.OPSAuthorize, currentAuditAmount) - router.GET("/stat/reports", security.MustAuthenticated, statReports) +func InitializeStatisticsController(router *fiber.App) { + router.Get("/audits", security.OPSAuthorize, currentAuditAmount) + router.Get("/stat/reports", security.MustAuthenticated, statReports) } -func currentAuditAmount(c *gin.Context) { +func currentAuditAmount(c *fiber.Ctx) error { result := response.NewResult(c) amount, err := service.WithdrawService.AuditWaits() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Json(http.StatusOK, "已经获取到指定的统计信息。", gin.H{ + return result.Json(http.StatusOK, "已经获取到指定的统计信息。", fiber.Map{ "amounts": map[string]int64{ "withdraw": amount, }, }) } -func statReports(c *gin.Context) { +func statReports(c *fiber.Ctx) error { result := response.NewResult(c) session, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } var ( enterprises int64 = 0 @@ -44,34 +42,29 @@ func statReports(c *gin.Context) { if session.Type != 0 { enterprises, err = service.StatisticsService.EnabledEnterprises() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } parks, err = service.StatisticsService.EnabledParks() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } reports, err = service.StatisticsService.ParksNewestState() if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } else { parks, err = service.StatisticsService.EnabledParks(session.Uid) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } reports, err = service.StatisticsService.ParksNewestState(session.Uid) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } - result.Json(http.StatusOK, "已经完成园区报告的统计。", gin.H{ - "statistics": gin.H{ + return result.Json(http.StatusOK, "已经完成园区报告的统计。", fiber.Map{ + "statistics": fiber.Map{ "enterprises": enterprises, "parks": parks, "reports": reports, diff --git a/controller/user.go b/controller/user.go index d67386a..7edf43b 100644 --- a/controller/user.go +++ b/controller/user.go @@ -13,23 +13,23 @@ import ( "net/http" "strconv" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" "github.com/shopspring/decimal" ) -func InitializeUserController(router *gin.Engine) { - router.DELETE("/password/:uid", security.OPSAuthorize, invalidUserPassword) - router.DELETE("/login", security.MustAuthenticated, logout) - router.PUT("/password", resetUserPassword) - router.GET("/accounts", security.OPSAuthorize, listPagedUser) - router.POST("/login", login) - router.PUT("/account/enabled/state", security.OPSAuthorize, switchUserEnabling) - router.POST("/account", security.OPSAuthorize, createOPSAndManagementAccount) - router.GET("/account/:uid", security.MustAuthenticated, getUserDetail) - router.POST("/enterprise", security.OPSAuthorize, createEnterpriseAccount) - router.PUT("/account/:uid", security.OPSAuthorize, modifyAccountDetail) - router.GET("/enterprise/quick/search", security.OPSAuthorize, quickSearchEnterprise) - router.GET("/expiration", security.EnterpriseAuthorize, fetchExpiration) +func InitializeUserController(router *fiber.App) { + router.Delete("/password/:uid", security.OPSAuthorize, invalidUserPassword) + router.Delete("/login", security.MustAuthenticated, logout) + router.Put("/password", resetUserPassword) + router.Get("/accounts", security.OPSAuthorize, listPagedUser) + router.Post("/login", login) + router.Put("/account/enabled/state", security.OPSAuthorize, switchUserEnabling) + router.Post("/account", security.OPSAuthorize, createOPSAndManagementAccount) + router.Get("/account/:uid", security.MustAuthenticated, getUserDetail) + router.Post("/enterprise", security.OPSAuthorize, createEnterpriseAccount) + router.Put("/account/:uid", security.OPSAuthorize, modifyAccountDetail) + router.Get("/enterprise/quick/search", security.OPSAuthorize, quickSearchEnterprise) + router.Get("/expiration", security.EnterpriseAuthorize, fetchExpiration) } type _LoginFormData struct { @@ -38,16 +38,15 @@ type _LoginFormData struct { Type int8 `json:"type"` } -func login(c *gin.Context) { +func login(c *fiber.Ctx) error { result := response.NewResult(c) loginData := new(_LoginFormData) - err := c.BindJSON(loginData) - if err != nil { - result.Error(http.StatusInternalServerError, "表单解析失败。") - return + if err := c.BodyParser(loginData); err != nil { + return result.Error(http.StatusInternalServerError, "表单解析失败。") } var ( session *model.Session + err error ) if loginData.Type == model.USER_TYPE_ENT { session, err = service.UserService.ProcessEnterpriseUserLogin(loginData.Username, loginData.Password) @@ -57,51 +56,43 @@ func login(c *gin.Context) { if err != nil { if authError, ok := err.(*exceptions.AuthenticationError); ok { if authError.NeedReset { - result.LoginNeedReset() - return + return result.LoginNeedReset() } - result.Error(int(authError.Code), authError.Message) - return + return result.Error(int(authError.Code), authError.Message) } else { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } - result.LoginSuccess(session) + return result.LoginSuccess(session) } -func logout(c *gin.Context) { +func logout(c *fiber.Ctx) error { result := response.NewResult(c) - session, exists := c.Get("session") - if !exists { - result.Success("用户会话已结束。") - return + session := c.Locals("session") + if session == nil { + return result.Success("用户会话已结束。") } _, err := cache.ClearSession(session.(*model.Session).Token) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Success("用户已成功登出系统。") + return result.Success("用户已成功登出系统。") } -func invalidUserPassword(c *gin.Context) { +func invalidUserPassword(c *fiber.Ctx) error { result := response.NewResult(c) - targetUserId := c.Param("uid") + targetUserId := c.Params("uid") verifyCode, err := service.UserService.InvalidUserPassword(targetUserId) if _, ok := err.(exceptions.NotFoundError); ok { - result.NotFound("未找到指定用户。") - return + return result.NotFound("未找到指定用户。") } if _, ok := err.(exceptions.UnsuccessfulOperationError); ok { - result.NotAccept("未能成功更新用户的密码。") - return + return result.NotAccept("未能成功更新用户的密码。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Json(http.StatusAccepted, "用户密码已经失效", gin.H{"verify": verifyCode}) + return result.Json(http.StatusAccepted, "用户密码已经失效", fiber.Map{"verify": verifyCode}) } type _ResetPasswordFormData struct { @@ -110,47 +101,42 @@ type _ResetPasswordFormData struct { NewPassword string `json:"newPass"` } -func resetUserPassword(c *gin.Context) { +func resetUserPassword(c *fiber.Ctx) error { result := response.NewResult(c) resetForm := new(_ResetPasswordFormData) - c.BindJSON(resetForm) + if err := c.BodyParser(resetForm); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } verified, err := service.UserService.VerifyUserPassword(resetForm.Username, resetForm.VerifyCode) if _, ok := err.(exceptions.NotFoundError); ok { - result.NotFound("指定的用户不存在。") - return + return result.NotFound("指定的用户不存在。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if !verified { - result.Error(http.StatusUnauthorized, "验证码不正确。") - return + return result.Error(http.StatusUnauthorized, "验证码不正确。") } completed, err := service.UserService.ResetUserPassword(resetForm.Username, resetForm.NewPassword) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } if completed { - result.Updated("用户凭据已更新。") - return + return result.Updated("用户凭据已更新。") } - result.NotAccept("用户凭据未能成功更新。") + return result.NotAccept("用户凭据未能成功更新。") } -func listPagedUser(c *gin.Context) { +func listPagedUser(c *fiber.Ctx) error { result := response.NewResult(c) - requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1")) + requestPage, err := strconv.Atoi(c.Query("page", "1")) if err != nil { - result.NotAccept("查询参数[page]格式不正确。") - return + return result.NotAccept("查询参数[page]格式不正确。") } - requestKeyword := c.DefaultQuery("keyword", "") - requestUserType, err := strconv.Atoi(c.DefaultQuery("type", "-1")) + requestKeyword := c.Query("keyword") + requestUserType, err := strconv.Atoi(c.Query("type", "-1")) if err != nil { - result.NotAccept("查询参数[type]格式不正确。") - return + return result.NotAccept("查询参数[type]格式不正确。") } var requestUserStat *bool state, err := strconv.ParseBool(c.Query("state")) @@ -161,14 +147,13 @@ func listPagedUser(c *gin.Context) { } users, total, err := service.UserService.ListUserDetail(requestKeyword, requestUserType, requestUserStat, requestPage) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Json( + return result.Json( http.StatusOK, "已取得符合条件的用户集合。", response.NewPagedResponse(requestPage, total).ToMap(), - gin.H{"accounts": users}, + fiber.Map{"accounts": users}, ) } @@ -177,21 +162,21 @@ type _UserStateChangeFormData struct { Enabled bool `json:"enabled" form:"enabled"` } -func switchUserEnabling(c *gin.Context) { +func switchUserEnabling(c *fiber.Ctx) error { result := response.NewResult(c) switchForm := new(_UserStateChangeFormData) - c.BindJSON(switchForm) + if err := c.BodyParser(switchForm); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } err := service.UserService.SwitchUserState(switchForm.UserID, switchForm.Enabled) if err != nil { if nfErr, ok := err.(*exceptions.NotFoundError); ok { - result.NotFound(nfErr.Message) - return + return result.NotFound(nfErr.Message) } else { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } - result.Updated("用户状态已经更新。") + return result.Updated("用户状态已经更新。") } type _OPSAccountCreationFormData struct { @@ -202,18 +187,18 @@ type _OPSAccountCreationFormData struct { Type int `json:"type" form:"type"` } -func createOPSAndManagementAccount(c *gin.Context) { +func createOPSAndManagementAccount(c *fiber.Ctx) error { result := response.NewResult(c) creationForm := new(_OPSAccountCreationFormData) - c.BindJSON(creationForm) + if err := c.BodyParser(creationForm); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } exists, err := service.UserService.IsUsernameExists(creationForm.Username) if exists { - result.Conflict("指定的用户名已经被使用了。") - return + return result.Conflict("指定的用户名已经被使用了。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } newUser := new(model.User) newUser.Username = creationForm.Username @@ -227,30 +212,27 @@ func createOPSAndManagementAccount(c *gin.Context) { newUserDetail.ServiceExpiration, _ = model.ParseDate("2099-12-31") verifyCode, err := service.UserService.CreateUser(newUser, newUserDetail) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } cache.AbolishRelation("user") - result.Json(http.StatusCreated, "用户已经成功创建。", gin.H{"verify": verifyCode}) + return result.Json(http.StatusCreated, "用户已经成功创建。", fiber.Map{"verify": verifyCode}) } -func getUserDetail(c *gin.Context) { +func getUserDetail(c *fiber.Ctx) error { result := response.NewResult(c) - targetUserId := c.Param("uid") + targetUserId := c.Params("uid") exists, err := service.UserService.IsUserExists(targetUserId) if !exists { - result.NotFound("指定的用户不存在。") - return + return result.NotFound("指定的用户不存在。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) + return result.Error(http.StatusInternalServerError, err.Error()) } userDetail, err := service.UserService.FetchUserDetail(targetUserId) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Json(http.StatusOK, "用户详细信息已获取到。", gin.H{"user": userDetail}) + return result.Json(http.StatusOK, "用户详细信息已获取到。", fiber.Map{"user": userDetail}) } type _EnterpriseCreationFormData struct { @@ -263,18 +245,18 @@ type _EnterpriseCreationFormData struct { UnitServiceFee *string `json:"unitServiceFee" form:"unitServiceFee"` } -func createEnterpriseAccount(c *gin.Context) { +func createEnterpriseAccount(c *fiber.Ctx) error { result := response.NewResult(c) creationForm := new(_EnterpriseCreationFormData) - c.BindJSON(creationForm) + if err := c.BodyParser(creationForm); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } exists, err := service.UserService.IsUsernameExists(creationForm.Username) if exists { - result.Conflict("指定的用户名已经被使用了。") - return + return result.Conflict("指定的用户名已经被使用了。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } newUser := new(model.User) newUser.Username = creationForm.Username @@ -286,18 +268,16 @@ func createEnterpriseAccount(c *gin.Context) { newUserDetail.Phone = creationForm.Phone newUserDetail.UnitServiceFee, err = decimal.NewFromString(*creationForm.UnitServiceFee) if err != nil { - result.BadRequest("用户月服务费无法解析。") - return + return result.BadRequest("用户月服务费无法解析。") } newUserDetail.ServiceExpiration = model.NewEmptyDate() verifyCode, err := service.UserService.CreateUser(newUser, newUserDetail) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } cache.AbolishRelation("user") - result.Json(http.StatusCreated, "用户已经成功创建。", gin.H{"verify": verifyCode}) + return result.Json(http.StatusCreated, "用户已经成功创建。", fiber.Map{"verify": verifyCode}) } type _AccountModificationFormData struct { @@ -309,19 +289,19 @@ type _AccountModificationFormData struct { UnitServiceFee *string `json:"unitServiceFee" form:"unitServiceFee"` } -func modifyAccountDetail(c *gin.Context) { +func modifyAccountDetail(c *fiber.Ctx) error { result := response.NewResult(c) - targetUserId := c.Param("uid") + targetUserId := c.Params("uid") modForm := new(_AccountModificationFormData) - c.BindJSON(modForm) + if err := c.BodyParser(modForm); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } exists, err := service.UserService.IsUserExists(targetUserId) if !exists { - result.NotFound("指定的用户不存在。") - return + return result.NotFound("指定的用户不存在。") } if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } newUserInfo := new(model.UserDetail) newUserInfo.Id = targetUserId @@ -336,43 +316,42 @@ func modifyAccountDetail(c *gin.Context) { newUserInfo.Phone = modForm.Phone newUserInfo.UnitServiceFee, err = decimal.NewFromString(*modForm.UnitServiceFee) if err != nil { - result.BadRequest("用户月服务费无法解析。") - return + return result.BadRequest("用户月服务费无法解析。") } _, err = global.DB.NewUpdate().Model(newUserInfo). WherePK(). Column("name", "abbr", "region", "address", "contact", "phone", "unit_service_fee"). - Exec(c) + Exec(c.Context()) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } cache.AbolishRelation(fmt.Sprintf("user:%s", targetUserId)) - result.Updated("指定用户的信息已经更新。") + return result.Updated("指定用户的信息已经更新。") } -func quickSearchEnterprise(c *gin.Context) { +func quickSearchEnterprise(c *fiber.Ctx) error { result := response.NewResult(c) keyword := c.Query("keyword") searchResult, err := service.UserService.SearchLimitUsers(keyword, 6) if err != nil { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } - result.Json(http.StatusOK, "已查询到存在符合条件的企业", gin.H{"users": searchResult}) + return result.Json(http.StatusOK, "已查询到存在符合条件的企业", fiber.Map{"users": searchResult}) } -func fetchExpiration(c *gin.Context) { +func fetchExpiration(c *fiber.Ctx) error { result := response.NewResult(c) session, err := _retreiveSession(c) if err != nil { - result.Unauthorized(err.Error()) - return + return result.Unauthorized(err.Error()) } user, err := service.UserService.FetchUserDetail(session.Uid) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Json(http.StatusOK, "已经取得用户的服务期限信息", gin.H{"expiration": user.ServiceExpiration.Format("2006-01-02")}) + return result.Json( + http.StatusOK, + "已经取得用户的服务期限信息", + fiber.Map{"expiration": user.ServiceExpiration.Format("2006-01-02")}, + ) } diff --git a/controller/withdraw.go b/controller/withdraw.go index 9bdcbbd..4021a93 100644 --- a/controller/withdraw.go +++ b/controller/withdraw.go @@ -8,59 +8,53 @@ import ( "net/http" "strconv" - "github.com/gin-gonic/gin" + "github.com/gofiber/fiber/v2" ) -func InitializeWithdrawController(router *gin.Engine) { - router.DELETE("/publicity/:pid", security.EnterpriseAuthorize, applyReportWithdraw) - router.GET("/withdraws", security.OPSAuthorize, fetchWithdrawsWaitingAutdit) - router.PUT("/withdraw/:rid", security.OPSAuthorize, auditWithdraw) +func InitializeWithdrawController(router *fiber.App) { + router.Delete("/publicity/:pid", security.EnterpriseAuthorize, applyReportWithdraw) + router.Get("/withdraws", security.OPSAuthorize, fetchWithdrawsWaitingAutdit) + router.Put("/withdraw/:rid", security.OPSAuthorize, auditWithdraw) } -func applyReportWithdraw(c *gin.Context) { +func applyReportWithdraw(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("pid") - if !ensureReportBelongs(c, result, requestReportId) { - return + requestReportId := c.Params("pid") + if ensure, err := ensureReportBelongs(c, &result, requestReportId); !ensure { + return err } deleted, err := service.WithdrawService.ApplyWithdraw(requestReportId) if err != nil { if nfErr, ok := err.(exceptions.NotFoundError); ok { - result.NotFound(nfErr.Error()) - return + return result.NotFound(nfErr.Error()) } else if ioErr, ok := err.(exceptions.ImproperOperateError); ok { - result.NotAccept(ioErr.Error()) - return + return result.NotAccept(ioErr.Error()) } else { - result.Error(http.StatusInternalServerError, err.Error()) - return + return result.Error(http.StatusInternalServerError, err.Error()) } } if !deleted { - result.Error(http.StatusInternalServerError, "未能完成公示报表的申请撤回操作。") - return + return result.Error(http.StatusInternalServerError, "未能完成公示报表的申请撤回操作。") } - result.Success("指定的公示报表已经申请撤回。") + return result.Success("指定的公示报表已经申请撤回。") } -func fetchWithdrawsWaitingAutdit(c *gin.Context) { +func fetchWithdrawsWaitingAutdit(c *fiber.Ctx) error { result := response.NewResult(c) - keyword := c.DefaultQuery("keyword", "") - requestPage, err := strconv.Atoi(c.DefaultQuery("page", "1")) + keyword := c.Query("keyword") + requestPage, err := strconv.Atoi(c.Query("page", "1")) if err != nil { - result.NotAccept("查询参数[page]格式不正确。") - return + return result.NotAccept("查询参数[page]格式不正确。") } reports, totalitems, err := service.WithdrawService.FetchPagedWithdrawApplies(requestPage, keyword) if err != nil { - result.NotFound(err.Error()) - return + return result.NotFound(err.Error()) } - result.Json( + return result.Json( http.StatusOK, "已经取得符合条件的等待审核的撤回申请。", response.NewPagedResponse(requestPage, totalitems).ToMap(), - gin.H{"records": reports}, + fiber.Map{"records": reports}, ) } @@ -68,19 +62,20 @@ type WithdrawAuditFormData struct { Audit bool `json:"audit" form:"audit"` } -func auditWithdraw(c *gin.Context) { +func auditWithdraw(c *fiber.Ctx) error { result := response.NewResult(c) - requestReportId := c.Param("rid") + requestReportId := c.Params("rid") formData := new(WithdrawAuditFormData) - c.BindJSON(formData) + if err := c.BodyParser(formData); err != nil { + return result.UnableToParse("无法解析提交的数据。") + } err := service.WithdrawService.AuditWithdraw(requestReportId, formData.Audit) if err != nil { if nfErr, ok := err.(exceptions.NotFoundError); ok { - result.NotFound(nfErr.Error()) + return result.NotFound(nfErr.Error()) } else { - result.NotAccept(err.Error()) + return result.NotAccept(err.Error()) } - return } - result.Success("指定公示报表的撤回申请已经完成审核") + return result.Success("指定公示报表的撤回申请已经完成审核") } diff --git a/response/user_response.go b/response/user_response.go index 6cfed8e..9eaf458 100644 --- a/response/user_response.go +++ b/response/user_response.go @@ -13,19 +13,19 @@ type LoginResponse struct { Session *model.Session `json:"session"` } -func (r *Result) LoginSuccess(session *model.Session) { +func (r Result) LoginSuccess(session *model.Session) error { res := &LoginResponse{} res.Code = http.StatusOK res.Message = "用户已成功登录。" res.NeedReset = false res.Session = session - r.Ctx.Status(fiber.StatusOK).JSON(res) + return r.Ctx.Status(fiber.StatusOK).JSON(res) } -func (r *Result) LoginNeedReset() { +func (r Result) LoginNeedReset() error { res := &LoginResponse{} res.Code = http.StatusUnauthorized res.Message = "用户凭据已失效。" res.NeedReset = true - r.Ctx.Status(fiber.StatusOK).JSON(res) + return r.Ctx.Status(fiber.StatusOK).JSON(res) }