Phase 2 part 1: the CRM bridge to EspoCRM through Hermes

Supermarket queues CRM work in crm_actions and never writes to EspoCRM
itself. A Hermes cron job (supermarket-crm, set up by `supermarket
hermes`) runs every 15 minutes behind a monitor script that prints
Supermarket's crm-state file, so unchanged state skips the AI run. Hermes
calls the new MCP tools crm_pending_actions, crm_report_result and
crm_ingest, creating each record through the Core's MCP hub unless a
match exists, and copying Leads, Accounts and Contacts back every 6 hours
for duplicate checks. Schema 5 adds crm_actions and crm_records.

Prospects -> CRM queue shows the queue, a test Lead, sync, Retry and
Cancel. When an action fails with a connection error, the page checks
EspoCRM from this computer and says whether the CRM is down or the hub
can't reach it, with a note to send to the Core's maintainer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 16:28:46 -07:00
co-authored by Claude Opus 5.5
parent 5feb6a16d4
commit 1dc5476d43
15 changed files with 1586 additions and 30 deletions
+95 -1
View File
@@ -9,7 +9,9 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -17,6 +19,7 @@ import (
"supermarket/internal/bridge"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/mcpserver"
@@ -92,7 +95,7 @@ func TestEveryPageRenders(t *testing.T) {
for _, path := range []string{"/", "/?msg=saved", "/settings/profile", "/inventory", "/inventory?relationship=partner",
"/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export",
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/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"} {
rec := do(h, http.MethodGet, path, nil, nil)
@@ -444,3 +447,94 @@ func TestLinkedInExpiryReminders(t *testing.T) {
t.Errorf("expired publish: %v", err)
}
}
func TestCRMQueuePage(t *testing.T) {
s, h := newTestServer(t, nil)
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, "Nothing queued yet") ||
!strings.Contains(body, "isn't set up yet") || !strings.Contains(body, `href="/crm" aria-current="page"`) {
t.Error("empty CRM page")
}
_ = os.WriteFile(filepath.Join(s.DataDir, "hermes-crm-job"), []byte("9fd45c690814\n"), 0o600)
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, "hermes cron run 9fd45c690814") {
t.Error("the job's run command isn't shown")
}
if rec := postForm(h, "/crm/test", nil); rec.Code != http.StatusSeeOther {
t.Fatalf("test lead: %d %s", rec.Code, rec.Body.String())
}
as, _ := crm.List(s.DB, 10)
if len(as) != 1 || as[0].Entity != "Lead" || as[0].Origin != "test" || as[0].Status != crm.StatusPending {
t.Fatalf("queued: %+v", as)
}
id := strconv.FormatInt(as[0].ID, 10)
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, "1 waiting") || !strings.Contains(body, "Supermarket Test") {
t.Error("the queued test lead isn't shown")
}
// Retry only applies to failed actions.
if rec := postForm(h, "/crm/"+id+"/retry", nil); !strings.Contains(rec.Body.String(), "has changed meanwhile") {
t.Error("retrying a pending action should be refused")
}
crm.Claim(s.DB, time.Now(), 10)
crm.Report(s.DB, as[0].ID, crm.Result{Outcome: "failed", Error: "hub said no"}, time.Now())
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, "hub said no") || !strings.Contains(body, "/crm/"+id+"/retry") {
t.Error("failed action not shown with Retry")
}
postForm(h, "/crm/"+id+"/retry", nil)
if a, _ := crm.Get(s.DB, as[0].ID); a.Status != crm.StatusPending {
t.Errorf("retry: %+v", a)
}
postForm(h, "/crm/"+id+"/cancel", nil)
if a, _ := crm.Get(s.DB, as[0].ID); a.Status != crm.StatusCancelled {
t.Errorf("cancel: %+v", a)
}
if rec := postForm(h, "/crm/sync", nil); rec.Code != http.StatusSeeOther {
t.Errorf("sync: %d", rec.Code)
}
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, "A sync is requested") {
t.Error("sync request not shown")
}
}
// When Hermes reports that EspoCRM couldn't be reached, the CRM page checks
// EspoCRM from here, to tell the user whether the CRM or the hub is at fault.
func TestCRMReachHint(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
defer up.Close()
down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
downURL := down.URL
down.Close()
s, h := newTestServer(t, &core.Core{Domain: "example.com", Email: "pat@example.com"})
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); strings.Contains(body, "/crm/reach") {
t.Error("hint shown with nothing failed")
}
fail := func(msg string) {
crm.Enqueue(s.DB, crm.Action{Key: "k:" + msg, Entity: "Lead", Fields: map[string]any{"lastName": "X"}})
as, _ := crm.Claim(s.DB, time.Now(), 10)
for _, a := range as {
crm.Report(s.DB, a.ID, crm.Result{Outcome: "failed", Error: msg}, time.Now())
}
}
// A record EspoCRM refused isn't a connection problem.
fail("Validation failed: lastName is required")
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); strings.Contains(body, "/crm/reach") {
t.Error("hint shown for a non-connection error")
}
fail("EspoCRM unreachable: connect ECONNREFUSED 192.168.0.39:443 on the search")
if body := do(h, http.MethodGet, "/crm", nil, nil).Body.String(); !strings.Contains(body, `hx-get="/crm/reach"`) {
t.Fatal("no hint for a connection error")
}
defer func(f func(*core.Core) string) { espoCRMURL = f }(espoCRMURL)
espoCRMURL = func(*core.Core) string { return up.URL }
body := do(h, http.MethodGet, "/crm/reach", nil, nil).Body.String()
for _, want := range []string{"answers from this computer", "<code>192.168.0.39:443</code>", "mcphub.example.com", up.URL} {
if !strings.Contains(body, want) {
t.Errorf("reachable: missing %q in %s", want, body)
}
}
espoCRMURL = func(*core.Core) string { return downURL }
body = do(h, http.MethodGet, "/crm/reach", nil, nil).Body.String()
if !strings.Contains(body, "doesn't answer from this computer either") {
t.Errorf("unreachable: %s", body)
}
}