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>
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
package tracking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/stripe"
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// Customer is a Stripe customer and where they came from.
|
||||
type Customer struct {
|
||||
ID string
|
||||
Email string
|
||||
Name string
|
||||
SignalID int64
|
||||
Subject string // contact:12 or company:3 when they're a prospect; else stripe:<id>
|
||||
Channel string
|
||||
Campaign string
|
||||
}
|
||||
|
||||
// stripeState is where the last sync stopped.
|
||||
type stripeState struct {
|
||||
Sessions int64 `json:"sessions"` // created time of the newest session read
|
||||
Invoices int64 `json:"invoices"`
|
||||
}
|
||||
|
||||
const stripeStateKey = "tracking:stripe-state"
|
||||
|
||||
// firstStripeDays is how far back the first sync reads.
|
||||
const firstStripeDays = 90
|
||||
|
||||
// SyncStripe reads new completed checkouts and paid invoices. A checkout
|
||||
// with nothing to pay (a trial or a free plan) counts as Signed up; money
|
||||
// paid counts as Paid, with its amount. Each customer is tied to a signal by
|
||||
// the utm_campaign the shopping cart saved in the checkout's metadata, or
|
||||
// else by their email: a prospect's, or one at a prospect company's domain.
|
||||
func SyncStripe(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time) (*Result, error) {
|
||||
res := &Result{At: now}
|
||||
var st stripeState
|
||||
if _, err := d.GetJSON(stripeStateKey, &st); err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
first := now.AddDate(0, 0, -firstStripeDays).Unix()
|
||||
if st.Sessions == 0 {
|
||||
st.Sessions = first
|
||||
}
|
||||
if st.Invoices == 0 {
|
||||
st.Invoices = first
|
||||
}
|
||||
tags, err := slugs(d)
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
|
||||
sessions, err := c.Sessions(ctx, time.Unix(st.Sessions, 0))
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
var signups, payments int
|
||||
var revenue int64
|
||||
for _, s := range sessions {
|
||||
key := s.Customer
|
||||
if key == "" {
|
||||
key = "guest:" + s.ID
|
||||
}
|
||||
cust, err := customer(d, tags, key, s.CustomerDetails.Email, s.CustomerDetails.Name, s.Metadata, time.Unix(s.Created, 0))
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
at := time.Unix(s.Created, 0)
|
||||
switch {
|
||||
case s.AmountTotal == 0 && s.Mode != "setup":
|
||||
added, err := record(d, cust, signals.StageSignedUp, "cs:"+s.ID, 0, s.Currency, "Checkout: "+planNote(s), at)
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
if added {
|
||||
signups++
|
||||
}
|
||||
case s.Mode == "payment" && s.PaymentStatus == "paid" && s.Invoice == "":
|
||||
// A one-time payment without an invoice; the others are
|
||||
// counted from their invoices.
|
||||
added, err := record(d, cust, signals.StagePaid, "cs:"+s.ID, s.AmountTotal, s.Currency, "One-time payment", at)
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
if added {
|
||||
payments++
|
||||
revenue += s.AmountTotal
|
||||
}
|
||||
}
|
||||
st.Sessions = max(st.Sessions, s.Created)
|
||||
}
|
||||
|
||||
invoices, err := c.PaidInvoices(ctx, time.Unix(st.Invoices, 0))
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
for _, inv := range invoices {
|
||||
st.Invoices = max(st.Invoices, inv.Created)
|
||||
if inv.AmountPaid <= 0 {
|
||||
continue
|
||||
}
|
||||
key := inv.Customer
|
||||
if key == "" {
|
||||
key = "guest:" + inv.ID
|
||||
}
|
||||
cust, err := customer(d, tags, key, inv.CustomerEmail, inv.CustomerName, nil, time.Unix(inv.Created, 0))
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
at := time.Unix(inv.Transitions.PaidAt, 0)
|
||||
if inv.Transitions.PaidAt == 0 {
|
||||
at = time.Unix(inv.Created, 0)
|
||||
}
|
||||
note := "Invoice"
|
||||
switch inv.BillingReason {
|
||||
case "subscription_create":
|
||||
note = "First subscription payment"
|
||||
case "subscription_cycle":
|
||||
note = "Subscription renewal"
|
||||
case "subscription_update":
|
||||
note = "Subscription change"
|
||||
}
|
||||
added, err := record(d, cust, signals.StagePaid, "in:"+inv.ID, inv.AmountPaid, inv.Currency, note, at)
|
||||
if err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
if added {
|
||||
payments++
|
||||
revenue += inv.AmountPaid
|
||||
}
|
||||
}
|
||||
if err := d.PutJSON(stripeStateKey, st); err != nil {
|
||||
return save(d, SourceStripe, res, err)
|
||||
}
|
||||
res.Added = signups + payments
|
||||
res.Detail = fmt.Sprintf("%s and %s (%s).", plural(signups, "sign-up"), plural(payments, "payment"), money(revenue))
|
||||
return save(d, SourceStripe, res, nil)
|
||||
}
|
||||
|
||||
func planNote(s stripe.Session) string {
|
||||
if s.Mode == "subscription" {
|
||||
return "a trial or free plan"
|
||||
}
|
||||
return "nothing to pay"
|
||||
}
|
||||
|
||||
func money(cents int64) string {
|
||||
return fmt.Sprintf("%d.%02d", cents/100, cents%100)
|
||||
}
|
||||
|
||||
// record adds one Stripe step to the funnel.
|
||||
func record(d *db.DB, c *Customer, stage, id string, cents int64, currency, note string, at time.Time) (bool, error) {
|
||||
if currency != "" {
|
||||
note += " (" + strings.ToUpper(currency) + ")"
|
||||
}
|
||||
return signals.Record(d, signals.Event{
|
||||
SignalID: c.SignalID, Stage: stage, Channel: c.Channel, Subject: c.Subject, Email: c.Email,
|
||||
Source: SourceStripe, ExternalID: id, ValueCents: cents, Note: note, At: at,
|
||||
})
|
||||
}
|
||||
|
||||
// customer returns the stored customer, adding or completing it from what
|
||||
// the checkout or invoice says.
|
||||
func customer(d *db.DB, tags map[string]int64, id, email, name string, meta map[string]string, now time.Time) (*Customer, error) {
|
||||
c := &Customer{ID: id}
|
||||
var sig sql.NullInt64
|
||||
err := d.QueryRow(`SELECT email, name, signal_id, subject, channel, utm_campaign FROM stripe_customers WHERE id = ?`, id).
|
||||
Scan(&c.Email, &c.Name, &sig, &c.Subject, &c.Channel, &c.Campaign)
|
||||
known := err == nil
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
c.SignalID = sig.Int64
|
||||
if c.Email == "" {
|
||||
c.Email = strings.ToLower(strings.TrimSpace(email))
|
||||
}
|
||||
if c.Name == "" {
|
||||
c.Name = strings.TrimSpace(name)
|
||||
}
|
||||
var source, medium string
|
||||
if meta != nil {
|
||||
campaign := strings.ToLower(strings.TrimSpace(meta["utm_campaign"]))
|
||||
if campaign == "" {
|
||||
campaign = strings.ToLower(strings.TrimSpace(meta["signal"]))
|
||||
}
|
||||
source, medium = meta["utm_source"], meta["utm_medium"]
|
||||
if s, ok := tags[campaign]; ok && c.SignalID == 0 {
|
||||
c.SignalID, c.Campaign = s, campaign
|
||||
c.Channel = Channel(source, medium)
|
||||
}
|
||||
}
|
||||
if c.Subject == "" || strings.HasPrefix(c.Subject, "stripe:") {
|
||||
if subj, s, ch := matchProspect(d, c.Email); subj != "" {
|
||||
c.Subject = subj
|
||||
if c.SignalID == 0 {
|
||||
c.SignalID = s
|
||||
}
|
||||
if c.Channel == "" {
|
||||
c.Channel = ch
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Subject == "" {
|
||||
c.Subject = "stripe:" + id
|
||||
}
|
||||
if c.Channel == "" {
|
||||
c.Channel = "website"
|
||||
}
|
||||
if known {
|
||||
_, err = d.Exec(`UPDATE stripe_customers SET email = ?, name = ?, signal_id = ?, subject = ?, channel = ?, utm_campaign = ?,
|
||||
utm_source = CASE WHEN utm_source = '' THEN ? ELSE utm_source END,
|
||||
utm_medium = CASE WHEN utm_medium = '' THEN ? ELSE utm_medium END WHERE id = ?`,
|
||||
c.Email, c.Name, nullID(c.SignalID), c.Subject, c.Channel, c.Campaign, source, medium, id)
|
||||
} else {
|
||||
_, err = d.Exec(`INSERT INTO stripe_customers (id, email, name, signal_id, subject, channel, utm_campaign, utm_source, utm_medium, first_seen)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, c.Email, c.Name, nullID(c.SignalID), c.Subject, c.Channel, c.Campaign,
|
||||
source, medium, now.UTC().Format(time.RFC3339))
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
func nullID(id int64) any {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// matchProspect finds the prospect a payer is: a person with that email,
|
||||
// or else a company at its domain. It returns their funnel subject, signal,
|
||||
// and the channel Supermarket last wrote to them on.
|
||||
func matchProspect(d *db.DB, email string) (subject string, signalID int64, channel string) {
|
||||
if email == "" {
|
||||
return "", 0, ""
|
||||
}
|
||||
var id, sig int64
|
||||
err := d.QueryRow(`SELECT p.id, coalesce(p.signal_id, c.signal_id, 0) FROM prospect_contacts p
|
||||
LEFT JOIN prospect_companies c ON c.id = p.company_id WHERE p.email = ? LIMIT 1`, email).Scan(&id, &sig)
|
||||
if err == nil {
|
||||
_ = d.QueryRow(`SELECT channel FROM outreach WHERE contact_id = ? AND status = 'sent' ORDER BY sent_at DESC LIMIT 1`, id).Scan(&channel)
|
||||
return prospects.Subject("contact", id), sig, channel
|
||||
}
|
||||
if dom := crm.EmailDomain(email); dom != "" {
|
||||
if err := d.QueryRow(`SELECT id, coalesce(signal_id, 0) FROM prospect_companies WHERE domain = ? LIMIT 1`, dom).Scan(&id, &sig); err == nil {
|
||||
return prospects.Subject("company", id), sig, ""
|
||||
}
|
||||
}
|
||||
return "", 0, ""
|
||||
}
|
||||
|
||||
// Customers lists the Stripe customers seen, newest first.
|
||||
func Customers(d *db.DB, limit int) ([]Customer, error) {
|
||||
rows, err := d.Query(`SELECT id, email, name, coalesce(signal_id, 0), subject, channel, utm_campaign
|
||||
FROM stripe_customers ORDER BY first_seen DESC LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Customer
|
||||
for rows.Next() {
|
||||
var c Customer
|
||||
if err := rows.Scan(&c.ID, &c.Email, &c.Name, &c.SignalID, &c.Subject, &c.Channel, &c.Campaign); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func plural(n int, word string) string {
|
||||
if n == 1 {
|
||||
return "1 " + word
|
||||
}
|
||||
return fmt.Sprintf("%d %ss", n, word)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user