From 0355300908a2be27232aee9057379d58152127a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Mon, 19 Sep 2022 14:27:25 +0800 Subject: [PATCH] =?UTF-8?q?fix(report):=E5=9F=BA=E6=9C=AC=E5=AE=8C?= =?UTF-8?q?=E6=88=90=E6=8A=A5=E8=A1=A8=E9=83=A8=E5=88=86=E7=9A=84=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E8=B0=83=E6=95=B4=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/end_user_detail.go | 42 ++++++++++++------------ model/meter_04kv.go | 2 +- model/park.go | 1 + model/region.go | 4 +-- model/report.go | 12 +++---- model/report_summary.go | 24 +++++++------- model/user_charges.go | 6 ++-- model/will_diluted_fee.go | 19 ++++++++++- service/end_user.go | 2 +- service/report.go | 68 ++++++++++++++++++++++----------------- 10 files changed, 104 insertions(+), 76 deletions(-) diff --git a/model/end_user_detail.go b/model/end_user_detail.go index 778c35d..c50e509 100644 --- a/model/end_user_detail.go +++ b/model/end_user_detail.go @@ -15,32 +15,32 @@ type EndUserDetail struct { ReportId string `bun:",pk,notnull" json:"reportId"` ParkId string `bun:",pk,notnull" json:"parkId"` MeterId string `bun:"meter_04kv_id,pk,notnull" json:"meterId"` - Seq int64 `bun:"type:bigint,notnull,default:0" json:"seq"` - Ratio decimal.Decimal `bun:",notnull,default:1" json:"ratio"` + Seq int64 `bun:"type:bigint,notnull" json:"seq"` + Ratio decimal.Decimal `bun:",notnull" json:"ratio"` Address *string `json:"address"` CustomerName *string `json:"customerName"` ContactName *string `json:"contactName"` ContactPhone *string `json:"contactPhone"` - IsPublicMeter bool `bun:"public_meter,notnull,default:false" json:"isPublicMeter"` - WillDilute bool `bun:"dilute,notnull,default:false" json:"willDilute"` - LastPeriodOverall decimal.Decimal `bun:",notnull,default:0" json:"lastPeriodOverall"` - LastPeriodCritical decimal.Decimal `bun:",notnull,default:0" json:"lastPeriodCritical"` - LastPeriodPeak decimal.Decimal `bun:",notnull,default:0" json:"lastPeriodPeak"` - LastPeriodFlat decimal.Decimal `bun:",notnull,default:0" json:"lastPeriodFlat"` - LastPeriodValley decimal.Decimal `bun:",notnull,default:0" json:"lastPeriodValley"` - CurrentPeriodOverall decimal.Decimal `bun:",notnull,default:0" json:"currentPeriodOverall"` - CurrentPeriodCritical decimal.Decimal `bun:",notnull,default:0" json:"currentPeriodCritical"` - CurrentPeriodPeak decimal.Decimal `bun:",notnull,default:0" json:"currentPeriodPeak"` - CurrentPeriodFlat decimal.Decimal `bun:",notnull,default:0" json:"currentPeriodFlat"` - CurrentPeriodValley decimal.Decimal `bun:",notnull,default:0" json:"currentPeriodValley"` - AdjustOverall decimal.Decimal `bun:",notnull,default:0" json:"adjustOverall"` - AdjustCritical decimal.Decimal `bun:",notnull,default:0" json:"adjustCritical"` - AdjustPeak decimal.Decimal `bun:",notnull,default:0" json:"adjustPeak"` - AdjustFlat decimal.Decimal `bun:",notnull,default:0" json:"adjustFlat"` - AdjustValley decimal.Decimal `bun:",notnull,default:0" json:"adjustValley"` + IsPublicMeter bool `bun:"public_meter,notnull" json:"isPublicMeter"` + WillDilute bool `bun:"dilute,notnull" json:"willDilute"` + LastPeriodOverall decimal.Decimal `bun:",notnull" json:"lastPeriodOverall"` + LastPeriodCritical decimal.Decimal `bun:",notnull" json:"lastPeriodCritical"` + LastPeriodPeak decimal.Decimal `bun:",notnull" json:"lastPeriodPeak"` + LastPeriodFlat decimal.Decimal `bun:",notnull" json:"lastPeriodFlat"` + LastPeriodValley decimal.Decimal `bun:",notnull" json:"lastPeriodValley"` + CurrentPeriodOverall decimal.Decimal `bun:",notnull" json:"currentPeriodOverall"` + CurrentPeriodCritical decimal.Decimal `bun:",notnull" json:"currentPeriodCritical"` + CurrentPeriodPeak decimal.Decimal `bun:",notnull" json:"currentPeriodPeak"` + CurrentPeriodFlat decimal.Decimal `bun:",notnull" json:"currentPeriodFlat"` + CurrentPeriodValley decimal.Decimal `bun:",notnull" json:"currentPeriodValley"` + AdjustOverall decimal.Decimal `bun:",notnull" json:"adjustOverall"` + AdjustCritical decimal.Decimal `bun:",notnull" json:"adjustCritical"` + AdjustPeak decimal.Decimal `bun:",notnull" json:"adjustPeak"` + AdjustFlat decimal.Decimal `bun:",notnull" json:"adjustFlat"` + AdjustValley decimal.Decimal `bun:",notnull" json:"adjustValley"` Overall decimal.NullDecimal `json:"overall"` OverallFee decimal.NullDecimal `json:"overallFee"` - OverallProportion decimal.Decimal `bun:",notnull,default:0" json:"-"` + OverallProportion decimal.Decimal `bun:",notnull" json:"-"` Critical decimal.NullDecimal `json:"critical"` CriticalFee decimal.NullDecimal `json:"criticalFee"` Peak decimal.NullDecimal `json:"peak"` @@ -58,7 +58,7 @@ type EndUserDetail struct { FinalDiluted decimal.NullDecimal `json:"finalDiluted"` FinalCharge decimal.NullDecimal `json:"finalCharge"` Initialize bool `bun:"-" json:"-"` - Origin *Meter04KV `bun:"rel:belongs-to,join:park_id=park_id,join:meter_04kv_id=code"` + Origin *Meter04KV `bun:"rel:belongs-to,join:park_id=park_id,join:meter_04kv_id=code" json:"-"` } var _ bun.BeforeAppendModelHook = (*EndUserDetail)(nil) diff --git a/model/meter_04kv.go b/model/meter_04kv.go index 9854944..cad217a 100644 --- a/model/meter_04kv.go +++ b/model/meter_04kv.go @@ -17,7 +17,7 @@ type Meter04KV struct { CustomerName *string `json:"customerName" excel:"name"` ContactName *string `json:"contactName" excel:"contact"` ContactPhone *string `json:"contactPhone" excel:"phone"` - Ratio decimal.Decimal `bun:",notnull,default:1" json:"ratio" excel:"ratio"` + Ratio decimal.Decimal `bun:",notnull" json:"ratio" excel:"ratio"` Seq int64 `bun:"type:bigint,notnull" json:"seq" excel:"seq"` IsPublicMeter bool `bun:"public_meter,notnull" json:"isPublicMeter" excel:"public"` WillDilute bool `bun:"dilute,notnull" json:"willDilute" excel:"dilute"` diff --git a/model/park.go b/model/park.go index 1700804..b7d048d 100644 --- a/model/park.go +++ b/model/park.go @@ -42,6 +42,7 @@ type Park struct { Enterprise *UserDetail `bun:"rel:belongs-to,join:user_id=id" json:"-"` MaintenanceFees []*MaintenanceFee `bun:"rel:has-many,join:id=park_id" json:"-"` Meters []*Meter04KV `bun:"rel:has-many,join:id=park_id" json:"-"` + Reports []*Report `bun:"rel:has-many,join:id=park_id" json:"-"` } type ParkSimplified struct { diff --git a/model/region.go b/model/region.go index 3fa46f6..8fecddf 100644 --- a/model/region.go +++ b/model/region.go @@ -6,6 +6,6 @@ type Region struct { bun.BaseModel `bun:"table:region,alias:r"` Code string `bun:",pk,notnull" json:"code"` Name string `bun:",notnull" json:"name"` - Level int `bun:",notnull,default:0" json:"level"` - Parent string `bun:",notnull,default:'0'" json:"parent"` + Level int `bun:",notnull" json:"level"` + Parent string `bun:",notnull" json:"parent"` } diff --git a/model/report.go b/model/report.go index fc1a417..0192b6d 100644 --- a/model/report.go +++ b/model/report.go @@ -20,12 +20,12 @@ type Report struct { Id string `bun:",pk,notnull" json:"id"` ParkId string `bun:",notnull" json:"parkId"` Period time.Time `bun:"type:date,notnull" json:"period" time_format:"simple_date" time_location:"shanghai"` - Category int8 `bun:"type:smallint,notnull,default:0" json:"category"` - SubmeterType int8 `bun:"meter_04kv_type,type:smallint,notnull,default:0" json:"meter04kvType"` + Category int8 `bun:"type:smallint,notnull" json:"category"` + SubmeterType int8 `bun:"meter_04kv_type,type:smallint,notnull" json:"meter04kvType"` StepState Steps `bun:"type:jsonb,notnull" json:"stepState"` - Published bool `bun:",notnull,default:false" json:"published"` + Published bool `bun:",notnull" json:"published"` PublishedAt *time.Time `bun:"type:timestamptz,nullzero" json:"publishedAt" time_format:"simple_datetime" time_location:"shanghai"` - Withdraw int8 `bun:"type:smallint,notnull,default:0" json:"withdraw"` + Withdraw int8 `bun:"type:smallint,notnull" json:"withdraw"` LastWithdrawAppliedAt *time.Time `bun:"type:timestamptz,nullzero" json:"lastWithdrawAppliedAt" time_format:"simple_datetime" time_location:"shanghai"` LastWithdrawAuditAt *time.Time `bun:"type:timestamptz,nullzero" json:"lastWithdrawAuditAt" time_format:"simple_datetime" time_location:"shanghai"` Park *Park `bun:"rel:belongs-to,join:park_id=id" json:"-"` @@ -71,9 +71,9 @@ type ReportIndexSimplified struct { ParkId string `bun:",notnull" json:"parkId"` Period Date `bun:"type:date,notnull" json:"period"` StepState Steps `bun:"type:jsonb,notnull" json:"stepState"` - Published bool `bun:",notnull,default:false" json:"published"` + Published bool `bun:",notnull" json:"published"` PublishedAt *time.Time `bun:"type:timestampz" json:"publishedAt" time_format:"simple_datetime" time_location:"shanghai"` - Withdraw int8 `bun:"type:smallint,notnull,default:0" json:"withdraw"` + Withdraw int8 `bun:"type:smallint,notnull" json:"withdraw"` LastWithdrawAppliedAt *time.Time `bun:"type:timestamptz" json:"lastWithdrawAppliedAt" time_format:"simple_datetime" time_location:"shanghai"` LastWithdrawAuditAt *time.Time `bun:"type:timestamptz" json:"lastWithdrawAuditAt" time_format:"simple_datetime" time_location:"shanghai"` } diff --git a/model/report_summary.go b/model/report_summary.go index b8aaf0d..4c096b7 100644 --- a/model/report_summary.go +++ b/model/report_summary.go @@ -10,21 +10,21 @@ import ( type ReportSummary struct { bun.BaseModel `bun:"table:report_summary,alias:rs"` ReportId string `bun:",pk,notnull" json:"-"` - Overall decimal.Decimal `bun:",notnull,default:0" json:"overall"` - OverallFee decimal.Decimal `bun:",notnull,default:0" json:"overallFee"` + Overall decimal.Decimal `bun:",notnull" json:"overall"` + OverallFee decimal.Decimal `bun:",notnull" json:"overallFee"` ConsumptionFee decimal.NullDecimal `json:"consumptionFee"` OverallPrice decimal.NullDecimal `json:"overallPrice"` - Critical decimal.Decimal `bun:",notnull,default:0" json:"critical"` - CriticalFee decimal.Decimal `bun:",notnull,default:0" json:"criticalFee"` + Critical decimal.Decimal `bun:",notnull" json:"critical"` + CriticalFee decimal.Decimal `bun:",notnull" json:"criticalFee"` CriticalPrice decimal.NullDecimal `json:"criticalPrice"` - Peak decimal.Decimal `bun:",notnull,default:0" json:"peak"` - PeakFee decimal.Decimal `bun:",notnull,default:0" json:"peakFee"` + Peak decimal.Decimal `bun:",notnull" json:"peak"` + PeakFee decimal.Decimal `bun:",notnull" json:"peakFee"` PeakPrice decimal.NullDecimal `json:"peakPrice"` - Flat decimal.Decimal `bun:",notnull,default:0" json:"flat"` - FlatFee decimal.Decimal `bun:",notnull,default:0" json:"flatFee"` + Flat decimal.Decimal `bun:",notnull" json:"flat"` + FlatFee decimal.Decimal `bun:",notnull" json:"flatFee"` FlatPrice decimal.NullDecimal `json:"flatPrice"` - Valley decimal.Decimal `bun:",notnull,default:0" json:"valley"` - ValleyFee decimal.Decimal `bun:",notnull,default:0" json:"valleyFee"` + Valley decimal.Decimal `bun:",notnull" json:"valley"` + ValleyFee decimal.Decimal `bun:",notnull" json:"valleyFee"` ValleyPrice decimal.NullDecimal `json:"valleyPrice"` Loss decimal.NullDecimal `json:"loss"` LossFee decimal.NullDecimal `json:"lossFee"` @@ -50,9 +50,9 @@ type ReportSummary struct { PublicConsumptionFlatFee decimal.NullDecimal `json:"publicConsumptionFlatFee"` PublicConsumptionValley decimal.NullDecimal `json:"publicConsumptionValley"` PublicConsumptionValleyFee decimal.NullDecimal `json:"publicConsumptionValleyFee"` - BasicFee decimal.Decimal `bun:",notnull,default:0" json:"basicFee"` + BasicFee decimal.Decimal `bun:",notnull" json:"basicFee"` BasicDilutedPrice decimal.NullDecimal `json:"basicDilutedPrice"` - AdjustFee decimal.Decimal `bun:",notnull,default:0" json:"adjustFee"` + AdjustFee decimal.Decimal `bun:",notnull" json:"adjustFee"` AdjustDilutedPrice decimal.NullDecimal `json:"adjustDilutedPrice"` MaintenanceDilutedPrice decimal.NullDecimal `json:"maintencanceDilutedPrice"` LossDilutedPrice decimal.NullDecimal `json:"lossDilutedPrice"` diff --git a/model/user_charges.go b/model/user_charges.go index e2902c5..19cf64b 100644 --- a/model/user_charges.go +++ b/model/user_charges.go @@ -17,11 +17,11 @@ type UserCharge struct { Discount decimal.NullDecimal `json:"discount"` Amount decimal.NullDecimal `json:"amount"` ChargeTo Date `bun:"type:date,notnull" json:"chargeTo"` - Settled bool `bun:",notnull,default:false" json:"settled"` + Settled bool `bun:",notnull" json:"settled"` SettledAt *time.Time `bun:"type:timestamptz" json:"settledAt" time_format:"simple_datetime" time_location:"shanghai"` - Cancelled bool `bun:",notnull,default:false" json:"cancelled"` + Cancelled bool `bun:",notnull" json:"cancelled"` CancelledAt *time.Time `bun:"type:timestamptz" json:"cancelledAt" time_format:"simple_datetime" time_location:"shanghai"` - Refunded bool `bun:",notnull,default:false" json:"refunded"` + Refunded bool `bun:",notnull" json:"refunded"` RefundedAt *time.Time `bun:"type:timestamptz" json:"refundedAt" time_format:"simple_datetime" time_location:"shanghai"` Detail *UserDetail `bun:"rel:belongs-to,join:user_id=id" json:"-"` } diff --git a/model/will_diluted_fee.go b/model/will_diluted_fee.go index e2fe073..16178cc 100644 --- a/model/will_diluted_fee.go +++ b/model/will_diluted_fee.go @@ -1,6 +1,9 @@ package model import ( + "context" + "time" + "github.com/shopspring/decimal" "github.com/uptrace/bun" ) @@ -12,7 +15,21 @@ type WillDilutedFee struct { ReportId string `bun:",notnull" json:"reportId"` SourceId *string `json:"sourceId"` Name string `bun:",notnull" json:"name"` - Fee decimal.Decimal `bun:",notnull,default:0" json:"fee"` + Fee decimal.Decimal `bun:",notnull" json:"fee"` Memo *string `bun:"type:text" json:"memo"` Origin *MaintenanceFee `bun:"rel:belongs-to,join:source_id=id"` } + +var _ bun.BeforeAppendModelHook = (*WillDilutedFee)(nil) + +func (d *WillDilutedFee) BeforeAppendModel(ctx context.Context, query bun.Query) error { + oprTime := time.Now() + switch query.(type) { + case *bun.InsertQuery: + d.CreatedAt = oprTime + d.LastModifiedAt = &oprTime + case *bun.UpdateQuery: + d.LastModifiedAt = &oprTime + } + return nil +} diff --git a/service/end_user.go b/service/end_user.go index 1e0fad8..00ed5c5 100644 --- a/service/end_user.go +++ b/service/end_user.go @@ -120,7 +120,7 @@ func (_EndUserService) UpdateEndUserRegisterRecord(tx *bun.Tx, ctx *context.Cont "current_period_critical", "current_period_peak", "current_period_flat", - "current_perios_valley", + "current_period_valley", "adjust_critical", "adjust_peak", "adjust_flat", diff --git a/service/report.go b/service/report.go index 0609fb8..37a90b8 100644 --- a/service/report.go +++ b/service/report.go @@ -36,37 +36,34 @@ func (_ReportService) FetchParksWithNewestReport(uid string) ([]model.ParkNewest ctx, cancel := global.TimeoutContext() defer cancel() - reports := make([]model.Report, 0) - err := global.DB.NewSelect().Model(&reports).Relation("Park"). - Where("p.user_id = ?", uid). - Where("p.enabled = ?", true). + parks := make([]model.Park, 0) + err := global.DB.NewSelect().Model(&parks).Relation("Reports"). + Where("user_id = ?", uid). + Where("enabled = ?", true). + Order("created_at asc"). Scan(ctx) if err != nil { return make([]model.ParkNewestReport, 0), err } reducedParks := lo.Reduce( - reports, - func(acc map[string]model.ParkNewestReport, elem model.Report, index int) map[string]model.ParkNewestReport { - if v, ok := acc[elem.Park.Id]; ok { - if v.Report == nil || (elem.Period.After(v.Report.Period)) { - acc[elem.Park.Id] = model.ParkNewestReport{ - Report: &elem, - Park: *elem.Park, - } - } - } else { - acc[elem.Park.Id] = model.ParkNewestReport{ - Report: &elem, - Park: *elem.Park, + parks, + func(acc map[string]model.ParkNewestReport, elem model.Park, index int) map[string]model.ParkNewestReport { + if _, ok := acc[elem.Id]; !ok { + newestReport := lo.MaxBy(elem.Reports, func(a, b *model.Report) bool { + return a.Period.After(b.Period) + }) + acc[elem.Id] = model.ParkNewestReport{ + Report: newestReport, + Park: elem, } } return acc }, make(map[string]model.ParkNewestReport, 0), ) - relations := lo.Map(reports, func(r model.Report, _ int) string { - return fmt.Sprintf("report:%s", r.Id) + relations := lo.Map(parks, func(r model.Park, _ int) string { + return fmt.Sprintf("park:%s", r.Id) }) relations = append(relations, "park", "report") cache.CacheSearch(reducedParks, relations, "park_newest_report", uid) @@ -81,11 +78,11 @@ func (_ReportService) IsNewPeriodValid(uid, pid string, period time.Time) (bool, reports = *cachedReport } else { err := global.DB.NewSelect().Model(&reports).Relation("Park"). - Where("p.user_id = ?", uid). + Where("park.user_id = ?", uid). Where("r.park_id = ?", pid). Scan(ctx) if err != nil { - return false, nil + return false, err } cache.CacheSearch(reports, []string{"report", "park"}, "park", "user", uid, "park", pid) } @@ -430,7 +427,8 @@ func (_ReportService) UpdateMaintenanceFee(feeId string, updates map[string]inte ctx, cancel := global.TimeoutContext() defer cancel() - _, err = global.DB.NewUpdate().Model(updates).TableExpr("will_diluted_fee"). + updates["last_modified_at"] = lo.ToPtr(time.Now()) + _, err = global.DB.NewUpdate().Model(&updates).TableExpr("will_diluted_fee"). Where("id = ?", feeId). Exec(ctx) cache.AbolishRelation(fmt.Sprintf("will_diluted_fee:%s", feeId)) @@ -454,6 +452,7 @@ func (_ReportService) ProgressReportWillDilutedFee(report model.Report) (err err report.StepState.WillDiluted = true _, err = global.DB.NewUpdate().Model(&report). + WherePK(). Column("step_state"). Exec(ctx) cache.AbolishRelation(fmt.Sprintf("report:%s", report.Id)) @@ -466,6 +465,7 @@ func (_ReportService) ProgressReportRegisterEndUser(report model.Report) (err er report.StepState.Submeter = true _, err = global.DB.NewUpdate().Model(&report). + WherePK(). Column("step_state"). Exec(ctx) cache.AbolishRelation(fmt.Sprintf("report:%s", report.Id)) @@ -478,6 +478,7 @@ func (_ReportService) ProgressReportCalculate(report model.Report) (err error) { report.StepState.Calculate = true _, err = global.DB.NewUpdate().Model(&report). + WherePK(). Column("step_state"). Exec(ctx) cache.AbolishRelation(fmt.Sprintf("report:%s", report.Id)) @@ -492,7 +493,11 @@ func (_ReportService) RetreiveParkEndUserMeterType(reportId string) (int, error) defer cancel() var mType int - err := global.DB.NewSelect().Model((*model.Report)(nil)).Relation("Park"). + err := global.DB.NewSelect().Model((*model.Report)(nil)). + Relation("Park", func(q *bun.SelectQuery) *bun.SelectQuery { + return q.Column("meter_04kv_type") + }). + ExcludeColumn("*"). Where("r.id = ?", reportId). Scan(ctx, &mType) if err != nil { @@ -597,14 +602,19 @@ func (_ReportService) AssembleReportPublicity(reportId string) (*model.Publicity var report = new(model.Report) err := global.DB.NewSelect().Model(report). Relation("Summary").Relation("WillDilutedFees").Relation("EndUsers"). - Relation("Park", func(q *bun.SelectQuery) *bun.SelectQuery { - return q.Relation("Enterprise") - }). - Where("id = ?", reportId). + Relation("Park"). + Where("r.id = ?", reportId). Scan(ctx) - if err != nil || report == nil { + if err != nil { return nil, exceptions.NewNotFoundErrorFromError("未找到指定的公示报表", err) } + var enterprise = new(model.UserDetail) + err = global.DB.NewSelect().Model(enterprise). + Where("id = ?", report.Park.UserId). + Scan(ctx) + if err != nil { + return nil, exceptions.NewNotFoundErrorFromError("未找到指定公示报表对应的用户信息", err) + } // 组合数据 paidPart := model.PaidPart{ @@ -719,7 +729,7 @@ func (_ReportService) AssembleReportPublicity(reportId string) (*model.Publicity publicity := &model.Publicity{ Report: *report, Park: *report.Park, - User: *report.Park.Enterprise, + User: *enterprise, Paid: paidPart, EndUser: endUserSummary, Loss: lossPart,