Files
supermarket/internal/tracking/tracking.go
T
davidandClaude Opus 5.5 2c42857419 Phase 6 part 3: website lead forms into EspoCRM
Sites → Lead forms sets up the site's forms to create EspoCRM Leads
through its Lead Capture: the address saved and tested with a CORS
preflight, and a pull request adding a script that maps the form's fields
onto a Lead (campaign, page and form in the description). Plausible's
Lead goal is imported per signal as interested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:54:26 -07:00

359 lines
11 KiB
Go

// 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, leads, leadNote := 0, 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
}
}
n, err := importLeads(ctx, d, c, site, from, yesterday, campaigns, tags)
if err != nil {
leadNote = fmt.Sprintf(" Form leads weren't read from %s: %v.", site, err)
}
leads += 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; %d form leads.", visits, leads) + leadNote
return save(d, SourcePlausible, res, nil)
}
// LeadGoal is the Plausible goal (a custom event) the sites' lead forms
// send when they're submitted.
const LeadGoal = "Lead"
// importLeads counts the lead forms sent on visits tagged with a signal
// (Plausible's Lead goal, by the visit's UTM tags) as interested, on the
// signal's funnel. Without the goal set up in Plausible, it reports why.
func importLeads(ctx context.Context, d *db.DB, c *plausible.Client, site, from, to string, campaigns []any, tags map[string]int64) (int, error) {
rows, err := c.Run(ctx, plausible.Query{
SiteID: site,
Metrics: []string{"events"},
DateRange: []string{from, to},
Dimensions: []string{"time:day", "visit:utm_campaign", "visit:utm_source", "visit:utm_medium"},
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}, {"is", "visit:utm_campaign", campaigns}},
Pagination: &plausible.Pagination{Limit: 10000},
})
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "goal") {
return 0, fmt.Errorf("add a %q goal (a custom event) in Plausible to count them", LeadGoal)
}
return 0, err
}
n := 0
for _, r := range rows {
if len(r.Dimensions) < 4 || len(r.Metrics) < 1 || r.Metrics[0] < 1 {
continue
}
day, campaign, source, medium := r.Dimensions[0], r.Dimensions[1], r.Dimensions[2], r.Dimensions[3]
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
}
count := int(r.Metrics[0])
note := strings.Trim(none(source)+" / "+none(medium), " /")
added, err := signals.Record(d, signals.Event{
SignalID: sig, Stage: signals.StageInterested, Channel: Channel(none(source), none(medium)),
Source: SourcePlausible, Count: count, Note: site + ": sent a lead form" + strings.TrimSuffix(" ("+note+")", " ()"),
At: at.Add(12 * time.Hour), ExternalID: strings.Join([]string{"lead", site, day, campaign, source, medium}, "|"),
})
if err != nil {
return n, err
}
if added {
n += count
}
}
return n, 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
}
// FormLead is a day's lead forms for a signal, as counted from Plausible.
type FormLead struct {
Signal string
Count int
Note string
At time.Time
}
// FormLeads are the latest lead forms counted, newest first.
func FormLeads(d *db.DB, limit int) ([]FormLead, error) {
rows, err := d.Query(`SELECT coalesce(s.name, ''), e.count, e.note, e.at FROM funnel_events e LEFT JOIN signals s ON s.id = e.signal_id
WHERE e.source = ? AND e.external_id LIKE 'lead|%' ORDER BY e.at DESC, e.id DESC LIMIT ?`, SourcePlausible, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []FormLead
for rows.Next() {
var f FormLead
var at string
if err := rows.Scan(&f.Signal, &f.Count, &f.Note, &at); err != nil {
return nil, err
}
f.At, _ = time.Parse(time.RFC3339, at)
out = append(out, f)
}
return out, rows.Err()
}