package web import ( "context" "errors" "net/http" "strconv" "strings" "time" "supermarket/internal/metrics" ) func (s *Server) metricsPage(w http.ResponseWriter, r *http.Request) { s.renderMetrics(w, r, "") } func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg string) { counts, err := metrics.Counts(s.DB) if err != nil { s.serverError(w, err) return } products, err := metrics.Products(s.DB, time.Now()) if err != nil { s.serverError(w, err) return } s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{ "Stripe": s.stripe() != nil, "Last": metrics.LastSync(s.DB), "Counts": counts, "Products": products, "Margins": metrics.LoadMargins(s.DB), }}) } // metricsMargins saves the gross margins: the default, and per product (an // empty box uses the default). func (s *Server) metricsMargins(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } parse := func(v string) (float64, bool, error) { v = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(v), "%")) if v == "" { return 0, false, nil } f, err := strconv.ParseFloat(v, 64) return f, true, err } m := metrics.Margins{ByProduct: map[string]float64{}} def, ok, err := parse(r.PostFormValue("default")) if err != nil || !ok { s.renderMetrics(w, r, "Give the default margin as a percentage.") return } m.Default = def for key, vals := range r.PostForm { id, isProduct := strings.CutPrefix(key, "margin:") if !isProduct || len(vals) == 0 { continue } v, set, err := parse(vals[0]) if err != nil { s.renderMetrics(w, r, "A margin isn't a number: "+vals[0]) return } if set { m.ByProduct[id] = v } } if err := metrics.SaveMargins(s.DB, m); err != nil { s.renderMetrics(w, r, err.Error()) return } redirect(w, r, "/metrics#margins", "saved") } // metricsSync syncs Stripe now; "full" reads everything again. func (s *Server) metricsSync(w http.ResponseWriter, r *http.Request) { c := s.stripe() if c == nil { s.renderMetrics(w, r, "Save a Stripe key under Settings → Website & sales first.") return } ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute) defer cancel() if _, err := metrics.Sync(ctx, s.DB, c, time.Now(), r.PostFormValue("full") == "1"); err != nil { s.renderMetrics(w, r, "Syncing Stripe: "+err.Error()) return } redirect(w, r, "/metrics", "synced") } // RunMetrics syncs Stripe every hour. func (s *Server) RunMetrics(ctx context.Context) { tick := time.NewTicker(10 * time.Minute) defer tick.Stop() for { if c := s.stripe(); c != nil { last := metrics.LastSync(s.DB) if last == nil || time.Since(last.At) >= time.Hour { sctx, cancel := context.WithTimeout(ctx, 30*time.Minute) if _, err := metrics.Sync(sctx, s.DB, c, time.Now(), false); err != nil && !errors.Is(err, context.Canceled) { s.Log.Warn("metrics: Stripe sync", "err", err) } cancel() } } select { case <-ctx.Done(): return case <-tick.C: } } }