Files
supermarket/internal/web/tracking.go
davidandClaude Opus 5.5 2c242d8c94 Phase 4 part 1: the full Stripe sync, and margins per product
Customers, invoices with all their lines (both of Stripe's line shapes),
credit notes, refunds (with their customer) and products: a backfill,
then the Events API every hour, and a new backfill when events have
expired. Metrics page with sync status. Gross margin per product: a
default (60%) and overrides, with names from Stripe's products or the
invoice lines. Schemas 18 and 19.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 09:24:32 -07:00

238 lines
6.7 KiB
Go

package web
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/api/plausible"
"supermarket/internal/api/stripe"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/tracking"
)
var (
plausibleKey = secretField{"plausible", secrets.PlausibleAPIKey, "Stats API key",
"In Plausible, your account settings → API Keys → New API key, of the Stats API kind.", ""}
stripeKey = secretField{"stripe", secrets.StripeAPIKey, "Restricted key",
"In Stripe, Developers → API keys → Create restricted key, with Read access only, to Checkout Sessions, Invoices, Customers, Credit notes, Charges and Refunds, and Events (the last four for Metrics). It starts rk_live_.", "https://dashboard.stripe.com/apikeys"}
)
const plausibleURLKey = "tracking:plausible-url"
// Test hooks: other servers for the APIs.
var (
stripeBase = ""
)
// plausibleURL is Plausible's address: the saved one, or the Core's.
func (s *Server) plausibleURL() string {
var u string
if _, err := s.DB.GetJSON(plausibleURLKey, &u); err == nil && u != "" {
return u
}
if s.Core != nil && s.Core.Domain != "" {
return "https://plausible." + s.Core.Domain
}
return "https://plausible.io"
}
func (s *Server) plausible() *plausible.Client {
key := s.Secrets.Get(secrets.PlausibleAPIKey)
if key == "" {
return nil
}
return plausible.New(s.plausibleURL(), key)
}
func (s *Server) stripe() *stripe.Client {
key := s.Secrets.Get(secrets.StripeAPIKey)
if key == "" {
return nil
}
c := stripe.New(key)
if stripeBase != "" {
c.WithBase(stripeBase)
}
return c
}
func (s *Server) sites() []string {
p, _ := profile.Load(s.DB)
if p == nil {
return nil
}
return tracking.Sites(p)
}
func (s *Server) trackingPage(w http.ResponseWriter, r *http.Request) {
s.renderTracking(w, r, "")
}
func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg string) {
lastP, _ := tracking.Last(s.DB, tracking.SourcePlausible)
lastS, _ := tracking.Last(s.DB, tracking.SourceStripe)
customers, _ := tracking.Customers(s.DB, 20)
set, _ := s.outreachSettings()
s.render(w, r, "tracking", page{Title: "Website & sales", Nav: "settings/tracking", Error: errMsg, Data: map[string]any{
"PlausibleURL": s.plausibleURL(),
"PlausibleKey": plausibleKey,
"PlausibleSet": s.Secrets.Has(secrets.PlausibleAPIKey),
"Sites": s.sites(),
"LastPlausible": lastP,
"StripeKey": stripeKey,
"StripeSet": s.Secrets.Has(secrets.StripeAPIKey),
"LastStripe": lastS,
"Customers": customers,
"BookingFrom": set.BookingFrom,
}})
}
func (s *Server) trackingSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
u := strings.TrimRight(strings.TrimSpace(r.PostFormValue("plausible_url")), "/")
if u != "" && !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
s.renderTracking(w, r, "Plausible's address must start with https://")
return
}
if err := s.DB.PutJSON(plausibleURLKey, u); err != nil {
s.serverError(w, err)
return
}
if err := s.saveSecrets(r, []secretField{plausibleKey, stripeKey}); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/tracking", "saved")
}
// trackingTest checks a key: Plausible's against each site, Stripe's
// against checkouts and invoices.
func (s *Server) trackingTest(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
data := map[string]any{}
switch r.PathValue("source") {
case tracking.SourcePlausible:
c := s.plausible()
if c == nil {
data["Error"] = "Save the key first."
break
}
sites := s.sites()
if len(sites) == 0 {
data["Error"] = "Add your websites to the profile first."
break
}
var ok, bad []string
for _, site := range sites {
n, err := c.Visitors(ctx, site)
if err != nil {
bad = append(bad, site+": "+err.Error())
} else {
ok = append(ok, site+": "+strconv.Itoa(n)+" visitors in the last 30 days")
}
}
if len(ok) > 0 {
data["OK"] = "The key works. " + strings.Join(ok, "; ") + "."
}
if len(bad) > 0 {
data["Error"] = strings.Join(bad, "; ")
}
case tracking.SourceStripe:
c := s.stripe()
if c == nil {
data["Error"] = "Save the key first."
break
}
if err := c.Check(ctx); err != nil {
data["Error"] = err.Error()
break
}
if c.Live() {
data["OK"] = "The key works: it can read checkouts and invoices (live data)."
} else {
data["OK"] = "The key works, but it's a test-mode key: it reads test data, not real customers."
}
default:
http.NotFound(w, r)
return
}
s.fragment(w, "sources", "test-result", data)
}
// trackingRun imports from one source now.
func (s *Server) trackingRun(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
if err := s.runTracking(ctx, r.PathValue("source")); err != nil {
s.renderTracking(w, r, err.Error())
return
}
redirect(w, r, "/settings/tracking", "imported")
}
func (s *Server) runTracking(ctx context.Context, source string) error {
now := time.Now()
switch source {
case tracking.SourcePlausible:
c := s.plausible()
if c == nil {
return errors.New("save the Plausible key first")
}
_, err := tracking.ImportPlausible(ctx, s.DB, c, s.sites(), now)
return err
case tracking.SourceStripe:
c := s.stripe()
if c == nil {
return errors.New("save the Stripe key first")
}
_, err := tracking.SyncStripe(ctx, s.DB, c, now)
return err
}
return errors.New("unknown source")
}
// RunTracking reads Plausible once a day (yesterday's visits) and Stripe
// every hour.
func (s *Server) RunTracking(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
tried := map[string]time.Time{}
for {
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
for _, src := range []string{tracking.SourcePlausible, tracking.SourceStripe} {
if (src == tracking.SourcePlausible && s.plausible() == nil) || (src == tracking.SourceStripe && s.stripe() == nil) {
continue
}
last, _ := tracking.Last(s.DB, src)
due := last == nil || time.Since(last.At) >= time.Hour
if src == tracking.SourcePlausible && last != nil && last.Error == "" && last.Through >= yesterday {
due = false
}
// After a failure, wait an hour before trying again.
if !due || time.Since(tried[src]) < time.Hour {
continue
}
tried[src] = time.Now()
rctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
if err := s.runTracking(rctx, src); err != nil {
s.Log.Warn("tracking: import failed", "source", src, "err", err)
}
cancel()
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}