Files
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -07:00

207 lines
5.5 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 ""
}
// 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, "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
}
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)
}
}