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)
|
||||
}
|
||||
Reference in New Issue
Block a user