Files
zarinpal-analytics-backend/internal/insight/time.go

50 lines
1.4 KiB
Go

package insight
import "time"
type Freshness string
const (
FreshnessFresh Freshness = "FRESH"
FreshnessLagging Freshness = "LAGGING"
FreshnessStale Freshness = "STALE"
)
type TimeContext struct {
AsOfDate string `json:"asOfDate"`
DataThroughDate string `json:"dataThroughDate"`
ForecastStartDate string `json:"forecastStartDate"`
Freshness Freshness `json:"freshness"`
DataLagDays int `json:"dataLagDays"`
}
func BuildTimeContext(now, dataThrough time.Time) TimeContext {
location, err := time.LoadLocation("Asia/Tehran")
if err != nil {
location = time.FixedZone("Asia/Tehran", 3*60*60+30*60)
}
today := dateOnly(now.In(location), location)
through := dateOnly(dataThrough.In(location), location)
lag := max(0, int(today.Sub(through).Hours()/24))
return TimeContext{
AsOfDate: today.Format(time.DateOnly), DataThroughDate: through.Format(time.DateOnly),
ForecastStartDate: today.Format(time.DateOnly), Freshness: ClassifyFreshness(lag), DataLagDays: lag,
}
}
func ClassifyFreshness(lagDays int) Freshness {
switch {
case lagDays <= 1:
return FreshnessFresh
case lagDays <= 7:
return FreshnessLagging
default:
return FreshnessStale
}
}
func dateOnly(value time.Time, location *time.Location) time.Time {
year, month, day := value.In(location).Date()
return time.Date(year, month, day, 0, 0, 0, 0, location)
}