supermarket export [--with-secrets] writes a whole Supermarket as a .tar.gz (a manifest, each table as JSON lines, secrets if asked for) to the file storage. supermarket import loads one into an empty database at the same schema, SQLite or Postgres, in one transaction, parents first, checking row counts and moving Postgres' identity counters past the imported ids. Checked on Federated's 112,543 rows: imported into Postgres and SQLite, every table and total matches, and TestPagesOnRealData renders all 57 pages the same from both. That found unsettled ordering (case-alike campaigns, customers with the same name, metrics' float sums), now fixed with ORDER BY and tie-breakers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
315 lines
8.6 KiB
Go
315 lines
8.6 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 with billing 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
|
|
}
|
|
billed := map[string]bool{}
|
|
rows, err := d.Query(`SELECT DISTINCT customer FROM stripe_objects WHERE kind = 'invoice' AND status IN ('paid', 'open')`)
|
|
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:%'`)
|
|
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 !billed[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
|
|
}
|