82 lines
2.3 KiB
Go
82 lines
2.3 KiB
Go
package service
|
|
|
|
import (
|
|
"electricity_bill_calc/cache"
|
|
"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) {
|
|
if cachedCount, err := cache.RetreiveCount("enabled_ent"); cachedCount != -1 && err == nil {
|
|
return cachedCount, nil
|
|
}
|
|
c, err := global.DBConn.
|
|
Table(new(model.User)).
|
|
Where(builder.Eq{"type": 0, "enabled": true}).
|
|
Count()
|
|
if err == nil {
|
|
cache.CacheCount([]string{"user"}, "enabled_ent", c)
|
|
}
|
|
return c, err
|
|
}
|
|
|
|
func (_StatisticsService) EnabledParks(userIds ...string) (int64, error) {
|
|
if cachedParks, err := cache.RetreiveCount("enabled_parks", userIds...); cachedParks != -1 && err == nil {
|
|
return cachedParks, nil
|
|
}
|
|
cond := builder.NewCond().And(builder.Eq{"enabled": true})
|
|
if len(userIds) > 0 {
|
|
cond = cond.And(builder.Eq{"user_id": userIds})
|
|
}
|
|
c, err := global.DBConn.
|
|
Table(new(model.Park)).
|
|
Where(cond).
|
|
Count()
|
|
if err == nil {
|
|
cache.CacheCount([]string{"user", "park"}, "enabled_parks", c, userIds...)
|
|
}
|
|
return c, err
|
|
}
|
|
|
|
func (_StatisticsService) ParksNewestState(userIds ...string) ([]model.ParkPeriodStatistics, error) {
|
|
if cachedState, _ := cache.RetreiveSearch[[]model.ParkPeriodStatistics]("park_period_stat", userIds...); cachedState != nil {
|
|
return *cachedState, nil
|
|
}
|
|
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
|
|
}
|
|
}
|
|
cache.CacheSearch(lo.Values(groupedParks), []string{"user", "park"}, "park_period_stat", userIds...)
|
|
return lo.Values(groupedParks), nil
|
|
}
|