63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"electricity_bill_calc/global"
|
|
"electricity_bill_calc/model"
|
|
|
|
"github.com/samber/lo"
|
|
"xorm.io/builder"
|
|
)
|
|
|
|
type _StatisticsService struct{}
|
|
|
|
var StatisticsService _StatisticsService
|
|
|
|
func (_StatisticsService) EnabledEnterprises() (int64, error) {
|
|
return global.DBConn.
|
|
Table(new(model.User)).
|
|
Where(builder.Eq{"type": 0, "enabled": true}).
|
|
Count()
|
|
}
|
|
|
|
func (_StatisticsService) EnabledParks(userIds ...string) (int64, error) {
|
|
cond := builder.NewCond().And(builder.Eq{"enabled": true})
|
|
if len(userIds) > 0 {
|
|
cond = cond.And(builder.Eq{"user_id": userIds})
|
|
}
|
|
return global.DBConn.
|
|
Table(new(model.Park)).
|
|
Where(cond).
|
|
Count()
|
|
}
|
|
|
|
func (_StatisticsService) ParksNewestState(userIds ...string) ([]model.ParkPeriodStatistics, error) {
|
|
cond := builder.NewCond().And(builder.Eq{"p.enabled": true, "r.published": true})
|
|
if len(userIds) > 0 {
|
|
cond = cond.And(builder.Eq{"p.user_id": userIds})
|
|
}
|
|
parks := make([]model.ParkPeriodStatistics, 0)
|
|
groupedParks := make(map[string]model.ParkPeriodStatistics, 0)
|
|
err := global.DBConn.
|
|
Table("park").Alias("p").
|
|
Join("LEFT", []string{"report", "r"}, "r.park_id=p.id").
|
|
Where(cond).
|
|
Cols("p.id", "p.name", "r.period").
|
|
Find(&parks)
|
|
if err != nil {
|
|
return make([]model.ParkPeriodStatistics, 0), err
|
|
}
|
|
for _, p := range parks {
|
|
if c, ok := groupedParks[p.Id]; ok {
|
|
if c.Period != nil && p.Period != nil && p.Period.After(*c.Period) {
|
|
groupedParks[p.Id] = p
|
|
}
|
|
if c.Period == nil && p.Period != nil {
|
|
groupedParks[p.Id] = p
|
|
}
|
|
} else {
|
|
groupedParks[p.Id] = p
|
|
}
|
|
}
|
|
return lo.Values(groupedParks), nil
|
|
}
|