Files
supermarket/internal/tracking/tracking_test.go
davidandClaude Opus 5.5 d23d5e2a87 Phase 2 part 7: the end of the funnel
Posts can be written for a buying signal: the prompt gets its hypothesis
and angle, and links carry its campaign tag. Plausible (Stats API v2) is
read once a day for visitors on tagged links, recorded per signal as
Visited. Stripe (restricted key) is read every hour: $0 checkouts are
Signed up, paid invoices and one-time payments are Paid with their value,
tied to a signal by the checkout's utm_campaign metadata or the payer's
email. The Core's Cal.com has no API, so booking emails from Cal.com in
the outreach mailbox count as Booked. New Settings → Website & sales;
the signal page lists its posts and tagged links. Schema 11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 06:42:03 -07:00

201 lines
8.0 KiB
Go

package tracking
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/plausible"
"supermarket/internal/api/stripe"
"supermarket/internal/db"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
var now = time.Date(2026, 11, 22, 9, 0, 0, 0, time.Local)
func openDB(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func signal(t *testing.T, d *db.DB, name, slug string) int64 {
s := &signals.Signal{Name: name, Slug: slug}
if err := signals.Save(d, s); err != nil {
t.Fatal(err)
}
return s.ID
}
func TestChannel(t *testing.T) {
for in, want := range map[[2]string]string{
{"email", "outreach"}: "email", {"linkedin", "outreach"}: "linkedin", {"linkedin", "social"}: "social",
{"x", ""}: "social", {"newsletter", ""}: "email", {"", ""}: "website", {"blog", ""}: "blog",
} {
if got := Channel(in[0], in[1]); got != want {
t.Errorf("%v: %q, want %q", in, got, want)
}
}
}
func TestSites(t *testing.T) {
p := &profile.Profile{Websites: []profile.Website{{URL: "https://www.federated.computer/", PlausibleSite: "plausible.federated.computer"},
{URL: "https://shop.example", PlausibleSite: "shop-stats"}, {URL: "https://federated.computer"},
{URL: "https://blog.example", PlausibleSite: "https://plausible.example.com/blog.example"}}}
if got := strings.Join(Sites(p), ","); got != "federated.computer,shop-stats,blog.example" {
t.Errorf("sites: %s", got)
}
}
func TestImportPlausible(t *testing.T) {
d := openDB(t)
m365 := signal(t, d, "Leaving M365", "leaving-m365")
var got []plausible.Query
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer k" || r.URL.Path != "/api/v2/query" {
w.WriteHeader(http.StatusUnauthorized)
return
}
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
got = append(got, q)
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-20", "leaving-m365", "email", "outreach", "outreach-3"}, "metrics": []float64{2}},
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social", "(none)"}, "metrics": []float64{5}},
map[string]any{"dimensions": []string{"2026-11-21", "old-campaign", "x", "social", "(none)"}, "metrics": []float64{9}},
}})
}))
defer srv.Close()
c := plausible.New(srv.URL, "k")
res, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now)
if err != nil {
t.Fatal(err)
}
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") {
t.Fatalf("result: %+v", res)
}
q := got[0]
dr, _ := json.Marshal(q.DateRange)
if q.SiteID != "federated.computer" || string(dr) != `["2026-10-23","2026-11-21"]` || len(q.Filters) != 1 {
t.Errorf("query: %+v %s", q, dr)
}
evs, _ := signals.RecentEvents(d, m365, 10)
if len(evs) != 2 || evs[0].Stage != signals.StageVisited || evs[0].Channel != "social" || evs[0].Count != 5 ||
evs[1].Channel != "email" || !strings.Contains(evs[1].Note, "outreach-3") {
t.Errorf("events: %+v", evs)
}
// The next day reads only the new day; running again the same day reads nothing.
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 1 {
t.Errorf("same day: %d queries, %v", len(got), err)
}
res, _ = ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now.AddDate(0, 0, 1))
dr, _ = json.Marshal(got[1].DateRange)
if string(dr) != `["2026-11-22","2026-11-22"]` || res.Added != 0 {
t.Errorf("next day: %s %+v", dr, res)
}
if last, _ := Last(d, SourcePlausible); last == nil || last.Through != "2026-11-22" {
t.Errorf("last: %+v", last)
}
if _, err := ImportPlausible(context.Background(), d, plausible.New(srv.URL, "bad"), []string{"x.example"}, now); err == nil {
t.Error("a bad key worked")
}
}
func TestSyncStripe(t *testing.T) {
d := openDB(t)
m365 := signal(t, d, "Leaving M365", "leaving-m365")
faith := signal(t, d, "Faith", "faith")
co, _, _ := prospects.AddCompany(d, prospects.Company{Name: "Church", Website: "church.example", Source: prospects.SourceManual, SignalID: faith}, now)
ann, _, _ := prospects.AddContact(d, prospects.Contact{FirstName: "Ann", Email: "ann@acme.example", Source: prospects.SourceManual, SignalID: m365}, now)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer rk_live_x" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Query().Get("status") == "" {
t.Errorf("unfiltered list: %s", r.URL)
}
switch r.URL.Path {
case "/v1/checkout/sessions":
if r.URL.Query().Get("starting_after") == "" {
json.NewEncoder(w).Encode(map[string]any{"has_more": true, "data": []any{
// A trial from a tagged link.
map[string]any{"id": "cs_2", "created": now.Unix() - 100, "status": "complete", "mode": "subscription", "amount_total": 0,
"currency": "usd", "customer": "cus_new", "customer_details": map[string]any{"email": "new@else.example", "name": "New Co"},
"metadata": map[string]any{"utm_campaign": "leaving-m365", "utm_source": "linkedin", "utm_medium": "social"}},
}})
return
}
json.NewEncoder(w).Encode(map[string]any{"has_more": false, "data": []any{
// A one-time payment by a prospect, no tags.
map[string]any{"id": "cs_1", "created": now.Unix() - 200, "status": "complete", "mode": "payment", "payment_status": "paid",
"amount_total": 7000, "currency": "usd", "customer": "cus_ann", "customer_details": map[string]any{"email": "ann@acme.example"}},
}})
case "/v1/invoices":
json.NewEncoder(w).Encode(map[string]any{"has_more": false, "data": []any{
map[string]any{"id": "in_1", "created": now.Unix() - 50, "customer": "cus_new", "amount_paid": 4900, "currency": "usd",
"billing_reason": "subscription_cycle", "status_transitions": map[string]any{"paid_at": now.Unix() - 40}},
map[string]any{"id": "in_2", "created": now.Unix() - 30, "customer": "cus_pastor", "customer_email": "pastor@church.example",
"amount_paid": 12000, "currency": "usd", "billing_reason": "subscription_create"},
map[string]any{"id": "in_3", "created": now.Unix() - 20, "customer": "cus_x", "amount_paid": 0},
}})
}
}))
defer srv.Close()
c := stripe.New("rk_live_x").WithBase(srv.URL)
res, err := SyncStripe(context.Background(), d, c, now)
if err != nil {
t.Fatal(err)
}
if res.Added != 4 || res.Detail != "1 sign-up and 3 payments (239.00)." {
t.Fatalf("result: %+v", res)
}
m, _ := signals.RecentEvents(d, m365, 10)
stages := map[string]signals.Event{}
for _, e := range m {
stages[e.Stage+":"+e.ExternalID] = e
}
if e := stages["signed_up:cs:cs_2"]; e.Channel != "social" || e.Subject != "stripe:cus_new" {
t.Errorf("trial: %+v", e)
}
if e := stages["paid:in:in_1"]; e.ValueCents != 4900 || e.Channel != "social" || e.Note != "Subscription renewal (USD)" {
t.Errorf("renewal: %+v", e)
}
if e := stages["paid:cs:cs_1"]; e.ValueCents != 7000 || e.Subject != prospects.Subject("contact", ann) || e.Channel != "website" {
t.Errorf("one-time: %+v", e)
}
f, _ := signals.RecentEvents(d, faith, 10)
var paid *signals.Event
for i := range f {
if f[i].Stage == signals.StagePaid {
paid = &f[i]
}
}
if len(f) != 2 || paid == nil || paid.ValueCents != 12000 || paid.Subject != prospects.Subject("company", co) {
t.Errorf("by domain: %+v", f)
}
// Running again adds nothing.
if res, _ := SyncStripe(context.Background(), d, c, now); res.Added != 0 {
t.Errorf("again: %+v", res)
}
// The invoice with nothing paid makes no customer.
if cs, _ := Customers(d, 10); len(cs) != 3 {
t.Errorf("customers: %+v", cs)
}
if err := stripe.New("bad").WithBase(srv.URL).Check(context.Background()); err == nil {
t.Error("a bad key worked")
}
}