// Package tracking brings the end of the funnel in: visits to the // company's websites from Plausible, counted per buying signal by the // campaign tag on the link that brought them; and sign-ups and payments // from Stripe, tied to a signal by the campaign the shopping cart saved // with the checkout, or else by who paid. Both only read. package tracking import ( "context" "errors" "fmt" "net/url" "strings" "time" "supermarket/internal/api/plausible" "supermarket/internal/db" "supermarket/internal/profile" "supermarket/internal/signals" ) // Event sources. const ( SourcePlausible = "plausible" SourceStripe = "stripe" ) // Result is what one import did. type Result struct { At time.Time `json:"at"` Added int `json:"added"` // funnel steps recorded Detail string `json:"detail,omitempty"` Error string `json:"error,omitempty"` Through string `json:"through,omitempty"` // Plausible: the last day read } func resultKey(source string) string { return "tracking:last:" + source } // Last is an import's last result, or nil. func Last(d *db.DB, source string) (*Result, error) { var r Result ok, err := d.GetJSON(resultKey(source), &r) if err != nil || !ok { return nil, err } return &r, nil } func save(d *db.DB, source string, r *Result, err error) (*Result, error) { if err != nil { r.Error = err.Error() } if perr := d.PutJSON(resultKey(source), r); perr != nil && err == nil { err = perr } return r, err } // Channel is the funnel channel for a link's UTM source and medium: the // direct channels by name, social posts, or the website. func Channel(source, medium string) string { source, medium = strings.ToLower(source), strings.ToLower(medium) switch { case medium == "outreach" && (source == "email" || source == "linkedin"): return source case medium == "email" || source == "email" || source == "newsletter": return "email" case medium == "social" || source == "x" || source == "twitter" || source == "linkedin" || source == "reddit" || source == "facebook" || source == "mastodon" || source == "bluesky": return "social" case source == "blog" || medium == "blog": return "blog" } return "website" } // slugs maps each signal's campaign tag to its ID. func slugs(d *db.DB) (map[string]int64, error) { list, err := signals.List(d) if err != nil { return nil, err } out := map[string]int64{} for _, s := range list { out[strings.ToLower(s.Slug)] = s.ID } return out, nil } // Sites are the Plausible site IDs of the company's websites: each one's // Plausible site if set, else its domain. func Sites(p *profile.Profile) []string { var out []string seen := map[string]bool{} for _, w := range p.Websites { site := plausibleSite(w.PlausibleSite) if site == "" { if u, err := url.Parse(strings.TrimSpace(w.URL)); err == nil { site = strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") } } if site != "" && !seen[site] { seen[site] = true out = append(out, site) } } return out } // firstDays is how far back the first Plausible import reads. const firstDays = 30 const dayFormat = "2006-01-02" func plausibleStateKey(site string) string { return "tracking:plausible-through:" + site } // ImportPlausible reads, for each site, the visitors per day that came on a // link tagged with a signal's campaign, by source, medium and content, for // the whole days since the last import (today is read tomorrow, when it's // complete). Visits are counted per signal, never per person. func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites []string, now time.Time) (*Result, error) { res := &Result{At: now} if len(sites) == 0 { return save(d, SourcePlausible, res, errors.New("no websites in the profile to read")) } tags, err := slugs(d) if err != nil { return save(d, SourcePlausible, res, err) } if len(tags) == 0 { res.Detail = "No signals yet, so no campaigns to look for." return save(d, SourcePlausible, res, nil) } var campaigns []any for slug := range tags { campaigns = append(campaigns, slug) } yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat) visits := 0 for _, site := range sites { var through string if _, err := d.GetJSON(plausibleStateKey(site), &through); err != nil { return save(d, SourcePlausible, res, err) } from := now.Local().AddDate(0, 0, -firstDays).Format(dayFormat) if through != "" { t, _ := time.ParseInLocation(dayFormat, through, time.Local) from = t.AddDate(0, 0, 1).Format(dayFormat) } if from > yesterday { continue } rows, err := c.Run(ctx, plausible.Query{ SiteID: site, Metrics: []string{"visitors"}, DateRange: []string{from, yesterday}, Dimensions: []string{"time:day", "visit:utm_campaign", "visit:utm_source", "visit:utm_medium", "visit:utm_content"}, Filters: [][]any{{"is", "visit:utm_campaign", campaigns}}, Pagination: &plausible.Pagination{Limit: 10000}, }) if err != nil { return save(d, SourcePlausible, res, fmt.Errorf("%s: %w", site, err)) } for _, r := range rows { if len(r.Dimensions) < 5 || len(r.Metrics) < 1 || r.Metrics[0] < 1 { continue } day, campaign, source, medium, content := r.Dimensions[0], r.Dimensions[1], r.Dimensions[2], r.Dimensions[3], r.Dimensions[4] sig, ok := tags[strings.ToLower(campaign)] if !ok { continue } at, err := time.ParseInLocation(dayFormat, day[:min(len(day), 10)], time.Local) if err != nil { continue } n := int(r.Metrics[0]) note := strings.Trim(none(source)+" / "+none(medium), " /") if c := none(content); c != "" { note += " ยท " + c } added, err := signals.Record(d, signals.Event{ SignalID: sig, Stage: signals.StageVisited, Channel: Channel(none(source), none(medium)), Source: SourcePlausible, Count: n, Note: site + ": " + note, At: at.Add(12 * time.Hour), ExternalID: strings.Join([]string{site, day, campaign, source, medium, content}, "|"), }) if err != nil { return save(d, SourcePlausible, res, err) } if added { res.Added++ visits += n } } if err := d.PutJSON(plausibleStateKey(site), yesterday); err != nil { return save(d, SourcePlausible, res, err) } } res.Through = yesterday res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal.", visits) return save(d, SourcePlausible, res, nil) } // none is "" for Plausible's empty values. func none(v string) string { if v == "(none)" || v == "(not set)" { return "" } return v } // plausibleSite is a site ID from what the profile holds, which may be the // dashboard's address instead (https://plausible.example.com/example.com) // or the Plausible server itself; that last one gives "", so the // website's domain is used. func plausibleSite(v string) string { v = strings.TrimSpace(strings.ToLower(v)) if strings.Contains(v, "://") { u, err := url.Parse(v) if err != nil { return "" } path := strings.Trim(u.Path, "/") if path == "" { return "" } parts := strings.Split(path, "/") v = parts[len(parts)-1] } if strings.HasPrefix(v, "plausible.") { return "" } return v } // SiteID is a website's Plausible site ID: its Plausible site if set, else // its domain. func SiteID(w profile.Website) string { if site := plausibleSite(w.PlausibleSite); site != "" { return site } if u, err := url.Parse(strings.TrimSpace(w.URL)); err == nil { return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") } return "" } // PageVisitors is each page's visitors over the last 30 days, by path, for // comparing a landing page with its variants. Counted per page, never per // person. func PageVisitors(ctx context.Context, c *plausible.Client, site string, paths []string) (map[string]int, error) { out := map[string]int{} if len(paths) == 0 { return out, nil } var ps []any for _, p := range paths { ps = append(ps, p) } rows, err := c.Run(ctx, plausible.Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d", Dimensions: []string{"event:page"}, Filters: [][]any{{"is", "event:page", ps}}}) if err != nil { return nil, err } for _, r := range rows { if len(r.Dimensions) > 0 && len(r.Metrics) > 0 { out[r.Dimensions[0]] = int(r.Metrics[0]) } } return out, nil }