diff --git a/PLAN.md b/PLAN.md index 405348b..680ed66 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1089,6 +1089,29 @@ into `main`. records), by stored ID, email or email domain, with a screen to fix wrong matches. Customers already tied to prospects (Phase 2) keep that tie. + - **Built 2026-11-22** (schema 20: `crm_matches`, the user's choices + only): + - `metrics.Matches` matches every customer with a paid or open + invoice, in this order: + 1. the user's choice; + 2. an Account Hermes created from here (a done `stripe-customer:` + CRM action); + 3. a stored ID: `espocrm_id`, `espo_id`, `crm_id` or + `espocrm_account_id` in the customer's metadata, or a + `cus_…` in the Account's `stripeCustomerId`, `cStripeCustomerId` + or a similar field; + 4. email, on the Account or one of its Contacts (via + `accountId`); + 5. the email's domain, skipping free mail. + - When several Accounts fit, the user chooses. + - The page is Metrics → Customers and the CRM, with three tabs: to + fix, paying now, all. Each customer can be matched to an Account + (by name), marked "not in the CRM", put back to automatic, or + queued as a new Account for Hermes (the website comes from the + email's domain). + - On the live account, 385 customers have billing. None can be + matched until Hermes copies the CRM's Accounts, which waits on the + Core's MCP hub. 4. **The spend log and CAC.** - Spend by channel and month, entered by hand or imported from CSV. - Outside tools' spend comes in automatically (origami.chat and diff --git a/README.md b/README.md index dd89824..f174e3f 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,14 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then - each month's movements (new, expansion, contraction, churn, reactivation), with a page per month listing each customer's move; - cohorts by the month customers first paid, with the share of their starting MRR they still pay. -MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. If your billing moved to Stripe partway through, set the month to count from, so the customers already paying then aren't counted as new; Metrics suggests one when it sees the jump. CAC and CLV come in the next parts. +MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. *Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order: +- a stored ID, either side; +- the email, on the Account or one of its Contacts; +- the email's domain (free mail doesn't count). + +Where several Accounts fit, you choose; you can fix any match, mark a customer as not in the CRM, or queue a paying customer to be added as an Account through Hermes. It needs Hermes to have copied the CRM's Accounts. + +If your billing moved to Stripe partway through, set the month to count from, so the customers already paying then aren't counted as new; Metrics suggests one when it sees the jump. CAC and CLV come in the next parts. **The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked. diff --git a/TEST.md b/TEST.md index a9907b0..45448aa 100644 --- a/TEST.md +++ b/TEST.md @@ -430,6 +430,19 @@ Throughout, also notice: starting base, and the suggestion goes away. - [ ] Cohorts start at 100% in their first month. +### Customers and the CRM + +- [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says + no Accounts are copied, and lists every customer with billing. +- [ ] Once Accounts are copied (after the CRM bridge works), customers are + matched by stored ID, email or domain; check a few against EspoCRM. + Gmail-style addresses never match by domain. +- [ ] Where several Accounts fit, they're listed; choosing one by name and + *Match* keeps it, and *automatic* undoes it. +- [ ] *not in the CRM* moves a customer out of the "to fix" list. +- [ ] *add to the CRM* on a paying customer queues an Account on the CRM + queue; once Hermes adds it, the customer shows as matched. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/crm/crm.go b/internal/crm/crm.go index 9473ce6..7356caf 100644 --- a/internal/crm/crm.go +++ b/internal/crm/crm.go @@ -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)] } diff --git a/internal/db/db.go b/internal/db/db.go index 5f9f559..4d0c519 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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 +); `, } diff --git a/internal/metrics/crmmatch.go b/internal/metrics/crmmatch.go new file mode 100644 index 0000000..05a5c20 --- /dev/null +++ b/internal/metrics/crmmatch.go @@ -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 +} diff --git a/internal/metrics/crmmatch_test.go b/internal/metrics/crmmatch_test.go new file mode 100644 index 0000000..b98f766 --- /dev/null +++ b/internal/metrics/crmmatch_test.go @@ -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) + } +} diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go index a72c81e..5c62f71 100644 --- a/internal/web/engines_test.go +++ b/internal/web/engines_test.go @@ -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 by you") { + 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) + } +} diff --git a/internal/web/metrics.go b/internal/web/metrics.go index 89aeebc..3b0f3e6 100644 --- a/internal/web/metrics.go +++ b/internal/web/metrics.go @@ -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 +} diff --git a/internal/web/server.go b/internal/web/server.go index cf28e08..bb2276c 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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) diff --git a/internal/web/server_test.go b/internal/web/server_test.go index e80d487..aee7b9b 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -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 { diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 80f641c..498f179 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -50,6 +50,12 @@ Search engines {{end}} + {{if eq .ID "metrics"}} +
+ {{end}} {{if eq .ID "prospects"}}