package web import ( "context" "errors" "fmt" "net/http" "net/url" "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() // The links visitors clicked, to say which are sign-ups. var links []tracking.OutboundLink if c := s.plausible(); c != nil { ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) for _, site := range s.sites() { l, err := tracking.OutboundLinks(ctx, c, site) if err == nil { links = append(links, l...) } } cancel() } var urls []string for _, l := range links { urls = append(urls, l.URL) } signups := tracking.LoadSignups(s.DB, urls) var own []string // patterns that aren't one of the links, to edit as text for i := range links { links[i].Signup = signups.Matches(links[i].URL) } for _, p := range signups.Patterns { listed := false for _, l := range links { if strings.EqualFold(patternOf(l.URL), p) { listed = true } } if !listed { own = append(own, p) } } lastPages, _ := tracking.Last(s.DB, "pages") 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, "Links": links, "Signups": signups, "OwnPatterns": strings.Join(own, "\n"), "LastPages": lastPages, }}) } 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) if _, perr := tracking.ImportPages(ctx, s.DB, c, s.sites(), now); perr != nil && err == nil { err = fmt.Errorf("pages: %w", perr) } if p, _ := profile.Load(s.DB); p != nil { if _, rerr := tracking.ImportReferrers(ctx, s.DB, c, p.Websites, now); rerr != nil && err == nil { err = fmt.Errorf("referring sites: %w", rerr) } } 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: } } } // patternOf is the pattern a ticked link saves as: its host and path. func patternOf(link string) string { if p := tracking.SuggestSignups([]string{link}); len(p) > 0 { return p[0] } if u, err := url.Parse(link); err == nil && u.Host != "" { return strings.ToLower(u.Host + strings.TrimRight(u.Path, "/")) } return strings.ToLower(link) } // trackingSignups saves what counts as a sign-up, and reads the pages // again with it. func (s *Server) trackingSignups(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var pats []string for _, l := range r.PostForm["link"] { pats = append(pats, patternOf(l)) } pats = append(pats, strings.Split(r.PostFormValue("patterns"), "\n")...) if err := tracking.SaveSignups(s.DB, pats); err != nil { s.serverError(w, err) return } if c := s.plausible(); c != nil { ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) _, err := tracking.ImportPages(ctx, s.DB, c, s.sites(), time.Now()) cancel() if err != nil { s.renderTracking(w, r, "Saved, but reading the pages again failed: "+err.Error()) return } } redirect(w, r, "/settings/tracking#signups", "signups-saved") } // convDays is the period the page tables show visits and sign-ups for, as // What ranks shows Search Console's. const convDays = 90 // pageConv is a website's visits, sign-ups and leads by page over the last // convDays, or nil before Plausible's pages were read. func (s *Server) pageConv(siteURL string) map[string]tracking.PageNumbers { p, _ := profile.Load(s.DB) if p == nil { return nil } want := strings.TrimRight(strings.ToLower(strings.TrimSpace(siteURL)), "/") for _, w := range p.Websites { if strings.TrimRight(strings.ToLower(strings.TrimSpace(w.URL)), "/") != want { continue } pages, ok, err := tracking.Pages(s.DB, tracking.SiteID(w), convDays) if err != nil || !ok { return nil } return pages } return nil }