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>
199 lines
6.2 KiB
Go
199 lines
6.2 KiB
Go
package crm
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"supermarket/internal/db"
|
|
)
|
|
|
|
func testDB(t *testing.T) *db.DB {
|
|
t.Helper()
|
|
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { d.Close() })
|
|
StateFile = filepath.Join(t.TempDir(), "crm-state")
|
|
t.Cleanup(func() { StateFile = "" })
|
|
return d
|
|
}
|
|
|
|
func lead(key, email string) Action {
|
|
return Action{Key: key, Entity: "Lead", Fields: map[string]any{"firstName": "Pat", "lastName": "Lee", "emailAddress": email},
|
|
Match: map[string]string{"emailAddress": email}, Origin: "test"}
|
|
}
|
|
|
|
func TestQueueClaimReport(t *testing.T) {
|
|
d := testDB(t)
|
|
a, err := Enqueue(d, lead("lead:pat@acme.example", "pat@acme.example"))
|
|
if err != nil || a.Status != StatusPending || a.Name() != "Pat Lee" {
|
|
t.Fatalf("enqueue: %+v %v", a, err)
|
|
}
|
|
// Queuing the same key again doesn't add a second action.
|
|
b, _ := Enqueue(d, lead("lead:pat@acme.example", "pat@acme.example"))
|
|
if b.ID != a.ID {
|
|
t.Errorf("same key queued twice: %d %d", a.ID, b.ID)
|
|
}
|
|
state, _ := os.ReadFile(StateFile)
|
|
if !strings.Contains(string(state), "pending: 1") {
|
|
t.Errorf("state file: %s", state)
|
|
}
|
|
|
|
now := time.Now()
|
|
claimed, err := Claim(d, now, 10)
|
|
if err != nil || len(claimed) != 1 || claimed[0].Attempts != 1 {
|
|
t.Fatalf("claim: %+v %v", claimed, err)
|
|
}
|
|
// Claimed actions aren't handed out again until they time out.
|
|
if again, _ := Claim(d, now.Add(time.Minute), 10); len(again) != 0 {
|
|
t.Errorf("claimed twice: %+v", again)
|
|
}
|
|
if again, _ := Claim(d, now.Add(ClaimTimeout+time.Minute), 10); len(again) != 1 || again[0].Attempts != 2 {
|
|
t.Errorf("a stuck claim should come back: %+v", again)
|
|
}
|
|
|
|
if err := Report(d, a.ID, Result{Outcome: OutcomeCreated}, now); err == nil {
|
|
t.Error("created without an ID accepted")
|
|
}
|
|
if err := Report(d, a.ID, Result{Outcome: OutcomeCreated, EspoID: "abc123"}, now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, _ := Get(d, a.ID)
|
|
if got.Status != StatusDone || got.EspoID != "abc123" || got.Outcome != OutcomeCreated {
|
|
t.Errorf("done: %+v", got)
|
|
}
|
|
// A second report for the same action is refused.
|
|
if err := Report(d, a.ID, Result{Outcome: "failed", Error: "x"}, now); err != ErrNoAction {
|
|
t.Errorf("second report: %v", err)
|
|
}
|
|
// And a done key isn't queued again.
|
|
if c, _ := Enqueue(d, lead("lead:pat@acme.example", "pat@acme.example")); c.Status != StatusDone {
|
|
t.Errorf("done action re-queued: %+v", c)
|
|
}
|
|
}
|
|
|
|
func TestFailRetryCancel(t *testing.T) {
|
|
d := testDB(t)
|
|
a, _ := Enqueue(d, lead("k1", "a@b.example"))
|
|
Claim(d, time.Now(), 10)
|
|
if err := Report(d, a.ID, Result{Outcome: "failed", Error: "hub said 500"}, time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got, _ := Get(d, a.ID); got.Status != StatusFailed || got.Error != "hub said 500" {
|
|
t.Errorf("failed: %+v", got)
|
|
}
|
|
if err := Retry(d, a.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got, _ := Get(d, a.ID); got.Status != StatusPending || got.Error != "" {
|
|
t.Errorf("retried: %+v", got)
|
|
}
|
|
if err := Cancel(d, a.ID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Retry(d, a.ID); err != ErrNoAction {
|
|
t.Errorf("retry a cancelled action: %v", err)
|
|
}
|
|
// A cancelled key can be queued again.
|
|
if b, _ := Enqueue(d, lead("k1", "a@b.example")); b.Status != StatusPending || b.ID != a.ID {
|
|
t.Errorf("re-queue cancelled: %+v", b)
|
|
}
|
|
counts, _ := Counts(d)
|
|
if counts[StatusPending] != 1 {
|
|
t.Errorf("counts: %v", counts)
|
|
}
|
|
}
|
|
|
|
func TestRecordsAndDuplicates(t *testing.T) {
|
|
d := testDB(t)
|
|
now := time.Now()
|
|
var recs []Record
|
|
for _, f := range []map[string]any{
|
|
{"id": "L1", "firstName": "Pat", "lastName": "Lee", "emailAddress": "Pat@Acme.example", "modifiedAt": "2026-11-20 10:00:00"},
|
|
{"id": "A1", "name": "Acme", "website": "https://www.acme.example/"},
|
|
{"id": "L2", "firstName": "Sam", "emailAddress": "sam@gmail.com"},
|
|
} {
|
|
entity := "Lead"
|
|
if f["id"] == "A1" {
|
|
entity = "Account"
|
|
}
|
|
r, err := RecordFrom(entity, f, now)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
recs = append(recs, r)
|
|
}
|
|
if _, err := RecordFrom("Lead", map[string]any{"name": "no id"}, now); err == nil {
|
|
t.Error("a record without an id was accepted")
|
|
}
|
|
if err := Ingest(d, recs); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := Ingest(d, recs[:1]); err != nil { // again: replaced, not added
|
|
t.Fatal(err)
|
|
}
|
|
counts, _ := RecordCounts(d)
|
|
if counts["Lead"] != 2 || counts["Account"] != 1 {
|
|
t.Errorf("record counts: %v", counts)
|
|
}
|
|
dups, _ := Duplicates(d, "", "acme.example")
|
|
if len(dups) != 2 { // the Account by website, the Lead by email domain
|
|
t.Errorf("by domain: %+v", dups)
|
|
}
|
|
if dups, _ := Duplicates(d, "PAT@acme.example", ""); len(dups) != 1 || dups[0].Name != "Pat Lee" {
|
|
t.Errorf("by email: %+v", dups)
|
|
}
|
|
if dups, _ := Duplicates(d, "", "gmail.com"); len(dups) != 0 {
|
|
t.Errorf("free mail domains must not match: %+v", dups)
|
|
}
|
|
}
|
|
|
|
func TestSyncState(t *testing.T) {
|
|
d := testDB(t)
|
|
now := time.Now()
|
|
if due, _, _ := SyncDue(d, now); !due {
|
|
t.Error("never synced: due")
|
|
}
|
|
SyncDone(d, now)
|
|
if due, _, _ := SyncDue(d, now.Add(time.Hour)); due {
|
|
t.Error("just synced: not due")
|
|
}
|
|
if due, _, _ := SyncDue(d, now.Add(SyncEvery)); !due {
|
|
t.Error("after SyncEvery: due")
|
|
}
|
|
RequestSync(d, now.Add(time.Minute))
|
|
if due, _, _ := SyncDue(d, now.Add(2*time.Minute)); !due {
|
|
t.Error("requested: due")
|
|
}
|
|
// The state file stays the same while nothing changes, within the hour.
|
|
base := now.Truncate(time.Hour)
|
|
s1, _ := State(d, base.Add(2*time.Minute))
|
|
s2, _ := State(d, base.Add(3*time.Minute))
|
|
if s1 != s2 || !strings.Contains(s1, "sync: due") {
|
|
t.Errorf("state: %q %q", s1, s2)
|
|
}
|
|
// But while work waits, it changes each hour, so a failed run is retried.
|
|
if s3, _ := State(d, base.Add(time.Hour+time.Minute)); s3 == s1 {
|
|
t.Error("waiting work should change the state hourly")
|
|
}
|
|
// With nothing to do, it doesn't change at all.
|
|
SyncDone(d, now.Add(5*time.Minute))
|
|
i1, _ := State(d, now.Add(6*time.Minute))
|
|
i2, _ := State(d, now.Add(3*time.Hour))
|
|
if i1 != i2 || strings.Contains(i1, "waiting") {
|
|
t.Errorf("idle state should be stable: %q %q", i1, i2)
|
|
}
|
|
}
|
|
|
|
func TestDomain(t *testing.T) {
|
|
for in, want := range map[string]string{"https://www.Acme.example/about": "acme.example", "acme.example": "acme.example", "": ""} {
|
|
if got := Domain(in); got != want {
|
|
t.Errorf("Domain(%q) = %q", in, got)
|
|
}
|
|
}
|
|
}
|