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:
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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}}
|
||||
Reference in New Issue
Block a user