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 "" } // crmBroken says whether the newest finished action failed because // EspoCRM couldn't be reached (and nothing has got through since). func crmBroken(actions []crm.Action) bool { for _, a := range actions { // newest first switch a.Status { case crm.StatusDone: return false case crm.StatusFailed: if connErr.MatchString(a.Error) { return true } } } return false } // 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, r, "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, r, "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 } msg := "" switch r.PathValue("action") { case "retry": err, msg = crm.Retry(s.DB, id), "crm-retried" case "cancel": err, msg = crm.Cancel(s.DB, id), "crm-cancelled" 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", msg) } }