diff --git a/TEST.md b/TEST.md index 8ef2f2d..0d0f882 100644 --- a/TEST.md +++ b/TEST.md @@ -184,7 +184,7 @@ Throughout, also notice: ### Sources -- [ ] *Fetch* on a Market entry finds new items from its feeds and +- [x] *Fetch* on a Market entry finds new items from its feeds and sitemap, and the list shows when it was last checked. - [x] Items can be dismissed and restored. - [ ] Your own products (`/content/own`) show your sites' and feeds' new diff --git a/internal/metrics/crmmatch.go b/internal/metrics/crmmatch.go index 7d33a74..3c91011 100644 --- a/internal/metrics/crmmatch.go +++ b/internal/metrics/crmmatch.go @@ -151,7 +151,8 @@ func manual(d *db.DB) (map[string]string, error) { return out, rows.Err() } -// Matches matches every Stripe customer with billing to an Account: the +// Matches matches every Stripe customer who has spent something to an +// Account: the // user's choice first, then a stored ID (either side), then email (an // Account's or one of its Contacts'), then the email's domain (not free // mail). Paying customers come first, by MRR. @@ -168,19 +169,12 @@ func Matches(d *db.DB, model *Model) ([]Match, error) { if err != nil { return nil, err } - billed := map[string]bool{} - rows, err := d.Query(`SELECT DISTINCT customer FROM stripe_objects WHERE kind = 'invoice' AND status IN ('paid', 'open')`) + paying, err := spenders(d) if err != nil { return nil, err } - for rows.Next() { - var c string - rows.Scan(&c) - billed[c] = true - } - rows.Close() prospects := map[string]string{} - rows, err = d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`) + rows, err := d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`) if err != nil { return nil, err } @@ -217,7 +211,7 @@ func Matches(d *db.DB, model *Model) ([]Match, error) { } var out []Match for _, c := range custs { - if !billed[c.ID] { + if !paying[c.ID] { continue } m := Match{Customer: c.Customer, MRR: now[c.ID], Prospect: prospects[c.ID]} @@ -312,3 +306,51 @@ func MatchSummary(ms []Match) map[string]int { } return out } + +// spenders are the customers whose total spend is above $0: what their +// paid invoices charged (amount_paid, so $0 and fully discounted invoices +// count as nothing), less what was refunded. Customers who only had a +// trial, or have only open invoices, aren't customers yet. +func spenders(d *db.DB) (map[string]bool, error) { + type row struct { + kind, customer, data string + amount int64 + } + rows, err := d.Query(`SELECT kind, customer, amount, data FROM stripe_objects + WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`) + if err != nil { + return nil, err + } + var all []row + for rows.Next() { + var r row + if err := rows.Scan(&r.kind, &r.customer, &r.amount, &r.data); err != nil { + rows.Close() + return nil, err + } + all = append(all, r) + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, err + } + spend := map[string]int64{} + for _, r := range all { + if r.kind == KindRefund { + spend[r.customer] -= r.amount + continue + } + var inv struct { + AmountPaid int64 `json:"amount_paid"` + } + _ = json.Unmarshal([]byte(r.data), &inv) + spend[r.customer] += inv.AmountPaid + } + out := map[string]bool{} + for c, v := range spend { + if v > 0 { + out[c] = true + } + } + return out, nil +} diff --git a/internal/metrics/crmmatch_test.go b/internal/metrics/crmmatch_test.go index b98f766..5b1fe87 100644 --- a/internal/metrics/crmmatch_test.go +++ b/internal/metrics/crmmatch_test.go @@ -39,9 +39,22 @@ func TestMatches(t *testing.T) { } { exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', ?, ?, ?)`, c.id, c.id, c.data) if c.id != "cus_unbilled" { - exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', '{}')`, "in_"+c.id, c.id) + exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', '{"amount_paid":1000}')`, "in_"+c.id, c.id) } } + // Customers who never spent anything aren't listed: a $0 trial invoice, + // only an open invoice, or a payment refunded in full. + for _, c := range []struct{ id, status, data string }{ + {"cus_trial", "paid", `{"amount_paid":0}`}, + {"cus_open", "open", `{"amount_paid":0}`}, + {"cus_refunded", "paid", `{"amount_paid":500}`}, + } { + exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', ?, ?, '{"name":"X","email":"x@x.example"}')`, c.id, c.id) + exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, ?, 'usd', ?)`, "in_"+c.id, c.id, c.status, c.data) + } + exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, amount, data) VALUES ('refund', 're_1', 'cus_refunded', 'succeeded', 'usd', 500, '{}')`) + // A partial refund leaves them a customer. + exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, amount, data) VALUES ('refund', 're_2', 'cus_beta', 'succeeded', 'usd', 400, '{}')`) exec(`INSERT INTO crm_actions (key, kind, entity, fields, status, espo_id) VALUES ('stripe-customer:cus_new', 'create', 'Account', '{"name":"Newco"}', 'done', 'a9')`) ms, err := Matches(d, nil) @@ -52,8 +65,10 @@ func TestMatches(t *testing.T) { for _, m := range ms { got[m.Customer.ID] = m } - if _, ok := got["cus_unbilled"]; ok { - t.Error("a customer never billed is listed") + for _, id := range []string{"cus_unbilled", "cus_trial", "cus_open", "cus_refunded"} { + if _, ok := got[id]; ok { + t.Errorf("%s spent nothing, but is listed", id) + } } for id, want := range map[string]struct{ account, how string }{ "cus_ann": {"a1", MatchEmail}, "cus_beta": {"a2", MatchStoredID}, "cus_meta": {"a1", MatchStoredID}, diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go index c7719f6..a35d668 100644 --- a/internal/web/engines_test.go +++ b/internal/web/engines_test.go @@ -116,7 +116,7 @@ func TestCustomersPage(t *testing.T) { s.DB.Exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, synced_at) VALUES ('Account', 'a1', 'Acme', '', 'acme.example', '{}', '')`) s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', 'cus_x', 'cus_x', '{"name":"Xco","email":"x@xco.example"}'), ('customer', 'cus_a', 'cus_a', '{"name":"Acme Ltd","email":"pay@acme.example"}')`) - s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'in_1', 'cus_x', 'paid', 'usd', '{}'), ('invoice', 'in_2', 'cus_a', 'paid', 'usd', '{}')`) + s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'in_1', 'cus_x', 'paid', 'usd', '{"amount_paid":1000}'), ('invoice', 'in_2', 'cus_a', 'paid', 'usd', '{"amount_paid":1000}')`) body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String() if !strings.Contains(body, "Xco") || strings.Contains(body, "Acme Ltd") { t.Fatal("the to-fix list should hold only the unmatched customer") diff --git a/internal/web/templates/metrics-customers.html b/internal/web/templates/metrics-customers.html index f43d16e..28c29b0 100644 --- a/internal/web/templates/metrics-customers.html +++ b/internal/web/templates/metrics-customers.html @@ -1,6 +1,6 @@ {{define "content"}}{{with .Data}}{{$d := .}}

Customers and the CRM

-

Each Stripe customer with billing, matched to its EspoCRM Account: first by a stored ID (a Stripe customer ID in the Account, or an EspoCRM ID in Stripe's metadata), then by email (the Account's, or one of its Contacts'), then by the email's domain (free mail like Gmail doesn't count). Fix what it gets wrong; your choice is kept. Pipeline influence and per-account numbers build on this.

+

Each Stripe customer who has spent more than $0 (paid invoices, less refunds; trials and unpaid invoices don't count), matched to its EspoCRM Account: first by a stored ID (a Stripe customer ID in the Account, or an EspoCRM ID in Stripe's metadata), then by email (the Account's, or one of its Contacts'), then by the email's domain (free mail like Gmail doesn't count). Fix what it gets wrong; your choice is kept. Pipeline influence and per-account numbers build on this.

{{if not .CRMCount}}