From 6fece99e002268c8912a0bc59b1ba26849d2835a Mon Sep 17 00:00:00 2001 From: ZiHangQin <1420014281@qq.com> Date: Tue, 25 Jul 2023 10:45:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B8=A6=E5=88=86=E9=A1=B5=E7=9A=84=E5=BE=85?= =?UTF-8?q?=E5=AE=A1=E6=A0=B8=E7=9A=84=E6=A0=B8=E7=AE=97=E6=92=A4=E5=9B=9E?= =?UTF-8?q?=E7=94=B3=E8=AF=B7=E5=88=97=E8=A1=A8=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/withdraw.go | 2 +- model/withdraw.go | 75 +++++++------ repository/withdraw.go | 243 ++++++++++++++++++++--------------------- tools/utils.go | 13 +++ 4 files changed, 173 insertions(+), 160 deletions(-) diff --git a/controller/withdraw.go b/controller/withdraw.go index e19d613..d6c7510 100644 --- a/controller/withdraw.go +++ b/controller/withdraw.go @@ -26,7 +26,7 @@ func withdraw(c *fiber.Ctx) error { withdrawLog.Info("参数为: ", zap.String("keyword", keyword), zap.Int("page", page)) //中间数据库操作暂且省略。。。。 //首先进行核算报表的分页查询 - withdraws, total, err := repository.WithdrawRepository.FindWithdraw(page, &keyword) + withdraws, total, err := repository.WithdrawRepository.FindWithdraw(uint(page), &keyword) if err != nil { withdrawLog.Error("检索用户核算报表失败。", zap.Error(err)) return result.Error(http.StatusInternalServerError, err.Error()) diff --git a/model/withdraw.go b/model/withdraw.go index 6b5b032..b1da5f1 100644 --- a/model/withdraw.go +++ b/model/withdraw.go @@ -1,8 +1,8 @@ package model import ( - "database/sql" "electricity_bill_calc/types" + "github.com/shopspring/decimal" "time" ) @@ -17,10 +17,10 @@ type SimplifiedPark struct { Address *string `json:"address"` // 园区地址 Area *string `json:"area"` // 园区面积 Capacity *string `json:"capacity"` // 供电容量 - Category int16 `json:"category"` // 用电分类,0:两部制,1:单一峰谷,2:单一单一 + Category int16 `json:"category"` // 用电分类,0:两部制,1:单一峰谷,2:单一单一 Contact *string `json:"contact"` // 园区联系人 ID string `json:"id"` // 园区ID - Meter04KvType int16 `json:"meter04kvType"` // 户表计量类型,0:非峰谷,1:峰谷 + Meter04KvType int16 `json:"meter04kvType"` // 户表计量类型,0:非峰谷,1:峰谷 Name string `json:"name"` // 园区名称 Phone *string `json:"phone"` // 园区联系人电话 Region *string `json:"region"` // 园区所在行政区划 @@ -30,17 +30,17 @@ type SimplifiedPark struct { // 简易核算报表信息 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"` // 发布时间 + 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:申请批准 + Withdraw int16 `json:"withdraw"` // 报表撤回状态,0:未撤回,1:申请撤回中,2:申请拒绝,3:申请批准 } // 简易用户信息 @@ -48,30 +48,37 @@ type UserInfos struct { Address *string `json:"address"` // 用户地址 Contact *string `json:"contact"` // 用户联系人 ID string `json:"id"` // 用户ID - Name *string `json:"name"` // 用户名称 + 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"` +type ReportRes struct { + ReportId string `db:"report_id"` + LastWithdrawAppliedAt *time.Time `db:"last_withdraw_applied_at"` + LastWithdrawAuditAt *time.Time `db:"last_withdraw_audit_at"` + ParkID string `db:"report_park_id"` + Period types.DateRange `db:"period"` + Published bool `db:"published"` + PublishedAt *time.Time `db: "published_at"` + Withdraw int16 `db:"withdraw"` + ParkAddress *string `db:"park_address"` + Area decimal.NullDecimal `db:"area"` + Capacity decimal.NullDecimal `db:"capacity"` + Category int16 + ParkContact *string `db:"park_contact"` + ParkId string `db:"park_id"` + Meter04KVType int16 `db:"meter_04kv_type"` + ParkName string `db:"park_name"` + ParkPhone *string `db:"park_phone"` + ParkRegion string `db:"park_region"` + TenementQuantity decimal.NullDecimal `db:"tenement_quantity"` + UserID string `db:"user_id"` + Address *string + Contact string `db:"user_detail_contact"` + ID string `db:"ud_id"` + Name *string `db:"user_detail_name"` + Phone string `db:"user_detail_phone"` + Region *string `db:"user_detail_region"` } diff --git a/repository/withdraw.go b/repository/withdraw.go index 5529731..4fe000c 100644 --- a/repository/withdraw.go +++ b/repository/withdraw.go @@ -1,6 +1,7 @@ package repository import ( + "electricity_bill_calc/config" "electricity_bill_calc/global" "electricity_bill_calc/logger" "electricity_bill_calc/model" @@ -30,154 +31,146 @@ var WithdrawRepository = &_WithdrawRepository{ * @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)) +func (wd _WithdrawRepository) FindWithdraw(page uint, keyword *string) ([]model.Withdraw, int64, error) { + wd.log.Info("查询用户的充值记录。", zap.Stringp("keyword", keyword), zap.Int("page", int(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")). + /** + 如果访问数据库次数过多出现时间过长的话可以用这个尝试优化,未测试的sql语句 + + wd.ds.From(goqu.T("report")). Where(goqu.I("withdraw").Eq(1)). - Select("*").ToSQL() + Select( + goqu.I("report.*"), + goqu.I("park.*"), + goqu.I("user_detail.*"), + ). + Join( + goqu.T("park"), goqu.On(goqu.I("report.park_id").Eq(goqu.I("park.id"))), + ). + Join( + goqu.T("user_detail"), goqu.On(goqu.I("park.user_id").Eq(goqu.I("user_detail.id"))), + ).ToSQL() - reports := make([]model.Report, 0) + SELECT report.*, park.*, user_detail.* + FROM report as r + JOIN park as p ON r.park_id = p.id + JOIN user_detail as ud ON p.user_id = ud.id + WHERE withdraw = 1 + AND p.name Like '%keyword%' + AND ud.name Like '%keyword%' + */ + reportQuery := wd.ds. + From(goqu.T("report").As("r")). + Where(goqu.I("withdraw").Eq(1)). + Join(goqu.T("park").As("p"), goqu.On(goqu.I("r.park_id").Eq(goqu.I("p.id")))). + Join(goqu.T("user_detail").As("ud"), goqu.On(goqu.I("p.user_id").Eq(goqu.I("ud.id")))). + Select( + goqu.I("r.id").As("report_id"), goqu.I("r.last_withdraw_applied_at"), goqu.I("r.last_withdraw_audit_at"), + goqu.I("r.park_id").As("report_park_id"), goqu.I("r.period"), goqu.I("r.published"), goqu.I("r.published_at"), goqu.I("r.withdraw"), + goqu.I("p.address").As("park_address"), goqu.I("p.area"), goqu.I("p.capacity"), goqu.I("p.category"), goqu.I("p.contact").As("park_contact"), + goqu.I("p.id").As("park_id"), goqu.I("p.meter_04kv_type"), goqu.I("p.name").As("park_name"), goqu.I("p.phone").As("park_phone"), goqu.I("p.region").As("park_region"), + goqu.I("p.tenement_quantity"), goqu.I("p.user_id"), goqu.I("ud.address"), goqu.I("ud.contact").As("user_detail_contact"), + goqu.I("ud.id").As("ud_id"), goqu.I("ud.name").As("user_detail_name"), goqu.I("ud.phone").As("user_detail_phone"), goqu.I("ud.region").As("user_detail_region"), + ) - err := pgxscan.Select(ctx, global.DB, &reports, reportQuery, reportQueryArgs...) - if err != nil { - fmt.Println(err) - return []model.Withdraw{}, 0, err + countReportQuery := wd.ds. + From(goqu.T("report").As("r")). + Where(goqu.I("withdraw").Eq(1)). + Join(goqu.T("park").As("p"), goqu.On(goqu.I("r.park_id").Eq(goqu.I("p.id")))). + Join(goqu.T("user_detail").As("ud"), goqu.On(goqu.I("p.user_id").Eq(goqu.I("ud.id")))). + Select(goqu.COUNT("*")) + + if keyword != nil && len(*keyword) > 0 { + pattern := fmt.Sprintf("%%%s%%", *keyword) + reportQuery = reportQuery.Where(goqu.Or( + goqu.I("p.name").ILike(pattern), + goqu.I("ud.name").ILike(pattern), + )) } + reportQuery = reportQuery.Order(goqu.I("r.created_at").Desc()) + + currentPostion := (page - 1) * config.ServiceSettings.ItemsPageSize + reportQuery = reportQuery.Offset(currentPostion).Limit(config.ServiceSettings.ItemsPageSize) + + reportSql, reportArgs, _ := reportQuery.Prepared(true).ToSQL() + + countReportQuerySql, countReportQueryArgs, _ := countReportQuery.Prepared(true).ToSQL() + + + var ( + reports []*model.ReportRes = make([]*model.ReportRes, 0) + total int64 + ) + var err error + + err = pgxscan.Select(ctx, global.DB, &reports, reportSql, reportArgs...) + if err != nil { + fmt.Println(err) + wd.log.Error("查询报表记录失败。", zap.Error(err)) + return make([]model.Withdraw, 0), 0, err + } + + if err = pgxscan.Get(ctx, global.DB, &total, countReportQuerySql, countReportQueryArgs...); err != nil { + wd.log.Error("查询报表记录总数失败。", zap.Error(err)) + return make([]model.Withdraw, 0), 0, err + } + + if len(reports) <= 0 { + return make([]model.Withdraw, 0), total, nil + } + + fmt.Println(&reports) var withdrawReses []model.Withdraw - + //TODO: 2023.07.24对查询到的数据进行拼接 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, + report := model.SimplifiedReport{ + ID: v.ReportId, + LastWithdrawAppliedAt: tools.TimeToStringPtr(v.LastWithdrawAppliedAt), + LastWithdrawAuditAt: tools.TimeToStringPtr(v.LastWithdrawAuditAt), Message: nil, ParkID: v.ParkID, PeriodBegin: Begin, PeriodEnd: End, Published: v.Published, - PublishedAt: publishAtStr, - Status: 0.00, + PublishedAt: nil, + Status: 0., 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 + park := model.SimplifiedPark{ + Address: v.ParkAddress, + Area: tools.NullDecimalToString(v.Area), + Capacity: tools.NullDecimalToString(v.Capacity), + Category: int16(v.Category), + Contact: v.ParkContact, + ID: v.ParkId, + Meter04KvType: v.Meter04KVType, + Name: v.ParkName, + Phone: v.ParkPhone, + Region: &v.ParkRegion, + Tenement: tools.NullDecimalToString(v.TenementQuantity), + UserID: v.UserID, + } + userInfo := model.UserInfos{ + Address: v.Address, + Contact: &v.Contact, + ID: v.ID, + Name: v.Name, + Phone: &v.Phone, + Region: v.Region, } - 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 - + withdrawRes.Report = report + withdrawRes.Park = park + withdrawRes.User = userInfo withdrawReses = append(withdrawReses, withdrawRes) } - total := len(reports) - - return withdrawReses, int64(total), nil + return withdrawReses, total, nil } diff --git a/tools/utils.go b/tools/utils.go index fceb81b..af61a41 100644 --- a/tools/utils.go +++ b/tools/utils.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "strings" + "time" "github.com/mozillazg/go-pinyin" "github.com/samber/lo" @@ -158,3 +159,15 @@ func NullTime2PointerString(nullTime sql.NullTime) *string { return strPtr } } + + +//该方法用于将时间解析为字符串指针 +func TimeToStringPtr(t *time.Time) *string { + if t == nil { + return nil + } + + timeStr := t.Format("2006-01-02 15:04:05") + return &timeStr +} +