Files
supermarket/internal/web/crm.go
T
davidandClaude Opus 5.5 1dc5476d43 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>
2026-11-21 16:28:46 -07:00

190 lines
5.1 KiB
Go

package web
import (
"errors"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"supermarket/internal/bridge"
"supermarket/internal/core"
"supermarket/internal/crm"
)
// hermesCRMJob is the name of the Hermes cron job `supermarket hermes`
// installs. It records the job's ID in hermes-crm-job in the data folder,
// which `hermes cron run` needs.
const hermesCRMJob = "supermarket-crm"
// crmJobID is the Hermes job's ID, or "" if it isn't set up.
func (s *Server) crmJobID() string {
raw, err := os.ReadFile(filepath.Join(s.DataDir, "hermes-crm-job"))
if err != nil {
return ""
}
return strings.TrimSpace(string(raw))
}
func (s *Server) crmPage(w http.ResponseWriter, r *http.Request) {
s.renderCRM(w, r, "")
}
func (s *Server) renderCRM(w http.ResponseWriter, r *http.Request, errMsg string) {
actions, err := crm.List(s.DB, 100)
if err != nil {
s.serverError(w, err)
return
}
counts, err := crm.Counts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
records, err := crm.RecordCounts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
sync, err := crm.LoadSync(s.DB)
if err != nil {
s.serverError(w, err)
return
}
last, err := bridge.Last(s.DB)
if err != nil {
s.serverError(w, err)
return
}
var lastDone time.Time
for _, a := range actions {
if a.DoneAt.After(lastDone) {
lastDone = a.DoneAt
}
}
s.render(w, r, "crm", page{Title: "CRM queue", Nav: "prospects/crm", Error: errMsg, Data: map[string]any{
"Actions": actions,
"Counts": counts,
"Records": records,
"Entities": crm.SyncEntities,
"Sync": sync,
"SyncRequested": sync.Requested.After(sync.Last),
"LastDone": lastDone,
"Checkin": last,
"Job": hermesCRMJob,
"JobID": s.crmJobID(),
"Waiting": counts[crm.StatusPending] + counts[crm.StatusClaimed],
"Unreachable": s.Core != nil && unreachableError(actions) != "",
}})
}
// espoCRMURL is where Supermarket checks EspoCRM from; tests replace it.
var espoCRMURL = (*core.Core).EspoCRMURL
// connErr spots a failed action whose error says the CRM couldn't be
// reached, as opposed to EspoCRM refusing the record. Its second group is
// the address that was tried, when the error names one.
var connErr = regexp.MustCompile(`(?i)(ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|ENOTFOUND|EAI_AGAIN|connection refused|no such host|timed out|unreachable)(?:\s+([\w-]+(?:\.[\w-]+)+(?::\d+)?))?`)
// unreachableError is the newest failed action's error, if it's a
// connection error.
func unreachableError(actions []crm.Action) string {
for _, a := range actions { // newest first
if a.Status == crm.StatusFailed && connErr.MatchString(a.Error) {
return a.Error
}
}
return ""
}
// crmReach is an htmx fragment shown when Hermes couldn't reach EspoCRM.
// Hermes goes through the Core's MCP hub, which connects to EspoCRM with
// its own settings; checking EspoCRM from here tells the user which side
// to look at.
func (s *Server) crmReach(w http.ResponseWriter, r *http.Request) {
actions, err := crm.List(s.DB, 100)
if err != nil {
s.serverError(w, err)
return
}
failure := unreachableError(actions)
if s.Core == nil || failure == "" {
s.fragment(w, "crm", "reach", nil)
return
}
check := probe(r.Context(), core.Service{Name: "EspoCRM", URL: espoCRMURL(s.Core)})
tried := ""
for _, m := range connErr.FindAllStringSubmatch(failure, -1) {
if m[2] != "" {
tried = m[2]
break
}
}
s.fragment(w, "crm", "reach", map[string]any{
"Check": check,
"Tried": tried,
"Error": failure,
"HubHost": "mcphub." + s.Core.Domain,
})
}
// crmAction handles the page's buttons.
func (s *Server) crmAction(w http.ResponseWriter, r *http.Request) {
now := time.Now()
switch r.PathValue("action") {
case "test":
// A new key each time, so the test can be repeated.
_, err := crm.Enqueue(s.DB, crm.Action{
Key: "test:" + strconv.FormatInt(now.UnixNano(), 36),
Entity: "Lead",
Fields: map[string]any{
"firstName": "Supermarket",
"lastName": "Test " + now.Format("2 Jan 15:04"),
"accountName": "Supermarket bridge test",
"source": "Other",
"description": "Created by Supermarket to check that Hermes can write to EspoCRM. Delete it.",
},
Match: map[string]string{"lastName": "Test " + now.Format("2 Jan 15:04")},
Origin: "test",
})
if err != nil {
s.renderCRM(w, r, err.Error())
return
}
redirect(w, r, "/crm", "crm-test")
case "sync":
if err := crm.RequestSync(s.DB, now); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/crm", "crm-sync")
default:
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
switch r.PathValue("action") {
case "retry":
err = crm.Retry(s.DB, id)
case "cancel":
err = crm.Cancel(s.DB, id)
default:
http.NotFound(w, r)
return
}
if errors.Is(err, crm.ErrNoAction) {
s.renderCRM(w, r, "That action has changed meanwhile: Hermes may have just carried it out.")
return
}
if err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/crm", "saved")
}
}