Phase 4 part 3: Stripe customers matched to EspoCRM Accounts

Every customer with billing is matched to an Account copied from the
CRM: the user's choice, then an Account Hermes created from here, a
stored ID on either side, an email (the Account's or a Contact's), or
the email's domain (not free mail). Several candidates wait for a
choice. Metrics → Customers and the CRM fixes matches, marks customers
not in the CRM, and queues paying ones as new Accounts. Schema 20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 12:22:05 -07:00
co-authored by Claude Opus 5.5
parent 5e799c7541
commit 6ba524295b
13 changed files with 675 additions and 2 deletions
+4
View File
@@ -612,3 +612,7 @@ func WriteState(d *db.DB, now time.Time) error {
}
return os.Rename(tmp, filepath.Clean(StateFile))
}
// IsFreeMail reports whether a domain is a free email provider's, which
// says nothing about the company.
func IsFreeMail(domain string) bool { return freeMail[strings.ToLower(domain)] }
+9
View File
@@ -537,6 +537,15 @@ CREATE INDEX stripe_invoice_lines_by_customer ON stripe_invoice_lines (customer,
// can't read Products.
`
ALTER TABLE stripe_invoice_lines ADD COLUMN description TEXT NOT NULL DEFAULT '';
`,
// 20: Stripe customers matched to EspoCRM Accounts by hand (the
// automatic matches are worked out each time).
`
CREATE TABLE crm_matches (
customer TEXT PRIMARY KEY, -- cus_…
espo_id TEXT NOT NULL DEFAULT '', -- the Account; '' means "not in the CRM"
set_at TEXT NOT NULL
);
`,
}
+311
View File
@@ -0,0 +1,311 @@
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
}
return strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email))
})
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
}
+94
View File
@@ -0,0 +1,94 @@
package metrics
import (
"testing"
"time"
)
func TestMatches(t *testing.T) {
d := openDB(t)
now := time.Now()
exec := func(q string, args ...any) {
t.Helper()
if _, err := d.Exec(q, args...); err != nil {
t.Fatal(err)
}
}
// The CRM: Acme (with a Contact), Beta (holding a Stripe ID), two
// Accounts at one domain, and one at gmail.com.
for _, r := range []struct{ entity, id, name, email, domain, data string }{
{"Account", "a1", "Acme", "", "acme.example", `{}`},
{"Contact", "c1", "Ann", "ann@acme.example", "acme.example", `{"accountId":"a1"}`},
{"Account", "a2", "Beta", "", "beta.example", `{"cStripeCustomerId":"cus_beta"}`},
{"Account", "a3", "Twin One", "", "twin.example", `{}`},
{"Account", "a4", "Twin Two", "", "twin.example", `{}`},
{"Account", "a5", "Solo", "solo@gmail.com", "gmail.com", `{}`},
} {
exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, synced_at) VALUES (?, ?, ?, ?, ?, ?, '')`,
r.entity, r.id, r.name, r.email, r.domain, r.data)
}
for _, c := range []struct{ id, data string }{
{"cus_ann", `{"name":"Ann","email":"ANN@acme.example"}`},
{"cus_beta", `{"name":"Beta Inc","email":"x@elsewhere.example"}`},
{"cus_meta", `{"name":"Meta","email":"m@meta.example","metadata":{"espocrm_id":"a1"}}`},
{"cus_twin", `{"name":"Twin","email":"t@twin.example"}`},
{"cus_gm", `{"name":"G","email":"other@gmail.com"}`},
{"cus_free", `{"name":"Free","email":"free@nowhere.example"}`},
{"cus_unbilled", `{"name":"Never billed","email":"ann@acme.example"}`},
{"cus_new", `{"name":"Newco","email":"hi@newco.example"}`},
} {
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 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)
if err != nil {
t.Fatal(err)
}
got := map[string]Match{}
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, want := range map[string]struct{ account, how string }{
"cus_ann": {"a1", MatchEmail}, "cus_beta": {"a2", MatchStoredID}, "cus_meta": {"a1", MatchStoredID},
"cus_twin": {"", MatchAmbiguous}, "cus_gm": {"", MatchNone}, "cus_free": {"", MatchNone}, "cus_new": {"a9", MatchStoredID},
} {
if m := got[id]; m.Account.ID != want.account || m.How != want.how {
t.Errorf("%s: %+v, want %s by %q", id, m, want.account, want.how)
}
}
if len(got["cus_twin"].Candidates) != 2 || got["cus_new"].Account.Name != "Newco" {
t.Errorf("twin: %+v; new: %+v", got["cus_twin"], got["cus_new"])
}
// The user decides.
SetMatch(d, "cus_twin", "a4", false, now)
SetMatch(d, "cus_free", "", false, now)
SetMatch(d, "cus_ann", "a5", false, now)
ms, _ = Matches(d, nil)
for _, m := range ms {
got[m.Customer.ID] = m
}
if got["cus_twin"].Account.Name != "Twin Two" || got["cus_twin"].How != MatchManual || got["cus_free"].How != MatchNotInCRM || got["cus_ann"].Account.ID != "a5" {
t.Errorf("manual: %+v %+v %+v", got["cus_twin"], got["cus_free"], got["cus_ann"])
}
SetMatch(d, "cus_ann", "", true, now)
ms, _ = Matches(d, nil)
for _, m := range ms {
got[m.Customer.ID] = m
}
if got["cus_ann"].How != MatchEmail {
t.Errorf("back to automatic: %+v", got["cus_ann"])
}
if s := MatchSummary(ms); s[MatchStoredID] != 3 || s[MatchManual] != 1 || s[MatchNone] != 1 {
t.Errorf("summary: %v", s)
}
if as, _ := Accounts(d); len(as) != 5 || as[0].Name != "Acme" {
t.Errorf("accounts: %+v", as)
}
}
+28
View File
@@ -9,6 +9,7 @@ import (
"testing"
"time"
"supermarket/internal/crm"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
@@ -109,3 +110,30 @@ func TestMRRPages(t *testing.T) {
t.Errorf("bad month: %s", rec.Body)
}
}
func TestCustomersPage(t *testing.T) {
s, h := newTestServer(t, nil)
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', '{}')`)
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")
}
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"account"}, "account": {"Acme"}})
if body := do(h, http.MethodGet, "/metrics/customers?show=all", nil, nil).Body.String(); !strings.Contains(body, "Acme <span class=\"muted small\">by you</span>") {
t.Error("the manual match isn't shown")
}
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"auto"}})
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"add"}})
if acts, _ := crm.List(s.DB, 10); len(acts) != 1 || acts[0].Entity != "Account" || acts[0].Fields["website"] != "https://xco.example" {
t.Errorf("queued: %+v", acts)
}
if body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String(); !strings.Contains(body, "queued for the CRM") {
t.Error("the queued Account isn't shown")
}
if rec := postForm(h, "/metrics/customers/bad", url.Values{"do": {"none"}}); rec.Code != http.StatusNotFound {
t.Errorf("bad id: %d", rec.Code)
}
}
+125
View File
@@ -8,6 +8,7 @@ import (
"strings"
"time"
"supermarket/internal/crm"
"supermarket/internal/metrics"
)
@@ -194,3 +195,127 @@ func (s *Server) RunMetrics(ctx context.Context) {
}
}
}
// --- Stripe customers and CRM Accounts ---
func (s *Server) metricsCustomers(w http.ResponseWriter, r *http.Request) {
s.renderCustomers(w, r, "")
}
func (s *Server) renderCustomers(w http.ResponseWriter, r *http.Request, errMsg string) {
model, err := metrics.Build(s.DB, time.Now())
if err != nil {
s.serverError(w, err)
return
}
all, err := metrics.Matches(s.DB, model)
if err != nil {
s.serverError(w, err)
return
}
show := r.URL.Query().Get("show")
var shown []metrics.Match
for _, m := range all {
open := m.How == metrics.MatchNone || m.How == metrics.MatchAmbiguous
if show == "all" || (show == "" && open) || (show == "paying" && m.MRR > 0) {
shown = append(shown, m)
}
}
accounts, err := metrics.Accounts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
counts, _ := crm.RecordCounts(s.DB)
sync, _ := crm.LoadSync(s.DB)
queued := map[string]bool{}
if acts, err := crm.List(s.DB, 1000); err == nil {
for _, a := range acts {
if strings.HasPrefix(a.Key, "stripe-customer:") && a.Status != "cancelled" {
queued[strings.TrimPrefix(a.Key, "stripe-customer:")] = true
}
}
}
s.render(w, r, "metrics-customers", page{Title: "Customers and the CRM", Nav: "metrics/customers", Error: errMsg, Data: map[string]any{
"Matches": shown, "Total": len(all), "Summary": metrics.MatchSummary(all), "Accounts": accounts,
"CRMCount": counts["Account"], "Synced": sync.Last, "Show": show, "Queued": queued,
}})
}
// metricsCustomerMatch handles a customer's buttons: choose an Account, say
// it isn't in the CRM, go back to automatic, or add it to the CRM.
func (s *Server) metricsCustomerMatch(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cust := r.PathValue("id")
if !strings.HasPrefix(cust, "cus_") {
http.NotFound(w, r)
return
}
now := time.Now()
var err error
switch r.PostFormValue("do") {
case "account":
acc := strings.TrimSpace(r.PostFormValue("account"))
// The box takes a name; find its Account.
if accounts, aerr := metrics.Accounts(s.DB); aerr == nil {
for _, a := range accounts {
if strings.EqualFold(a.Name, acc) || a.ID == acc {
acc = a.ID
}
}
}
if acc == "" {
err = errors.New("choose an Account")
} else {
err = metrics.SetMatch(s.DB, cust, acc, false, now)
}
case "none":
err = metrics.SetMatch(s.DB, cust, "", false, now)
case "auto":
err = metrics.SetMatch(s.DB, cust, "", true, now)
case "add":
err = s.queueAccount(cust)
default:
http.NotFound(w, r)
return
}
if err != nil {
s.renderCustomers(w, r, err.Error())
return
}
redirect(w, r, "/metrics/customers?show="+r.PostFormValue("show"), "saved")
}
// queueAccount asks Hermes to add a paying Stripe customer to the CRM as an
// Account (and remembers the match once it exists).
func (s *Server) queueAccount(cust string) error {
names, err := metrics.CustomerNames(s.DB)
if err != nil {
return err
}
c, ok := names[cust]
if !ok {
return errors.New("no such customer")
}
name := c.Name
if name == "" {
name = c.Email
}
if name == "" {
return errors.New("the customer has no name or email to create an Account from")
}
fields := map[string]any{"name": name, "description": "Added by Supermarket: a paying Stripe customer (" + cust + ")."}
match := map[string]string{"name": name}
if dom := crm.EmailDomain(c.Email); dom != "" && !crm.IsFreeMail(dom) {
fields["website"] = "https://" + dom
match = map[string]string{"website": "https://" + dom}
}
if c.Email != "" {
fields["emailAddress"] = c.Email
}
_, err = crm.Enqueue(s.DB, crm.Action{Key: "stripe-customer:" + cust, Entity: "Account", Fields: fields, Match: match, Origin: "stripe-customer:" + cust})
return err
}
+2
View File
@@ -165,6 +165,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /metrics/margins", s.metricsMargins)
mux.HandleFunc("POST /metrics/start", s.metricsStart)
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+6
View File
@@ -50,6 +50,12 @@
<a href="/seo/engines" {{if eq $nav "seo/engines"}}aria-current="page"{{end}}>Search engines</a>
</div>
{{end}}
{{if eq .ID "metrics"}}
<div class="subnav">
<a href="/metrics" {{if eq $nav "metrics/overview"}}aria-current="page"{{end}}>MRR and NRR</a>
<a href="/metrics/customers" {{if eq $nav "metrics/customers"}}aria-current="page"{{end}}>Customers and the CRM</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
<div class="subnav">
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
@@ -0,0 +1,51 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Customers and the CRM</h1></div>
<p class="lede">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.</p>
<section class="card">
{{if not .CRMCount}}
<p class="warn-text">No CRM Accounts copied yet, so nothing can be matched. Hermes copies them once the CRM bridge works (see <a href="/crm">CRM queue</a>); until then you can say which customers aren't in the CRM, or queue them to be added.</p>
{{else}}<p class="small muted">{{num .CRMCount}} Accounts copied from the CRM{{if not .Synced.IsZero}} {{ago .Synced}}{{end}}.</p>{{end}}
{{$s := .Summary}}
<div class="funnel">
<div class="step"><span class="label">Customers</span><strong>{{num .Total}}</strong></div>
<div class="step"><span class="label">By stored ID</span><strong>{{or (index $s "stored ID") 0}}</strong></div>
<div class="step"><span class="label">By email</span><strong>{{or (index $s "email") 0}}</strong></div>
<div class="step"><span class="label">By domain</span><strong>{{or (index $s "domain") 0}}</strong></div>
<div class="step"><span class="label">By you</span><strong>{{or (index $s "by you") 0}}</strong></div>
<div class="step"><span class="label">To choose</span><strong>{{or (index $s "several") 0}}</strong></div>
<div class="step"><span class="label">No match</span><strong>{{or (index $s "") 0}}</strong></div>
<div class="step"><span class="label">Not in the CRM</span><strong>{{or (index $s "not in the CRM") 0}}</strong></div>
</div>
</section>
<nav class="tabs">
<a href="/metrics/customers" {{if eq .Show ""}}aria-current="page"{{end}}>To fix</a>
<a href="/metrics/customers?show=paying" {{if eq .Show "paying"}}aria-current="page"{{end}}>Paying now</a>
<a href="/metrics/customers?show=all" {{if eq .Show "all"}}aria-current="page"{{end}}>All</a>
</nav>
<datalist id="accounts">{{range .Accounts}}<option value="{{.Name}}">{{.Domain}}</option>{{end}}</datalist>
{{if .Matches}}
<div class="table-wrap"><table class="list compact">
<thead><tr><th>Customer</th><th class="num">MRR now</th><th>Account</th><th></th></tr></thead>
<tbody>{{range .Matches}}<tr>
<td>{{or .Customer.Name .Customer.Email .Customer.ID}}{{if and .Customer.Name .Customer.Email}}<br><span class="muted small">{{.Customer.Email}}</span>{{end}}{{if .Prospect}}<br><span class="badge">a prospect</span>{{end}}</td>
<td class="num">{{if .MRR}}{{usd .MRR}}{{else}}<span class="muted">·</span>{{end}}</td>
<td>{{if .Account.ID}}{{.Account.Name}} <span class="muted small">{{.How}}</span>
{{else if eq .How "several"}}<span class="warn-text small">Several fit:</span> {{range $i, $a := .Candidates}}{{if $i}}, {{end}}{{$a.Name}}{{end}}
{{else if eq .How "not in the CRM"}}<span class="muted">not in the CRM</span>
{{else}}<span class="muted">no match</span>{{if index $d.Queued .Customer.ID}} <span class="badge draft">queued for the CRM</span>{{end}}{{end}}</td>
<td>
<form method="post" action="/metrics/customers/{{.Customer.ID}}" class="row wrap">
<input type="hidden" name="show" value="{{$d.Show}}">
{{if $d.Accounts}}<input name="account" list="accounts" placeholder="an Account" size="16"><button type="submit" name="do" value="account" class="secondary small">Match</button>{{end}}
{{if or .Account.ID (eq .How "not in the CRM")}}{{if or (eq .How "by you") (eq .How "not in the CRM")}}<button type="submit" name="do" value="auto" class="link small">automatic</button>{{end}}
{{else}}<button type="submit" name="do" value="none" class="link small">not in the CRM</button>
{{if and .MRR (not (index $d.Queued .Customer.ID))}}<button type="submit" name="do" value="add" class="link small">add to the CRM</button>{{end}}{{end}}
</form>
</td>
</tr>{{end}}</tbody>
</table></div>
{{else}}<section class="card empty"><p>{{if eq .Show ""}}Nothing to fix.{{else}}No customers.{{end}}</p></section>{{end}}
{{end}}{{end}}