Customers who paid without an invoice (one-off Checkout payments) were missed, and the Stripe card counted every customer record, deleted ones too. The sync now reads charges (and follows their events); a customer's total spend is their successful charges, captured less refunded. A database synced before reads everything once (sync state version 2). Until charges are in, paid invoices less refunds stand in. The Stripe card's Customers now counts those who spent more than $0, "of N in Stripe", and a Payments count is added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
370 lines
10 KiB
Go
370 lines
10 KiB
Go
package metrics
|
|
|
|
import (
|
|
"encoding/json"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"supermarket/internal/crm"
|
|
"supermarket/internal/db"
|
|
)
|
|
|
|
// How a customer was matched to an Account.
|
|
const (
|
|
MatchStoredID = "stored ID"
|
|
MatchEmail = "email"
|
|
MatchDomain = "domain"
|
|
MatchManual = "by you"
|
|
MatchNotInCRM = "not in the CRM" // the user said so
|
|
MatchNone = ""
|
|
MatchAmbiguous = "several"
|
|
)
|
|
|
|
// Account is an EspoCRM Account, as copied.
|
|
type Account struct {
|
|
ID, Name, Domain string
|
|
}
|
|
|
|
// Match is a Stripe customer and the Account it belongs to.
|
|
type Match struct {
|
|
Customer Customer
|
|
Account Account
|
|
How string
|
|
Candidates []Account // when several Accounts fit
|
|
MRR float64 // now, in cents
|
|
Prospect string // the Phase 2 prospect it's tied to (contact:12), if any
|
|
}
|
|
|
|
var stripeIDFields = []string{"stripeCustomerId", "cStripeCustomerId", "stripeId", "cStripeId", "stripeCustomerID"}
|
|
|
|
// crmIndex is the copied CRM, indexed for matching.
|
|
type crmIndex struct {
|
|
accounts map[string]Account
|
|
byStripe map[string]string // cus_… → Account
|
|
byEmail map[string][]string // email → Accounts (theirs, or their Contacts')
|
|
byDomain map[string][]string
|
|
}
|
|
|
|
func loadCRM(d *db.DB) (*crmIndex, error) {
|
|
ix := &crmIndex{accounts: map[string]Account{}, byStripe: map[string]string{}, byEmail: map[string][]string{}, byDomain: map[string][]string{}}
|
|
rows, err := d.Query(`SELECT entity, espo_id, name, email, domain, data FROM crm_records WHERE entity IN ('Account', 'Contact')`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
type contact struct{ email, account string }
|
|
var contacts []contact
|
|
for rows.Next() {
|
|
var entity, id, name, email, domain, raw string
|
|
if err := rows.Scan(&entity, &id, &name, &email, &domain, &raw); err != nil {
|
|
rows.Close()
|
|
return nil, err
|
|
}
|
|
var data map[string]any
|
|
_ = json.Unmarshal([]byte(raw), &data)
|
|
if entity == "Contact" {
|
|
if acc, _ := data["accountId"].(string); acc != "" && email != "" {
|
|
contacts = append(contacts, contact{strings.ToLower(email), acc})
|
|
}
|
|
continue
|
|
}
|
|
ix.accounts[id] = Account{ID: id, Name: name, Domain: domain}
|
|
for _, f := range stripeIDFields {
|
|
if v, _ := data[f].(string); strings.HasPrefix(v, "cus_") {
|
|
ix.byStripe[v] = id
|
|
}
|
|
}
|
|
if email != "" {
|
|
ix.byEmail[strings.ToLower(email)] = appendUnique(ix.byEmail[strings.ToLower(email)], id)
|
|
}
|
|
if domain != "" && !crm.IsFreeMail(domain) {
|
|
ix.byDomain[domain] = appendUnique(ix.byDomain[domain], id)
|
|
}
|
|
}
|
|
rows.Close()
|
|
for _, c := range contacts {
|
|
if _, ok := ix.accounts[c.account]; ok {
|
|
ix.byEmail[c.email] = appendUnique(ix.byEmail[c.email], c.account)
|
|
}
|
|
}
|
|
return ix, rows.Err()
|
|
}
|
|
|
|
func appendUnique(s []string, v string) []string {
|
|
if slices.Contains(s, v) {
|
|
return s
|
|
}
|
|
return append(s, v)
|
|
}
|
|
|
|
// customerMeta reads the fields matching needs from a Stripe customer.
|
|
type customerMeta struct {
|
|
Customer
|
|
EspoID string // from the customer's metadata
|
|
}
|
|
|
|
func loadCustomers(d *db.DB) ([]customerMeta, error) {
|
|
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ? AND status != 'deleted'`, KindCustomer)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []customerMeta
|
|
for rows.Next() {
|
|
var id, raw string
|
|
if err := rows.Scan(&id, &raw); err != nil {
|
|
return nil, err
|
|
}
|
|
var c struct {
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
Metadata map[string]string `json:"metadata"`
|
|
}
|
|
_ = json.Unmarshal([]byte(raw), &c)
|
|
m := customerMeta{Customer: Customer{ID: id, Name: c.Name, Email: strings.ToLower(c.Email)}}
|
|
for _, k := range []string{"espocrm_id", "espo_id", "crm_id", "espocrm_account_id"} {
|
|
if v := c.Metadata[k]; v != "" {
|
|
m.EspoID = v
|
|
break
|
|
}
|
|
}
|
|
out = append(out, m)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// manual are the user's choices: customer → Account ("" for not in the CRM).
|
|
func manual(d *db.DB) (map[string]string, error) {
|
|
rows, err := d.Query(`SELECT customer, espo_id FROM crm_matches`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := map[string]string{}
|
|
for rows.Next() {
|
|
var c, a string
|
|
if err := rows.Scan(&c, &a); err != nil {
|
|
return nil, err
|
|
}
|
|
out[c] = a
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// 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.
|
|
func Matches(d *db.DB, model *Model) ([]Match, error) {
|
|
ix, err := loadCRM(d)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
custs, err := loadCustomers(d)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
man, err := manual(d)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
paying, err := Spenders(d)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
prospects := map[string]string{}
|
|
rows, err := d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for rows.Next() {
|
|
var c, s string
|
|
rows.Scan(&c, &s)
|
|
prospects[c] = s
|
|
}
|
|
rows.Close()
|
|
// Accounts Hermes created (or found) for customers queued from here.
|
|
added := map[string]Account{}
|
|
rows, err = d.Query(`SELECT substr(key, 17), espo_id, json_extract(fields, '$.name') FROM crm_actions
|
|
WHERE key LIKE 'stripe-customer:%' AND status = 'done' AND espo_id != ''`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for rows.Next() {
|
|
var c, id string
|
|
var name *string
|
|
rows.Scan(&c, &id, &name)
|
|
a := ix.accounts[id]
|
|
if a.ID == "" {
|
|
a = Account{ID: id}
|
|
if name != nil {
|
|
a.Name = *name
|
|
}
|
|
}
|
|
added[c] = a
|
|
}
|
|
rows.Close()
|
|
var now map[string]float64
|
|
if model != nil && model.Last() != nil {
|
|
now = model.Last().ByCustomer
|
|
}
|
|
var out []Match
|
|
for _, c := range custs {
|
|
if !paying[c.ID] {
|
|
continue
|
|
}
|
|
m := Match{Customer: c.Customer, MRR: now[c.ID], Prospect: prospects[c.ID]}
|
|
if a, ok := man[c.ID]; ok {
|
|
if a == "" {
|
|
m.How = MatchNotInCRM
|
|
} else {
|
|
m.How, m.Account = MatchManual, ix.accounts[a]
|
|
if m.Account.ID == "" {
|
|
m.Account = Account{ID: a, Name: "(an Account not copied yet)"}
|
|
}
|
|
}
|
|
out = append(out, m)
|
|
continue
|
|
}
|
|
pick := func(ids []string, how string) bool {
|
|
switch len(ids) {
|
|
case 0:
|
|
return false
|
|
case 1:
|
|
m.Account, m.How = ix.accounts[ids[0]], how
|
|
default:
|
|
m.How = MatchAmbiguous
|
|
for _, id := range ids {
|
|
m.Candidates = append(m.Candidates, ix.accounts[id])
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
switch {
|
|
case added[c.ID].ID != "":
|
|
m.Account, m.How = added[c.ID], MatchStoredID
|
|
case c.EspoID != "" && ix.accounts[c.EspoID].ID != "":
|
|
m.Account, m.How = ix.accounts[c.EspoID], MatchStoredID
|
|
case ix.byStripe[c.ID] != "":
|
|
m.Account, m.How = ix.accounts[ix.byStripe[c.ID]], MatchStoredID
|
|
case c.Email != "" && pick(ix.byEmail[c.Email], MatchEmail):
|
|
case pick(ix.byDomain[crm.EmailDomain(c.Email)], MatchDomain):
|
|
}
|
|
out = append(out, m)
|
|
}
|
|
slices.SortStableFunc(out, func(a, b Match) int {
|
|
switch {
|
|
case a.MRR > b.MRR:
|
|
return -1
|
|
case a.MRR < b.MRR:
|
|
return 1
|
|
}
|
|
if c := strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email)); c != 0 {
|
|
return c
|
|
}
|
|
return strings.Compare(a.Customer.ID, b.Customer.ID) // the same name and email twice: a stable order
|
|
})
|
|
return out, nil
|
|
}
|
|
|
|
// SetMatch records the user's choice: an Account, "" for "not in the CRM",
|
|
// or forget clears it (back to automatic).
|
|
func SetMatch(d *db.DB, customer, account string, forget bool, now time.Time) error {
|
|
if forget {
|
|
_, err := d.Exec(`DELETE FROM crm_matches WHERE customer = ?`, customer)
|
|
return err
|
|
}
|
|
_, err := d.Exec(`INSERT INTO crm_matches (customer, espo_id, set_at) VALUES (?, ?, ?)
|
|
ON CONFLICT (customer) DO UPDATE SET espo_id = excluded.espo_id, set_at = excluded.set_at`, customer, account, now.UTC().Format(time.RFC3339))
|
|
return err
|
|
}
|
|
|
|
// Accounts lists the copied Accounts, by name, for choosing one.
|
|
func Accounts(d *db.DB) ([]Account, error) {
|
|
rows, err := d.Query(`SELECT espo_id, name, domain FROM crm_records WHERE entity = 'Account' ORDER BY name COLLATE NOCASE`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []Account
|
|
for rows.Next() {
|
|
var a Account
|
|
if err := rows.Scan(&a.ID, &a.Name, &a.Domain); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, a)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// MatchSummary counts the matches by how they were made.
|
|
func MatchSummary(ms []Match) map[string]int {
|
|
out := map[string]int{}
|
|
for _, m := range ms {
|
|
out[m.How]++
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Spenders are the customers whose total spend is above $0, as Stripe's
|
|
// dashboard counts it: their successful payments (charges), less what was
|
|
// refunded. Customers who only had a trial, or have only unpaid invoices,
|
|
// aren't customers yet. Until the charges are synced, paid invoices
|
|
// (amount_paid) less refunds stand in.
|
|
func Spenders(d *db.DB) (map[string]bool, error) {
|
|
var charges int
|
|
if err := d.QueryRow(`SELECT count(*) FROM stripe_objects WHERE kind = ?`, KindCharge).Scan(&charges); err != nil {
|
|
return nil, err
|
|
}
|
|
type row struct {
|
|
kind, customer, data string
|
|
amount int64
|
|
}
|
|
q := `SELECT kind, customer, amount, '' FROM stripe_objects
|
|
WHERE kind = 'charge' AND status = 'succeeded' AND customer != ''`
|
|
if charges == 0 {
|
|
q = `SELECT kind, customer, amount, data FROM stripe_objects
|
|
WHERE customer != '' AND ((kind = 'invoice' AND status = 'paid') OR (kind = 'refund' AND status IN ('succeeded', 'pending')))`
|
|
}
|
|
rows, err := d.Query(q)
|
|
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 {
|
|
switch r.kind {
|
|
case KindCharge:
|
|
spend[r.customer] += r.amount // captured, less refunded
|
|
case KindRefund:
|
|
spend[r.customer] -= r.amount
|
|
case KindInvoice:
|
|
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
|
|
}
|