Files
supermarket/internal/web/server_test.go
T
davidandClaude Opus 5.5 c6c4c40600 Phase 9, part 6: background work shared safely between copies of the app
internal/jobs keeps named locks as leases in the database (schema 31:
locks, instances), taken with one conditional UPDATE on SQLite or Postgres,
renewed while the work runs and lapsing if its copy stops. Each background
loop's turn, sending an email, audits, discovery runs and imports run
under a lock; OAuth sign-ins under way are kept in the database. Copies
check in, and work marked running is recovered at start only when no
other copy is alive. Settings -> About lists the copies and work under
way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:56:47 -07:00

777 lines
35 KiB
Go

package web
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"supermarket/internal/bridge"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/mcpserver"
"supermarket/internal/models"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
const testToken = "0123456789abcdef0123456789abcdef"
func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) {
t.Helper()
dir := t.TempDir()
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
sec, err := secrets.Open(filepath.Join(dir, "secrets.json"))
if db.OnPostgres() { // as the server edition keeps them
sec, err = secrets.OpenDB(d, []byte("0123456789abcdef0123456789abcdef"), nil)
}
if err != nil {
t.Fatal(err)
}
s := &Server{
DB: d, Secrets: sec, Core: c, DataDir: dir,
PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken,
MCP: mcpserver.Handler(d, testToken, "test"),
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
h, err := s.Handler()
if err != nil {
t.Fatal(err)
}
return s, h
}
func do(h http.Handler, method, target string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, target, body)
req.Host = "localhost:8470"
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func postForm(h http.Handler, target string, form url.Values) *httptest.ResponseRecorder {
return do(h, http.MethodPost, target, strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "http://localhost:8470",
})
}
func TestEveryPageRenders(t *testing.T) {
for _, c := range []*core.Core{nil, {Domain: "example.com", Email: "pat@example.com", Name: "Pat"}} {
s, h := newTestServer(t, c)
// Some data, so templates' non-empty branches run too.
if err := profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.",
Products: []profile.Product{{Name: "Widget", Benefits: []string{"fast"}}},
Websites: []profile.Website{{URL: "https://acme.example", Repo: "r"}}}); err != nil {
t.Fatal(err)
}
e := &inventory.Entry{Name: "Rival", Relationship: "competitor", Hashtags: []string{"rival"}}
if err := inventory.Save(s.DB, e); err != nil {
t.Fatal(err)
}
if err := bridge.Record(s.DB, bridge.Checkin{Agent: "hermes", MCPHubTools: []string{"espocrm_create_lead"}}); err != nil {
t.Fatal(err)
}
if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: "tok"}); err != nil {
t.Fatal(err)
}
for _, path := range []string{"/", "/?msg=saved", "/settings/profile", "/market", "/market?relationship=partner",
"/market/new", "/market/1", "/market/import", "/market/export",
"/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/next", "/seo/links", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new", "/settings/backups",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String())
}
}
if rec := do(h, http.MethodGet, "/market/999", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("missing entry: %d", rec.Code)
}
}
}
func TestGuardRejectsForeignHostsAndCrossSitePosts(t *testing.T) {
_, h := newTestServer(t, nil)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = "evil.example:8470" // DNS rebinding
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusMisdirectedRequest {
t.Errorf("foreign Host: got %d", rec.Code)
}
form := url.Values{"name": {"Acme"}, "description": {"x"}}
rec = do(h, http.MethodPost, "/settings/profile", strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://evil.example",
})
if rec.Code != http.StatusForbidden {
t.Errorf("cross-origin POST: got %d", rec.Code)
}
rec = do(h, http.MethodPost, "/settings/profile", strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Sec-Fetch-Site": "cross-site",
})
if rec.Code != http.StatusForbidden {
t.Errorf("cross-site POST without Origin: got %d", rec.Code)
}
if rec := postForm(h, "/settings/profile", form); rec.Code != http.StatusSeeOther {
t.Errorf("same-origin POST: got %d %s", rec.Code, rec.Body.String())
}
}
func TestProfileAndInventoryForms(t *testing.T) {
s, h := newTestServer(t, nil)
form := url.Values{
"name": {" Acme "}, "description": {"We make widgets."}, "keywords": {"widgets\n\nwidget software\nWidgets"},
"product_name": {"Widget", ""}, "product_url": {"https://a.example/w", ""},
"product_description": {"A widget", ""}, "product_pricing": {"$5", ""}, "product_benefits": {"cheap\nfast", ""},
"website_url": {"https://acme.example/", ""}, "website_repo": {"https://gitea.example/acme/site.git", ""},
"website_branch": {"", ""}, "website_plausible": {"", ""}, "website_gsc": {"", ""}, "website_bing": {"", ""},
"account_x": {"@acme"}, "subreddits": {"r/selfhosted\n/r/homelab"},
}
if rec := postForm(h, "/settings/profile", form); rec.Code != http.StatusSeeOther {
t.Fatalf("save profile: %d %s", rec.Code, rec.Body.String())
}
p, _ := profile.Load(s.DB)
if p.Name != "Acme" || len(p.Products) != 1 || len(p.Products[0].Benefits) != 2 {
t.Errorf("profile products: %+v", p)
}
if len(p.Keywords) != 2 {
t.Errorf("keywords should be de-duplicated case-insensitively: %q", p.Keywords)
}
if len(p.Websites) != 1 || p.Websites[0].URL != "https://acme.example" || p.Websites[0].Branch != "main" {
t.Errorf("websites: %+v", p.Websites)
}
if p.Accounts.X != "acme" || strings.Join(p.Accounts.Subreddits, ",") != "selfhosted,homelab" {
t.Errorf("accounts: %+v", p.Accounts)
}
// Missing description: the form comes back with an error, nothing saved.
rec := postForm(h, "/settings/profile", url.Values{"name": {"Other"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "required") {
t.Errorf("invalid profile: %d", rec.Code)
}
entry := url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "hashtags": {"rival, #Other"}, "twitter_handle": {"@rival"}}
if rec := postForm(h, "/market/save", entry); rec.Code != http.StatusSeeOther {
t.Fatalf("save entry: %d %s", rec.Code, rec.Body.String())
}
entries, _ := inventory.List(s.DB, "competitor")
if len(entries) != 1 || entries[0].TwitterHandle != "rival" || entries[0].MentionPolicy != "category" ||
strings.Join(entries[0].Hashtags, " ") != "#rival #Other" {
t.Fatalf("entry: %+v", entries)
}
// Same name, different case: refused.
rec = postForm(h, "/market/save", url.Values{"name": {"RIVAL"}, "relationship": {"partner"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "already has that name") {
t.Errorf("duplicate: %d", rec.Code)
}
rec = postForm(h, "/market/import", url.Values{"example": {"federated"}, "relationship": {"watch"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "21 added") {
t.Errorf("import example: %d %s", rec.Code, rec.Body.String())
}
partners, _ := inventory.List(s.DB, "partner")
if len(partners) != 21 {
t.Errorf("example entries are partners: got %d", len(partners))
}
if rec := postForm(h, "/market/1/delete", nil); rec.Code != http.StatusSeeOther {
t.Errorf("delete: %d", rec.Code)
}
}
func TestAccountsKeepAndRemove(t *testing.T) {
s, h := newTestServer(t, nil)
postForm(h, "/settings/accounts", url.Values{secrets.XClientID: {" id-1 "}, secrets.YouTubeAPIKey: {"yt"}})
// Empty field keeps the value; remove clears it.
postForm(h, "/settings/accounts", url.Values{secrets.XClientID: {""}, "remove:" + secrets.YouTubeAPIKey: {"on"}})
if got := s.Secrets.Get(secrets.XClientID); got != "id-1" {
t.Errorf("x client id = %q", got)
}
if s.Secrets.Has(secrets.YouTubeAPIKey) {
t.Error("youtube key should be removed")
}
// The AI keys aren't on this tab, so it can't change them.
postForm(h, "/settings/accounts", url.Values{secrets.AnthropicAPIKey: {"sk-x"}})
if s.Secrets.Has(secrets.AnthropicAPIKey) {
t.Error("the accounts form saved an AI key")
}
// From the page, a save sends back just that card, updated, not a redirect.
rec := do(h, http.MethodPost, "/settings/accounts", strings.NewReader(url.Values{
"network": {"LinkedIn"}, secrets.LinkedInClientID: {"li"}, secrets.LinkedInClientSecret: {"ls"}}.Encode()),
map[string]string{"Content-Type": "application/x-www-form-urlencoded", "Origin": "http://localhost:8470", "HX-Request": "true"})
card := rec.Body.String()
if rec.Code != http.StatusOK || !strings.Contains(card, `id="network-LinkedIn"`) || strings.Contains(card, "<html") ||
!strings.Contains(card, "Saved.") || strings.Contains(card, "Save the client ID") || strings.Contains(card, `"li"`) {
t.Errorf("htmx save: %d\n%s", rec.Code, card)
}
if s.Secrets.Get(secrets.XClientID) != "id-1" {
t.Error("saving one card cleared another's keys")
}
page := do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
if strings.Contains(page, "id-1") {
t.Error("the accounts page must never show a saved value")
}
}
func TestAIKeysOnTheAITab(t *testing.T) {
s, h := newTestServer(t, nil)
form := url.Values{"provider": {"anthropic"}, "model": {"claude-opus-5-5"}, "effort": {"medium"},
secrets.AnthropicAPIKey: {" sk-1 "}}
if rec := postForm(h, "/settings/ai", form); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
}
if got := s.Secrets.Get(secrets.AnthropicAPIKey); got != "sk-1" {
t.Errorf("anthropic key = %q", got)
}
// A form that needs fixing still keeps the key typed into it.
rec := postForm(h, "/settings/ai", url.Values{"provider": {"openai"}, "model": {"m"}, secrets.OpenAIAPIKey: {"ok-2"}})
if rec.Code != http.StatusOK || s.Secrets.Get(secrets.OpenAIAPIKey) != "ok-2" {
t.Errorf("openai without address: %d, key %q", rec.Code, s.Secrets.Get(secrets.OpenAIAPIKey))
}
postForm(h, "/settings/ai", url.Values{"provider": {"anthropic"}, "model": {"m"}, "remove:" + secrets.AnthropicAPIKey: {"on"}})
if s.Secrets.Has(secrets.AnthropicAPIKey) {
t.Error("anthropic key should be removed")
}
if page := do(h, http.MethodGet, "/settings/ai", nil, nil).Body.String(); strings.Contains(page, "ok-2") {
t.Error("the AI page must never show a saved key")
}
}
func TestOldAddressesRedirect(t *testing.T) {
_, h := newTestServer(t, nil)
for old, now := range map[string]string{"/profile": "/settings/profile", "/core": "/settings/core", "/inbox": "/posts",
"/settings/credentials": "/settings/accounts", "/settings": "/settings/profile"} {
rec := do(h, http.MethodGet, old, nil, nil)
if rec.Code/100 != 3 || rec.Header().Get("Location") != now {
t.Errorf("%s: %d → %q", old, rec.Code, rec.Header().Get("Location"))
}
}
}
func TestSearch(t *testing.T) {
s, h := newTestServer(t, nil)
if err := inventory.Save(s.DB, &inventory.Entry{Name: "Rival Corp", Relationship: "competitor", Description: "Makes gadgets."}); err != nil {
t.Fatal(err)
}
if _, err := content.SaveItems(s.DB, []models.ContentItem{{ID: "rss:1", AppName: "Rival Corp", Source: models.SourceRSS,
Title: "Gadget 2 launches", Body: "Faster gadgets for everyone", PublishedAt: time.Now()}}); err != nil {
t.Fatal(err)
}
if _, err := content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Rival Corp", Kind: "competitor",
Channel: "x", Content: "Our widgets beat any gadget"}}); err != nil {
t.Fatal(err)
}
body := do(h, http.MethodGet, "/search?q=GADGET", nil, nil).Body.String()
for _, want := range []string{"Rival Corp", "Gadget 2 launches", "Our widgets beat any gadget", `href="/content/1"`, `href="/posts"`} {
if !strings.Contains(body, want) {
t.Errorf("search for gadget: missing %q", want)
}
}
// Every word must match.
if body := do(h, http.MethodGet, "/search?q=gadget+launches", nil, nil).Body.String(); strings.Contains(body, "Our widgets") {
t.Error("a draft without \"launches\" matched")
}
if body := do(h, http.MethodGet, "/search?q=anthropic+key", nil, nil).Body.String(); !strings.Contains(body, `href="/settings/ai"`) {
t.Error("settings search should find the AI tab")
}
}
func TestCallbackURLs(t *testing.T) {
s, h := newTestServer(t, nil)
s.PublicURL = "http://localhost:8470"
for provider, want := range map[string]string{
"x": "http://127.0.0.1:8470/auth/x/callback", // X refuses localhost
"linkedin": "http://localhost:8470/auth/linkedin/callback",
"reddit": "http://localhost:8470/auth/reddit/callback",
} {
if got := s.callbackURL(provider); got != want {
t.Errorf("%s: %s", provider, got)
}
}
if body := do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String(); !strings.Contains(body, "http://127.0.0.1:8470/auth/x/callback") {
t.Error("the accounts page should show X's 127.0.0.1 callback")
}
// The sign-in sends the same address X has registered.
_ = s.Secrets.Set(map[string]string{secrets.XClientID: "cid"})
rec := postForm(h, "/auth/x/start", nil)
if loc := rec.Header().Get("Location"); !strings.Contains(loc, url.QueryEscape("http://127.0.0.1:8470/auth/x/callback")) {
t.Errorf("x start: %d %s", rec.Code, loc)
}
}
func TestOAuthErrorIsShownOnce(t *testing.T) {
s, h := newTestServer(t, nil)
_ = s.Secrets.Set(map[string]string{secrets.LinkedInClientID: "cid", secrets.LinkedInClientSecret: "cs"})
loc, _ := url.Parse(postForm(h, "/auth/linkedin/start", nil).Header().Get("Location"))
state := loc.Query().Get("state")
body := do(h, http.MethodGet, "/auth/linkedin/callback?state="+state+"&error=unauthorized_scope_error&error_description="+
url.QueryEscape("Scope &quot;openid&quot; is not authorized"), nil, nil).Body.String()
if !strings.Contains(body, "Scope &#34;openid&#34; is not authorized") || strings.Contains(body, "&amp;quot;") {
t.Errorf("error page:\n%s", body)
}
}
func TestOAuthCallbackRejectsUnknownState(t *testing.T) {
_, h := newTestServer(t, nil)
rec := do(h, http.MethodGet, "/auth/x/callback?state=nope&code=c", nil, nil)
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "oauth-expired") {
t.Errorf("got %d %s", rec.Code, rec.Header().Get("Location"))
}
}
func TestMCPNeedsTokenAndChecksIn(t *testing.T) {
s, h := newTestServer(t, nil)
call := func(token string, body any) *httptest.ResponseRecorder {
raw, _ := json.Marshal(body)
hdr := map[string]string{"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
if token != "" {
hdr["Authorization"] = "Bearer " + token
}
return do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), hdr)
}
list := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
if rec := call("", list); rec.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", rec.Code)
}
if rec := call("wrong", list); rec.Code != http.StatusUnauthorized {
t.Errorf("wrong token: %d", rec.Code)
}
rec := call(testToken, list)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "bridge_checkin") {
t.Fatalf("tools/list: %d %s", rec.Code, rec.Body.String())
}
rec = call(testToken, map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": map[string]any{
"name": "bridge_checkin",
"arguments": map[string]any{"agent": "hermes", "mcphub_tools": []string{"espocrm_list_leads"}},
}})
if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), `"isError":true`) {
t.Fatalf("checkin: %d %s", rec.Code, rec.Body.String())
}
last, err := bridge.Last(s.DB)
if err != nil || last == nil || last.Agent != "hermes" || len(last.MCPHubTools) != 1 {
t.Fatalf("checkin not recorded: %+v %v", last, err)
}
}
func TestInventoryFillNeedsAI(t *testing.T) {
_, h := newTestServer(t, nil)
if body := do(h, http.MethodGet, "/market/new", nil, nil).Body.String(); !strings.Contains(body, `<a href="/settings/ai">set up the AI</a>`) {
t.Error("new entry without AI: no warning")
}
// The form comes back with what was typed, and says why.
rec := postForm(h, "/market/fill", url.Values{"name": {"Rival"}, "relationship": {"competitor"},
"description": {"Typed."}, "draft_url": {"https://rival.example"}})
body := rec.Body.String()
if rec.Code != http.StatusOK || !strings.Contains(body, "AI provider not configured") || !strings.Contains(body, "Typed.") {
t.Errorf("fill without AI: %d", rec.Code)
}
rec = postForm(h, "/market/fill", url.Values{"name": {"Rival"}})
if !strings.Contains(rec.Body.String(), "Enter their website") {
t.Error("fill without a website: no message")
}
}
func TestProfileDraftNeedsAI(t *testing.T) {
s, h := newTestServer(t, nil)
body := do(h, http.MethodGet, "/settings/profile", nil, nil).Body.String()
if !strings.Contains(body, `<a href="/settings/ai">choose an AI provider</a>`) || !strings.Contains(body, `class="secondary" disabled>Draft`) {
t.Errorf("profile without AI:\n%s", body)
}
_ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
if body := do(h, http.MethodGet, "/settings/profile", nil, nil).Body.String(); strings.Contains(body, "choose an AI provider") {
t.Error("warning shown with an AI key saved")
}
}
func TestLinkedInExpiryReminders(t *testing.T) {
s, h := newTestServer(t, nil)
_ = s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: "tok", secrets.LinkedInAuthorURN: "urn:li:person:1"})
day := 24 * time.Hour
get := func(path string) string { return do(h, http.MethodGet, path, nil, nil).Body.String() }
// Plenty of time: the card says until when, no reminders.
_ = s.saveConnection("linkedin", Connection{At: time.Now(), Expires: time.Now().Add(50 * day)})
if !strings.Contains(get("/settings/accounts"), "The sign-in lasts until") || strings.Contains(get("/"), "Reconnect LinkedIn") {
t.Error("50 days left: wrong reminders")
}
if !s.connected()["linkedin"] {
t.Error("50 days left: should be connected")
}
// Saved before expiries were recorded, 50 days ago: 10 days left.
_ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-50 * day)})
for _, path := range []string{"/", "/posts"} {
if body := get(path); !strings.Contains(body, "LinkedIn's sign-in expires in 9 days") && !strings.Contains(body, "LinkedIn's sign-in expires in 10 days") {
t.Errorf("%s: no 10-day reminder", path)
}
}
// Expired: reminders, not connected, and publishing says why.
_ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-61 * day), Expires: time.Now().Add(-day)})
if body := get("/"); !strings.Contains(body, "LinkedIn's sign-in expired on") {
t.Error("expired: no reminder on the Overview")
}
if !strings.Contains(get("/settings/accounts"), "The sign-in expired on") {
t.Error("expired: the card doesn't say so")
}
if s.connected()["linkedin"] {
t.Error("expired: still counted as connected")
}
if _, err := s.publishers()["linkedin"].Publish(context.Background(), content.Post{Text: "hi"}); err == nil ||
!strings.Contains(err.Error(), "reconnect LinkedIn") {
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)
}
}
// Prospects: add by hand, see the CRM warning, accept into the CRM queue,
// and the suppression list stops what's on it.
func TestProspectsReview(t *testing.T) {
s, h := newTestServer(t, nil)
rec, _ := crm.RecordFrom("Account", map[string]any{"id": "a1", "name": "Acme", "website": "https://acme.com"}, time.Now())
crm.Ingest(s.DB, []crm.Record{rec})
if rec := postForm(h, "/prospects/new", url.Values{}); !strings.Contains(rec.Body.String(), "Give a company, a person, or both") {
t.Error("an empty form was accepted")
}
form := url.Values{"company_name": {"Acme"}, "website": {"acme.com"}, "why": {"Runs its own servers"},
"first_name": {"Pat"}, "last_name": {"Lee"}, "title": {"CTO"}, "email": {"pat@acme.com"}, "source_detail": {"Met at FOSDEM"}}
if rec := postForm(h, "/prospects/new", form); rec.Code != http.StatusSeeOther {
t.Fatalf("add: %d %s", rec.Code, rec.Body.String())
}
body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String()
for _, want := range []string{"Acme", "Pat Lee", "Runs its own servers", "Met at FOSDEM", "Already in your CRM", "Accept with 1 person",
`<span class="count-badge" title="2 waiting for review">2</span>`} {
if !strings.Contains(body, want) {
t.Errorf("review page lacks %q in %s", want, body)
}
}
if rec := postForm(h, "/prospects/company/1/accept-all", url.Values{"tab": {"new"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("accept all: %d %s", rec.Code, rec.Body.String())
}
as, _ := crm.List(s.DB, 10)
if len(as) != 2 {
t.Fatalf("queued: %+v", as)
}
if body := do(h, http.MethodGet, "/prospects?status=accepted", nil, nil).Body.String(); !strings.Contains(body, "waiting for Hermes") {
t.Error("accepted tab doesn't show the CRM state")
}
// Suppression.
postForm(h, "/prospects/new", url.Values{"first_name": {"Ray"}, "last_name": {"Doe"}, "email": {"ray@other.org"}})
if rec := postForm(h, "/prospects/suppressed", url.Values{"value": {"other.org"}, "reason": {"partner"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("suppress: %d %s", rec.Code, rec.Body.String())
}
if body := do(h, http.MethodGet, "/prospects?status=rejected", nil, nil).Body.String(); !strings.Contains(body, "Ray Doe") {
t.Error("a suppressed prospect should be set aside")
}
if rec := postForm(h, "/prospects/new", url.Values{"last_name": {"Kim"}, "email": {"kim@other.org"}}); !strings.Contains(rec.Body.String(), "suppression list (kim@other.org)") {
t.Errorf("adding a suppressed person: %s", rec.Body.String())
}
if body := do(h, http.MethodGet, "/prospects/suppressed", nil, nil).Body.String(); !strings.Contains(body, "other.org") || !strings.Contains(body, "partner") {
t.Error("suppression list page")
}
postForm(h, "/prospects/suppressed", url.Values{"kind": {"domain"}, "value": {"other.org"}, "remove": {"1"}})
if list, _ := prospects.Suppressions(s.DB); len(list) != 0 {
t.Errorf("remove: %+v", list)
}
if body := do(h, http.MethodGet, "/search?q=pat+cto", nil, nil).Body.String(); !strings.Contains(body, "Pat Lee") || !strings.Contains(body, "/prospects?status=accepted") {
t.Error("search doesn't find the prospect")
}
if rec := postForm(h, "/prospects/contact/99/accept", url.Values{}); rec.Code != http.StatusNotFound {
t.Errorf("missing prospect: %d", rec.Code)
}
}
// Signals: define one, tag a prospect, record outcomes, and see them on
// the scorecard.
func TestSignalsFunnel(t *testing.T) {
s, h := newTestServer(t, nil)
rec := postForm(h, "/signals/new", url.Values{"name": {"Leaving Microsoft 365"}, "status": {"testing"},
"hypothesis": {"Price rise makes them switch"}, "spot": {"m365 alternative"}})
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signals/1") {
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
}
if rec := postForm(h, "/signals/new", url.Values{"name": {""}}); !strings.Contains(rec.Body.String(), "needs a name") {
t.Error("a nameless signal was accepted")
}
postForm(h, "/prospects/new", url.Values{"company_name": {"Acme"}, "website": {"acme.example"}, "first_name": {"Pat"},
"last_name": {"Lee"}, "email": {"pat@acme.example"}, "signal": {"1"}})
body := do(h, http.MethodGet, "/prospects?signal=1", nil, nil).Body.String()
if !strings.Contains(body, "Pat Lee") || !strings.Contains(body, `<option value="1" selected>Leaving Microsoft 365</option>`) {
t.Error("the prospect isn't shown with its signal")
}
if body := do(h, http.MethodGet, "/prospects?signal=99", nil, nil).Body.String(); strings.Contains(body, "Pat Lee") {
t.Error("the signal filter doesn't filter")
}
for _, f := range []url.Values{
{"stage": {"contacted"}, "channel": {"email"}, "date": {"2026-11-20"}},
{"stage": {"replied"}, "channel": {"email"}, "note": {"Interested, call next week"}},
{"stage": {"paid"}, "channel": {"email"}, "amount": {"$1,070.50"}},
} {
f.Set("tab", "new")
f.Set("filter", "1")
if rec := postForm(h, "/prospects/contact/1/outcome", f); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/prospects?status=new&signal=1&msg=outcome" {
t.Fatalf("outcome: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
}
}
if rec := postForm(h, "/prospects/contact/1/outcome", url.Values{"stage": {"paid"}, "channel": {"email"}, "amount": {"lots"}}); !strings.Contains(rec.Body.String(), "an amount") {
t.Errorf("a bad amount was accepted: %d", rec.Code)
}
body = do(h, http.MethodGet, "/signals", nil, nil).Body.String()
for _, want := range []string{"Leaving Microsoft 365", "$1,070.50", `<span class="rate">100%</span>`} {
if !strings.Contains(body, want) {
t.Errorf("scorecard lacks %q", want)
}
}
body = do(h, http.MethodGet, "/signals/1", nil, nil).Body.String()
if !strings.Contains(body, "Interested, call next week") || !strings.Contains(body, "Its prospects (1 new)") {
t.Error("the signal's page")
}
if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); !strings.Contains(body, "Interested, call next week") {
t.Error("the prospect's steps aren't shown")
}
// Moving the company to no signal moves its person and their steps.
postForm(h, "/prospects/company/1/signal", url.Values{"signal": {"0"}})
if rows, _ := signals.Scorecard(s.DB, signals.Filter{}); rows[0].Total() != 0 || rows[1].Signal != nil || rows[1].Counts["paid"] != 1 {
t.Errorf("after untagging: %+v", rows)
}
// An outside campaign, assigned to the signal.
signals.SaveCampaign(s.DB, signals.Campaign{Source: "explee", ID: "7", Name: "M365 movers", SpendCents: 990, SyncedAt: time.Now()})
if body := do(h, http.MethodGet, "/signals", nil, nil).Body.String(); !strings.Contains(body, "M365 movers") {
t.Error("campaign not listed")
}
postForm(h, "/signals/campaigns", url.Values{"source": {"explee"}, "id": {"7"}, "signal": {"1"}})
if cs, _ := signals.Campaigns(s.DB); cs[0].SignalID != 1 {
t.Errorf("assign: %+v", cs)
}
if rec := postForm(h, "/lead-sources/explee/import", nil); !strings.Contains(rec.Body.String(), "API key first") {
t.Errorf("import without a key: %s", rec.Body.String())
}
if body := do(h, http.MethodGet, "/search?q=microsoft", nil, nil).Body.String(); !strings.Contains(body, "/signals/1") {
t.Error("search doesn't find the signal")
}
// Lead source keys.
postForm(h, "/settings/sources", url.Values{secrets.ExpleeAPIKey: {"ex-key"}, "origami_project": {"proj"}})
if s.Secrets.Get(secrets.ExpleeAPIKey) != "ex-key" || s.origamiProject() != "proj" {
t.Error("lead source settings not saved")
}
if rec := postForm(h, "/settings/sources/test/origami", nil); !strings.Contains(rec.Body.String(), "Save the key first") {
t.Errorf("test without a key: %s", rec.Body.String())
}
postForm(h, "/signals/1/delete", nil)
if list, _ := signals.List(s.DB); len(list) != 0 {
t.Error("delete")
}
}
// The discovery card: what it needs before it can search, its schedule,
// and the run list.
func TestSignalDiscoveryCard(t *testing.T) {
s, h := newTestServer(t, nil)
postForm(h, "/signals/new", url.Values{"name": {"Leaving Microsoft 365"}, "spot": {"m365 alternative"},
"discover_every_days": {"7"}, "explee_definition": {"managed IT services"}})
sig, err := signals.Get(s.DB, 1)
if err != nil || sig.DiscoverEveryDays != 7 || sig.ExpleeDefinition != "managed IT services" {
t.Fatalf("saved: %+v %v", sig, err)
}
body := do(h, http.MethodGet, "/signals/1", nil, nil).Body.String()
for _, want := range []string{"Find companies", "No searches yet", `<option value="7" selected>Every 7 days</option>`,
"Save an explee.com API key"} {
if !strings.Contains(body, want) {
t.Errorf("signal page lacks %q", want)
}
}
if strings.Contains(body, `action="/signals/1/discover/claude"`) {
t.Error("the web search button shows without an AI key")
}
if rec := postForm(h, "/signals/1/discover/claude", nil); rec.Code == http.StatusSeeOther {
t.Error("a search started without an AI key")
}
s.Secrets.Set(map[string]string{secrets.ExpleeAPIKey: "k"})
if body := do(h, http.MethodGet, "/signals/1", nil, nil).Body.String(); !strings.Contains(body, `action="/signals/1/discover/explee"`) {
t.Error("the explee.com button doesn't show with a key and a description")
}
s.DB.Exec(`INSERT INTO discovery_runs (signal_id, source, status, started_at, found, added, skipped, searches, notes)
VALUES (1, 'claude', 'done', '2026-11-21T10:00:00Z', 5, 3, 2, 6, '["Rival: in your inventory (competitor)"]'),
(1, 'claude', 'running', '2026-11-21T11:00:00Z', 0, 0, 0, 0, '[]')`)
body = do(h, http.MethodGet, "/signals/1/runs", nil, nil).Body.String()
for _, want := range []string{"searching…", "3 new", "6 web searches", "Rival: in your inventory", `hx-trigger="every 4s"`} {
if !strings.Contains(body, want) {
t.Errorf("runs lack %q in %s", want, body)
}
}
}
func TestRedirectKeepsFragmentLast(t *testing.T) {
for path, want := range map[string]string{
"/signals#campaigns": "/signals?msg=saved#campaigns",
"/prospects?status=new#x": "/prospects?status=new&msg=saved#x",
"/signals": "/signals?msg=saved",
} {
w := httptest.NewRecorder()
redirect(w, httptest.NewRequest("POST", path, nil), path, "saved")
if got := w.Header().Get("Location"); got != want {
t.Errorf("%s: got %q, want %q", path, got, want)
}
}
}
// Settings → About shows the edition, and where the local edition keeps
// its database.
func TestAboutPage(t *testing.T) {
s, h := newTestServer(t, nil)
rec := do(h, "GET", "/settings/about", nil, nil)
if rec.Code != 200 {
t.Fatal(rec.Code)
}
body := rec.Body.String()
for _, want := range []string{"Local edition", "SQLite: " + s.DataDir + "/app.db", "SUPERMARKET_MODE", `href="/settings/about" aria-current="page"`} {
if !strings.Contains(body, want) {
t.Errorf("no %q", want)
}
}
}
// Settings → About lists this copy of the app, and work under way.
func TestAboutRunning(t *testing.T) {
s, h := newTestServer(t, nil)
_, release, err := s.jobs().TryLock(context.Background(), "job:seo")
if err != nil {
t.Fatal(err)
}
defer release()
body := do(h, "GET", "/settings/about", nil, nil).Body.String()
for _, want := range []string{"<code>" + s.jobs().ID() + "</code> <span class=\"muted\">(this one)</span>", "<code>job:seo</code>"} {
if !strings.Contains(body, want) {
t.Errorf("no %q", want)
}
}
}