diff --git a/controller/report.go b/controller/report.go index a99cabe..b79efe5 100644 --- a/controller/report.go +++ b/controller/report.go @@ -23,7 +23,8 @@ func InitializeReportHandlers(router *fiber.App) { router.Get("/reports", security.MustAuthenticated, reportComprehensiveSearch) router.Post("/report", security.EnterpriseAuthorize, initNewReportCalculateTask) router.Get("/report/draft", security.EnterpriseAuthorize, listDraftReportIndicies) - router.Post("/report/calcualte", security.EnterpriseAuthorize, testCalculateReportSummary) + //TODO: 2023-07-20将calcualte错误请求改为正确的calculate请求 + router.Post("/report/calculate", security.EnterpriseAuthorize, testCalculateReportSummary) router.Get("/report/calculate/status", security.EnterpriseAuthorize, listCalculateTaskStatus) router.Get("/report/:rid", security.EnterpriseAuthorize, getReportDetail) router.Put("/report/:rid", security.EnterpriseAuthorize, updateReportCalculateTask) diff --git a/controller/tenement.go b/controller/tenement.go index 04dab4c..0e1c98b 100644 --- a/controller/tenement.go +++ b/controller/tenement.go @@ -25,9 +25,11 @@ func InitializeTenementHandler(router *fiber.App) { router.Put("/tenement/:pid/:tid", security.EnterpriseAuthorize, updateTenement) router.Get("/tenement/:pid/:tid", security.EnterpriseAuthorize, getTenementDetail) router.Get("/tenement/:pid/:tid/meter", security.EnterpriseAuthorize, listMeters) + //TODO: 2023-07-19再apiFox上该请求是个PUT请求,后端接收是个POST请求,不知道是否有误或是缺少对应请求(apiFox测试请求返回值为405) router.Post("/tenement/:pid/:tid/move/out", security.EnterpriseAuthorize, moveOutTenement) router.Post("/tenement/:pid", security.EnterpriseAuthorize, addTenement) router.Post("/tenement/:pid/:tid/binding", security.EnterpriseAuthorize, bindMeterToTenement) + //TODO: 2023-07-19再apiFox上该请求是个PUT请求,后端接收是个POST请求,不知道是否有误或是缺少对应请求(apiFox测试请求返回值为405) router.Post("/tenement/:pid/:tid/binding/:code/unbind", security.EnterpriseAuthorize, unbindMeterFromTenement) } diff --git a/controller/withdraw.go b/controller/withdraw.go index cc490ac..e19d613 100644 --- a/controller/withdraw.go +++ b/controller/withdraw.go @@ -2,9 +2,11 @@ package controller import ( "electricity_bill_calc/logger" + "electricity_bill_calc/repository" "electricity_bill_calc/response" "github.com/gofiber/fiber/v2" "go.uber.org/zap" + "net/http" ) var withdrawLog = logger.Named("Handler", "Withdraw") @@ -24,51 +26,15 @@ func withdraw(c *fiber.Ctx) error { withdrawLog.Info("参数为: ", zap.String("keyword", keyword), zap.Int("page", page)) //中间数据库操作暂且省略。。。。 //首先进行核算报表的分页查询 - - //TODO: 2023-07-18 此处的data需要经过上面数据库查询后进行数据返回,此处只是作于演示 - data := fiber.Map{ - "report": fiber.Map{ - "id": "string", - "parkId": "string", - "periodBegin": "string", - "periodEnd": "string", - "published": true, - "publishedAt": "string", - "withdraw": 0, - "lastWithdrawAppliedAt": "string", - "lastWithdrawAuditAt": "string", - "status": 0, - "message": "string", - }, - "park": fiber.Map{ - "id": "string", - "userId": "string", - "name": "string", - "tenement": "string", - "area": "string", - "capacity": "string", - "category": 0, - "meter04kvType": 0, - "region": "string", - "address": "string", - "contact": "string", - "phone": "string", - }, - "user": fiber.Map{ - "id": "string", - "name": "string", - "contact": "string", - "phone": "string", - "region": "string", - "address": "string", - }, + withdraws, total, err := repository.WithdrawRepository.FindWithdraw(page, &keyword) + if err != nil { + withdrawLog.Error("检索用户核算报表失败。", zap.Error(err)) + return result.Error(http.StatusInternalServerError, err.Error()) } - datas := make([]interface{}, 0) - datas = append(datas, data) //TODO: 2023-07-18 此处返回值是个示例,具体返回值需要查询数据库 return result.Success( "withdraw请求成功", - response.NewPagedResponse(page, 20).ToMap(), - fiber.Map{"records": datas}, + response.NewPagedResponse(page, total).ToMap(), + fiber.Map{"records": withdraws}, ) } diff --git a/model/park.go b/model/park.go index 9dfd190..c00df57 100644 --- a/model/park.go +++ b/model/park.go @@ -31,3 +31,8 @@ type Park struct { LastModifiedAt time.Time `json:"lastModifiedAt"` DeletedAt *time.Time `json:"deletedAt"` } + +type Parks struct { + Park + NormAuthorizedLossRate float64 `json:"norm_authorized_loss_rate"` +} diff --git a/model/withdraw.go b/model/withdraw.go new file mode 100644 index 0000000..6b5b032 --- /dev/null +++ b/model/withdraw.go @@ -0,0 +1,77 @@ +package model + +import ( + "database/sql" + "electricity_bill_calc/types" + "time" +) + +type Withdraw struct { + Park SimplifiedPark `json:"park"` + Report SimplifiedReport `json:"report"` + User UserInfos `json:"user"` // 简易用户详细信息 +} + +// 简易园区信息 +type SimplifiedPark struct { + Address *string `json:"address"` // 园区地址 + Area *string `json:"area"` // 园区面积 + Capacity *string `json:"capacity"` // 供电容量 + Category int16 `json:"category"` // 用电分类,0:两部制,1:单一峰谷,2:单一单一 + Contact *string `json:"contact"` // 园区联系人 + ID string `json:"id"` // 园区ID + Meter04KvType int16 `json:"meter04kvType"` // 户表计量类型,0:非峰谷,1:峰谷 + Name string `json:"name"` // 园区名称 + Phone *string `json:"phone"` // 园区联系人电话 + Region *string `json:"region"` // 园区所在行政区划 + Tenement *string `json:"tenement"` // 园区住户数量 + UserID string `json:"userId"` // 园区所属用户ID +} + +// 简易核算报表信息 +type SimplifiedReport struct { + ID string `json:"id"` // 报表ID + LastWithdrawAppliedAt *string `json:"lastWithdrawAppliedAt"` // 最后一次申请撤回的时间,格式为 yyyy-MM-dd HH:mm:ss + LastWithdrawAuditAt *string `json:"lastWithdrawAuditAt"` // 最后一次申请审核的时间,格式为 yyyy-MM-dd HH:mm:ss + Message *string `json:"message"` // 当前状态的错误提示 + ParkID string `json:"parkId"` // 所属园区ID + PeriodBegin string `json:"periodBegin"` // 核算起始日期,格式为 yyyy-MM-dd + PeriodEnd string `json:"periodEnd"` // 核算结束日期,格式为 yyyy-MM-dd + Published bool `json:"published"` // 是否已发布 + PublishedAt *string `json:"publishedAt"` // 发布时间 + Status float64 `json:"status,omitempty"` // 当前状态,0:计算任务已队列,1:计算任务已完成,2:计算数据不足 + Withdraw int16 `json:"withdraw"` // 报表撤回状态,0:未撤回,1:申请撤回中,2:申请拒绝,3:申请批准 +} + +// 简易用户信息 +type UserInfos struct { + Address *string `json:"address"` // 用户地址 + Contact *string `json:"contact"` // 用户联系人 + ID string `json:"id"` // 用户ID + Name *string `json:"name"` // 用户名称 + Phone *string `json:"phone"` // 用户联系人电话 + Region *string `json:"region"` // 用户所在行政区划 +} + +//用于映射数据库的报表结构体 +type Report struct { + CreatedAt time.Time `db:"created_at"` + LastModifiedAt sql.NullTime `db:"last_modified_at"` + ID string `db:"id"` + ParkID string `db:"park_id"` + Period types.DateRange `db:"period"` + Published bool `db:"published"` + PublishedAt sql.NullTime `db:"published_at"` + Withdraw int16 `db:"withdraw"` + LastWithdrawAppliedAt sql.NullTime `db:"last_withdraw_applied_at"` + LastWithdrawAuditAt sql.NullTime `db:"last_withdraw_audit_at"` + Category int16 `db:"category"` + Meter04KVType int16 `db:"meter_04kv_type"` + PricePolicy int16 `db:"price_policy"` + BasisPooled int16 `db:"basis_pooled"` + AdjustPooled int16 `db:"adjust_pooled"` + LossPooled int16 `db:"loss_pooled"` + PublicPooled int16 `db:"public_pooled"` + AuthorizedLossRate float64 `db:"authorized_loss_rate"` + AuthorizedLossRateIncr float64 `db:"authorized_loss_rate_increment"` +} diff --git a/repository/withdraw.go b/repository/withdraw.go new file mode 100644 index 0000000..f316d7f --- /dev/null +++ b/repository/withdraw.go @@ -0,0 +1,184 @@ +package repository + +import ( + "electricity_bill_calc/global" + "electricity_bill_calc/logger" + "electricity_bill_calc/model" + "electricity_bill_calc/tools" + "fmt" + "github.com/doug-martin/goqu/v9" + "github.com/georgysavva/scany/v2/pgxscan" + "go.uber.org/zap" +) + +type _WithdrawRepository struct { + log *zap.Logger + ds goqu.DialectWrapper +} + +var WithdrawRepository = &_WithdrawRepository{ + log: logger.Named("Repository", "Withdraw"), + ds: goqu.Dialect("postgres"), +} + +/** + * @author: ZiHangQin + * 该方法用于分页查询核算报表 + * @param:page + * @param: keyword + * @return:[]object + * @return:total + * @return: error + */ +func (wd _WithdrawRepository) FindWithdraw(page int, keyword *string) ([]model.Withdraw, int64, error) { + wd.log.Info("查询用户的充值记录。", zap.Stringp("keyword", keyword), zap.Int("page", page)) + ctx, cancel := global.TimeoutContext() + defer cancel() + fmt.Println(ctx) + //TODO: 2023-07-18此处进行用户的核算报表分页查询的sql语句拼接逻辑。 + //1、SELECT * FROM report WHERE `withdraw` = 1(获取到所有的状态为申请撤回中的报表数据) + // + //2、循环遍历1中获取的数据{ + //查询需要的字段"id": "string", + // "parkId": "string", + // "periodBegin": "string", + // "periodEnd": "string", + // "published": true, + // "publishedAt": "string", + // "withdraw": 0, + // "lastWithdrawAppliedAt": "string", + // "lastWithdrawAuditAt": "string", + // "status": 0, + // "message": "string" + //----report简易核算报表信息获取完成 + // + //3、SELECT * FROM park WHERE `id` = report.park_id(获取园区信息) + //查询结果需要的字段 "id": "string", + // "userId": "string", + // "name": "string", + // "tenement": "string", + // "area": "string", + // "capacity": "string", + // "category": 0, + // "meter04kvType": 0, + // "region": "string", + // "address": "string", + // "contact": "string", + // "phone": "string" + //----park简易园区信息货物完成 + // + //4、SELECT * FROM user_detail WHERE `id` = park.user_id(获取用户信息) + //查询结果需要的字段 "id": "string", + // "name": "string", + // "contact": "string", + // "phone": "string", + // "region": "string", + // "address": "string" + //----user简易用户信息获取完成 + //} + + reportQuery, reportQueryArgs, _ := wd.ds. + From(goqu.T("report")). + Where(goqu.I("withdraw").Eq(1)). + Select("*").ToSQL() + + reports := make([]model.Report, 0) + + err := pgxscan.Select(ctx, global.DB, &reports, reportQuery, reportQueryArgs...) + if err != nil { + fmt.Println(err) + return []model.Withdraw{}, 0, err + } + fmt.Println("数据库中读取的指定数据:", reports) + + var withdrawReses []model.Withdraw + + for _, v := range reports { + lastWithdrawAppliedAtStr := tools.NullTime2PointerString(v.LastWithdrawAppliedAt) + lastWithdrawAuditAtStr := tools.NullTime2PointerString(v.LastWithdrawAuditAt) + publishAtStr := tools.NullTime2PointerString(v.PublishedAt) + + Begin := v.Period.SafeLower().Format("2006-01-02") + End := v.Period.SafeUpper().Format("2006-01-02") + var withdrawRes model.Withdraw + //构建简易报表信息 + simplifiedReport := model.SimplifiedReport{ + ID: v.ID, + LastWithdrawAppliedAt: lastWithdrawAppliedAtStr, + LastWithdrawAuditAt: lastWithdrawAuditAtStr, + Message: nil, + ParkID: v.ParkID, + PeriodBegin: Begin, + PeriodEnd: End, + Published: v.Published, + PublishedAt: publishAtStr, + Status: 0.00, + Withdraw: v.Withdraw, + } + + parkQuery, parkQueryArgs, _ := wd.ds. + From(goqu.T("park")). + Where(goqu.I("id").Eq(v.ParkID)). + Select("*").ToSQL() + + park := make([]model.Parks, 0) + err := pgxscan.Select(ctx, global.DB, &park, parkQuery, parkQueryArgs...) + fmt.Println("读到的园区数据:", park) + if err != nil { + fmt.Println(err) + return []model.Withdraw{}, 0, err + } + + areaStr := tools.NullDecimalToString(park[0].Area) + capacityStr := tools.NullDecimalToString(park[0].Capacity) + TenementQuantityStr := tools.NullDecimalToString(park[0].TenementQuantity) + //构建简易园区数据 + simplifiedPark := model.SimplifiedPark{ + Address: park[0].Address, + Area: areaStr, + Capacity: capacityStr, + Category: park[0].Category, + Contact: park[0].Contact, + ID: park[0].Id, + Meter04KvType: park[0].MeterType, + Name: park[0].Name, + Phone: park[0].Phone, + Region: park[0].Region, + Tenement: TenementQuantityStr, + UserID: park[0].UserId, + } + + userQuery, userQueryArgs, _ := wd.ds. + From(goqu.T("user_detail")). + Where(goqu.I("id").Eq(park[0].UserId)). + Select("*").ToSQL() + + userInfo := make([]model.UserDetail, 0) + + err = pgxscan.Select(ctx, global.DB, &userInfo, userQuery, userQueryArgs...) + fmt.Println("读到的用户数据:", userInfo) + if err != nil { + fmt.Println(err) + return []model.Withdraw{}, 0, err + } + + simplifiedUser := model.UserInfos{ + Address: userInfo[0].Address, + Contact: userInfo[0].Contact, + ID: userInfo[0].Id, + Name: userInfo[0].Name, + Phone: userInfo[0].Phone, + Region: userInfo[0].Region, + } + + withdrawRes.Report = simplifiedReport + withdrawRes.Park = simplifiedPark + withdrawRes.User = simplifiedUser + + withdrawReses = append(withdrawReses, withdrawRes) + } + + total := len(reports) + + return withdrawReses, int64(total), nil +} diff --git a/router/router.go b/router/router.go index 908558d..f1db451 100644 --- a/router/router.go +++ b/router/router.go @@ -53,6 +53,8 @@ func App() *fiber.App { controller.InitializeInvoiceHandler(app) controller.InitializeTopUpHandlers(app) controller.InitializeReportHandlers(app) + + controller.InitializeWithdrawHandlers(app) return app diff --git a/tools/utils.go b/tools/utils.go index 6312dd5..fceb81b 100644 --- a/tools/utils.go +++ b/tools/utils.go @@ -1,6 +1,7 @@ package tools import ( + "database/sql" "encoding/json" "fmt" "strings" @@ -144,3 +145,16 @@ func NullDecimalToString(d decimal.NullDecimal, precision ...int32) *string { } return lo.ToPtr(d.Decimal.StringFixedBank(precision[0])) } + +//将sql.NullTime转换为*string +func NullTime2PointerString(nullTime sql.NullTime) *string { + var strPtr *string + if nullTime.Valid { + str := nullTime.Time.String() + strPtr = &str + return strPtr + } else { + strPtr = nil + return strPtr + } +}