2020-09-06 13:15:46 +03:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"github.com/muety/wakapi/models"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-09-12 17:09:23 +03:00
|
|
|
func ResolveInterval(interval string) (err error, from, to time.Time) {
|
|
|
|
to = time.Now()
|
|
|
|
|
|
|
|
switch interval {
|
|
|
|
case models.IntervalToday:
|
|
|
|
from = StartOfToday()
|
|
|
|
case models.IntervalYesterday:
|
|
|
|
from = StartOfToday().Add(-24 * time.Hour)
|
|
|
|
to = StartOfToday()
|
|
|
|
case models.IntervalThisWeek:
|
|
|
|
from = StartOfWeek()
|
|
|
|
case models.IntervalThisMonth:
|
|
|
|
from = StartOfMonth()
|
|
|
|
case models.IntervalThisYear:
|
|
|
|
from = StartOfYear()
|
|
|
|
case models.IntervalPast7Days:
|
|
|
|
from = StartOfToday().AddDate(0, 0, -7)
|
|
|
|
case models.IntervalPast30Days:
|
|
|
|
from = StartOfToday().AddDate(0, 0, -30)
|
|
|
|
case models.IntervalPast12Months:
|
|
|
|
from = StartOfToday().AddDate(0, -12, 0)
|
|
|
|
case models.IntervalAny:
|
|
|
|
from = time.Time{}
|
|
|
|
default:
|
|
|
|
err = errors.New("invalid interval")
|
|
|
|
}
|
|
|
|
|
|
|
|
return err, from, to
|
|
|
|
}
|
|
|
|
|
2020-09-06 13:15:46 +03:00
|
|
|
func ParseSummaryParams(r *http.Request) (*models.SummaryParams, error) {
|
|
|
|
user := r.Context().Value(models.UserKey).(*models.User)
|
|
|
|
params := r.URL.Query()
|
|
|
|
|
2020-09-12 17:09:23 +03:00
|
|
|
var err error
|
2020-09-12 13:40:38 +03:00
|
|
|
var from, to time.Time
|
|
|
|
|
|
|
|
if interval := params.Get("interval"); interval != "" {
|
2020-09-12 17:09:23 +03:00
|
|
|
err, from, to = ResolveInterval(interval)
|
2020-09-12 13:40:38 +03:00
|
|
|
} else {
|
|
|
|
from, err = ParseDate(params.Get("from"))
|
|
|
|
if err != nil {
|
2020-09-06 13:15:46 +03:00
|
|
|
return nil, errors.New("missing 'from' parameter")
|
|
|
|
}
|
|
|
|
|
2020-09-12 13:40:38 +03:00
|
|
|
to, err = ParseDate(params.Get("to"))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.New("missing 'to' parameter")
|
|
|
|
}
|
|
|
|
}
|
2020-09-06 13:15:46 +03:00
|
|
|
|
|
|
|
recompute := params.Get("recompute") != "" && params.Get("recompute") != "false"
|
|
|
|
|
|
|
|
return &models.SummaryParams{
|
|
|
|
From: from,
|
|
|
|
To: to,
|
|
|
|
User: user,
|
|
|
|
Recompute: recompute,
|
|
|
|
}, nil
|
|
|
|
}
|