// Package crm is Supermarket's side of the CRM bridge. Supermarket never // writes to EspoCRM itself: what the user approves waits in a queue, with // its exact fields and how to recognise an existing record, until Hermes // carries it out through the Core's MCP hub and reports back. Hermes also // copies CRM records here, so Supermarket can spot duplicates before // queueing anything. package crm import ( "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "fmt" "net/url" "os" "path/filepath" "strings" "time" "supermarket/internal/db" ) // Action kinds and statuses. const ( KindCreate = "create" StatusPending = "pending" // waiting for Hermes StatusClaimed = "claimed" // handed to Hermes, result not back yet StatusDone = "done" // created, or found already there StatusFailed = "failed" // Hermes reported an error; can be retried StatusCancelled = "cancelled" // the user took it back OutcomeCreated = "created" OutcomeExisting = "existing" // a matching record was already in the CRM ) // ClaimTimeout is how long a claimed action waits for its result before // it's handed out again (a run that died half way). const ClaimTimeout = time.Hour // SyncEvery is how often Hermes is asked to copy changed CRM records. const SyncEvery = 6 * time.Hour // SyncEntities are the record types copied for dedupe and, later, metrics. var SyncEntities = []string{"Lead", "Account", "Contact"} // Action is one queued CRM change. type Action struct { ID int64 `json:"id"` Key string `json:"key"` Kind string `json:"kind"` Entity string `json:"entity"` Fields map[string]any `json:"fields"` Match map[string]string `json:"match"` Origin string `json:"origin"` Status string `json:"status"` Outcome string `json:"outcome,omitempty"` EspoID string `json:"espo_id,omitempty"` Error string `json:"error,omitempty"` Attempts int `json:"attempts"` CreatedAt time.Time `json:"created_at"` ClaimedAt time.Time `json:"claimed_at,omitempty"` DoneAt time.Time `json:"done_at,omitempty"` } // Name is a short label for the page: the record's name or email. func (a *Action) Name() string { for _, k := range []string{"name", "accountName"} { if v, ok := a.Fields[k].(string); ok && v != "" { return v } } first, _ := a.Fields["firstName"].(string) last, _ := a.Fields["lastName"].(string) if n := strings.TrimSpace(first + " " + last); n != "" { return n } email, _ := a.Fields["emailAddress"].(string) return email } const timeFormat = time.RFC3339 func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) } func parseTime(s sql.NullString) time.Time { if !s.Valid { return time.Time{} } t, _ := time.Parse(timeFormat, s.String) return t } // ErrNoAction means there's no action with that ID, or not in a state that // allows the change. var ErrNoAction = errors.New("no such CRM action, or it can't be changed now") // Enqueue queues an action. One with the same key that is already queued or // done is returned instead, so approving twice doesn't create two Leads; a // cancelled one is queued again. func Enqueue(d *db.DB, a Action) (*Action, error) { if a.Key == "" || a.Entity == "" || len(a.Fields) == 0 { return nil, errors.New("a CRM action needs a key, an entity and fields") } if a.Kind == "" { a.Kind = KindCreate } if a.Match == nil { a.Match = map[string]string{} } fields, err := json.Marshal(a.Fields) if err != nil { return nil, err } match, err := json.Marshal(a.Match) if err != nil { return nil, err } _, err = d.Exec(`INSERT INTO crm_actions (key, kind, entity, fields, match, origin) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET kind = excluded.kind, entity = excluded.entity, fields = excluded.fields, match = excluded.match, origin = excluded.origin, status = 'pending', outcome = '', espo_id = '', error = '', claimed_at = NULL, done_at = NULL, created_at = excluded.created_at WHERE crm_actions.status = 'cancelled'`, a.Key, a.Kind, a.Entity, string(fields), string(match), a.Origin) if err != nil { return nil, err } if err := writeState(d); err != nil { return nil, err } return getByKey(d, a.Key) } const actionColumns = `id, key, kind, entity, fields, match, origin, status, outcome, espo_id, error, attempts, created_at, claimed_at, done_at` func scan(rows *sql.Rows) ([]Action, error) { defer rows.Close() var out []Action for rows.Next() { var a Action var fields, match, created string var claimed, done sql.NullString if err := rows.Scan(&a.ID, &a.Key, &a.Kind, &a.Entity, &fields, &match, &a.Origin, &a.Status, &a.Outcome, &a.EspoID, &a.Error, &a.Attempts, &created, &claimed, &done); err != nil { return nil, err } _ = json.Unmarshal([]byte(fields), &a.Fields) _ = json.Unmarshal([]byte(match), &a.Match) a.CreatedAt = parseTime(sql.NullString{String: created, Valid: true}) a.ClaimedAt, a.DoneAt = parseTime(claimed), parseTime(done) out = append(out, a) } return out, rows.Err() } func getByKey(d *db.DB, key string) (*Action, error) { rows, err := d.Query(`SELECT `+actionColumns+` FROM crm_actions WHERE key = ?`, key) if err != nil { return nil, err } as, err := scan(rows) if err != nil || len(as) == 0 { return nil, err } return &as[0], nil } // Get returns one action. func Get(d *db.DB, id int64) (*Action, error) { rows, err := d.Query(`SELECT `+actionColumns+` FROM crm_actions WHERE id = ?`, id) if err != nil { return nil, err } as, err := scan(rows) if err != nil { return nil, err } if len(as) == 0 { return nil, ErrNoAction } return &as[0], nil } // List returns actions, newest first; with statuses, only those. func List(d *db.DB, limit int, statuses ...string) ([]Action, error) { q := `SELECT ` + actionColumns + ` FROM crm_actions` var args []any if len(statuses) > 0 { q += ` WHERE status IN (?` + strings.Repeat(", ?", len(statuses)-1) + `)` for _, s := range statuses { args = append(args, s) } } q += ` ORDER BY id DESC LIMIT ?` rows, err := d.Query(q, append(args, limit)...) if err != nil { return nil, err } return scan(rows) } // Counts is how many actions are in each status. func Counts(d *db.DB) (map[string]int, error) { rows, err := d.Query(`SELECT status, count(*) FROM crm_actions GROUP BY status`) if err != nil { return nil, err } defer rows.Close() out := map[string]int{} for rows.Next() { var s string var n int if err := rows.Scan(&s, &n); err != nil { return nil, err } out[s] = n } return out, rows.Err() } // Claim hands Hermes the actions to carry out: pending ones, and claimed // ones whose result never came (after ClaimTimeout). They're marked claimed // so a second run at the same time doesn't do them again. func Claim(d *db.DB, now time.Time, limit int) ([]Action, error) { tx, err := d.Begin() if err != nil { return nil, err } defer tx.Rollback() rows, err := tx.Query(`SELECT `+actionColumns+` FROM crm_actions WHERE status = ? OR (status = ? AND claimed_at < ?) ORDER BY id LIMIT ?`, StatusPending, StatusClaimed, formatTime(now.Add(-ClaimTimeout)), limit) if err != nil { return nil, err } as, err := scan(rows) if err != nil { return nil, err } for i := range as { if _, err := tx.Exec(`UPDATE crm_actions SET status = ?, claimed_at = ?, attempts = attempts + 1 WHERE id = ?`, StatusClaimed, formatTime(now), as[i].ID); err != nil { return nil, err } as[i].Status, as[i].ClaimedAt = StatusClaimed, now as[i].Attempts++ } if err := tx.Commit(); err != nil { return nil, err } return as, writeState(d) } // Result is what Hermes reports for one action. type Result struct { Outcome string // created, existing, or failed EspoID string Error string } // Report records an action's result. A result for an action that isn't // claimed (already reported, or cancelled meanwhile) is refused. func Report(d *db.DB, id int64, r Result, now time.Time) error { var res sql.Result var err error switch r.Outcome { case OutcomeCreated, OutcomeExisting: if strings.TrimSpace(r.EspoID) == "" { return errors.New("a created or existing record needs its EspoCRM ID") } res, err = d.Exec(`UPDATE crm_actions SET status = ?, outcome = ?, espo_id = ?, error = '', done_at = ? WHERE id = ? AND status = ?`, StatusDone, r.Outcome, strings.TrimSpace(r.EspoID), formatTime(now), id, StatusClaimed) case "failed": msg := strings.TrimSpace(r.Error) if msg == "" { msg = "Hermes reported a failure without a reason" } res, err = d.Exec(`UPDATE crm_actions SET status = ?, error = ?, done_at = ? WHERE id = ? AND status = ?`, StatusFailed, msg, formatTime(now), id, StatusClaimed) default: return fmt.Errorf("outcome must be created, existing or failed, not %q", r.Outcome) } if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return ErrNoAction } return writeState(d) } // Retry queues a failed action again. func Retry(d *db.DB, id int64) error { return setStatus(d, id, StatusPending, StatusFailed) } // Cancel takes back an action Hermes hasn't done. func Cancel(d *db.DB, id int64) error { return setStatus(d, id, StatusCancelled, StatusPending, StatusFailed, StatusClaimed) } func setStatus(d *db.DB, id int64, to string, from ...string) error { args := []any{to, id} for _, f := range from { args = append(args, f) } res, err := d.Exec(`UPDATE crm_actions SET status = ?, error = CASE WHEN ? = 'pending' THEN '' ELSE error END WHERE id = ? AND status IN (?`+strings.Repeat(", ?", len(from)-1)+`)`, append([]any{to, to}, args[1:]...)...) if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return ErrNoAction } return writeState(d) } // --- Records copied from the CRM --- // Record is one CRM record as Hermes sent it. type Record struct { Entity string EspoID string Name string Email string Domain string Data map[string]any ModifiedAt string SyncedAt time.Time } // RecordFrom builds a Record from the fields Hermes sent (EspoCRM's names). func RecordFrom(entity string, f map[string]any, now time.Time) (Record, error) { str := func(k string) string { v, _ := f[k].(string) return strings.TrimSpace(v) } r := Record{Entity: entity, EspoID: str("id"), Data: f, ModifiedAt: str("modifiedAt"), SyncedAt: now} if r.EspoID == "" { return r, errors.New("a record without an id") } r.Name = str("name") if r.Name == "" { r.Name = strings.TrimSpace(str("firstName") + " " + str("lastName")) } if r.Name == "" { r.Name = str("accountName") } r.Email = strings.ToLower(str("emailAddress")) r.Domain = Domain(str("website")) if r.Domain == "" { r.Domain = EmailDomain(r.Email) } return r, nil } // Ingest stores records Hermes copied from the CRM, replacing older copies. func Ingest(d *db.DB, recs []Record) error { tx, err := d.Begin() if err != nil { return err } defer tx.Rollback() for _, r := range recs { data, err := json.Marshal(r.Data) if err != nil { return err } if _, err := tx.Exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, modified_at, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (entity, espo_id) DO UPDATE SET name = excluded.name, email = excluded.email, domain = excluded.domain, data = excluded.data, modified_at = excluded.modified_at, synced_at = excluded.synced_at`, r.Entity, r.EspoID, r.Name, r.Email, r.Domain, string(data), r.ModifiedAt, formatTime(r.SyncedAt)); err != nil { return err } } return tx.Commit() } // RecordCounts is how many records of each entity are copied. func RecordCounts(d *db.DB) (map[string]int, error) { rows, err := d.Query(`SELECT entity, count(*) FROM crm_records GROUP BY entity`) if err != nil { return nil, err } defer rows.Close() out := map[string]int{} for rows.Next() { var e string var n int if err := rows.Scan(&e, &n); err != nil { return nil, err } out[e] = n } return out, rows.Err() } // Duplicates returns copied CRM records with this email, or this domain // (a company's website or email domain). Free-mail domains don't count. func Duplicates(d *db.DB, email, domain string) ([]Record, error) { email = strings.ToLower(strings.TrimSpace(email)) domain = Domain(domain) if freeMail[domain] { domain = "" } if email == "" && domain == "" { return nil, nil } rows, err := d.Query(`SELECT entity, espo_id, name, email, domain, data, modified_at, synced_at FROM crm_records WHERE (? != '' AND email = ?) OR (? != '' AND domain = ?) ORDER BY entity, name LIMIT 20`, email, email, domain, domain) if err != nil { return nil, err } defer rows.Close() var out []Record for rows.Next() { var r Record var data, synced string if err := rows.Scan(&r.Entity, &r.EspoID, &r.Name, &r.Email, &r.Domain, &data, &r.ModifiedAt, &synced); err != nil { return nil, err } _ = json.Unmarshal([]byte(data), &r.Data) r.SyncedAt, _ = time.Parse(timeFormat, synced) out = append(out, r) } return out, rows.Err() } // Domain is a website's host without www., lower case. func Domain(site string) string { site = strings.TrimSpace(strings.ToLower(site)) if site == "" { return "" } if !strings.Contains(site, "://") { site = "https://" + site } u, err := url.Parse(site) if err != nil { return "" } return strings.TrimPrefix(u.Hostname(), "www.") } // EmailDomain is the part of an address after @. func EmailDomain(email string) string { if _, d, ok := strings.Cut(strings.ToLower(strings.TrimSpace(email)), "@"); ok { return d } return "" } var freeMail = map[string]bool{"gmail.com": true, "googlemail.com": true, "outlook.com": true, "hotmail.com": true, "yahoo.com": true, "icloud.com": true, "me.com": true, "aol.com": true, "proton.me": true, "protonmail.com": true, "gmx.com": true, "live.com": true, "msn.com": true} // --- Sync --- const syncKey = "crm_sync" // SyncState is when Hermes last copied CRM records, and whether the user // asked for a sync now. type SyncState struct { Last time.Time `json:"last"` Requested time.Time `json:"requested,omitempty"` Started time.Time `json:"started,omitempty"` // when Hermes was last asked to sync } // LoadSync returns the sync state. func LoadSync(d *db.DB) (SyncState, error) { var s SyncState _, err := d.GetJSON(syncKey, &s) return s, err } // SyncDue reports whether Hermes should copy records on this run, and from // when. func SyncDue(d *db.DB, now time.Time) (bool, time.Time, error) { s, err := LoadSync(d) if err != nil { return false, time.Time{}, err } due := s.Last.IsZero() || now.Sub(s.Last) >= SyncEvery || s.Requested.After(s.Last) return due, s.Last, nil } // StartSync records that Hermes was asked to sync, so the sync counts from // then once it's done. func StartSync(d *db.DB, now time.Time) error { s, err := LoadSync(d) if err != nil { return err } s.Started = now return d.PutJSON(syncKey, s) } // FinishSync records that Hermes finished the sync it was last asked for. func FinishSync(d *db.DB, now time.Time) error { s, err := LoadSync(d) if err != nil { return err } at := s.Started if at.IsZero() || at.After(now) { at = now } return SyncDone(d, at) } // SyncDone records a finished sync, as of when it started. func SyncDone(d *db.DB, at time.Time) error { s, err := LoadSync(d) if err != nil { return err } s.Last = at if err := d.PutJSON(syncKey, s); err != nil { return err } return writeState(d) } // RequestSync asks for a sync on Hermes' next run. func RequestSync(d *db.DB, now time.Time) error { s, err := LoadSync(d) if err != nil { return err } s.Requested = now if err := d.PutJSON(syncKey, s); err != nil { return err } return writeState(d) } // --- The state file Hermes' job checks --- // StateFile, if set, is where Supermarket writes a summary of what Hermes // has to do: pending action IDs and whether a sync is due. Hermes' job runs // a script that prints it; when it hasn't changed, Hermes skips the run // and spends nothing. var StateFile string // State is the state file's content: stable while nothing changes. func State(d *db.DB, now time.Time) (string, error) { rows, err := d.Query(`SELECT id FROM crm_actions WHERE status = ? OR (status = ? AND claimed_at < ?) ORDER BY id`, StatusPending, StatusClaimed, formatTime(now.Add(-ClaimTimeout))) if err != nil { return "", err } defer rows.Close() var ids []string for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return "", err } ids = append(ids, fmt.Sprint(id)) } if err := rows.Err(); err != nil { return "", err } due, last, err := SyncDue(d, now) if err != nil { return "", err } sync := "no" if due { // Changes once per sync, not on every write. sync = "due since " + formatTime(last) } h := sha256.Sum256([]byte(strings.Join(ids, ","))) out := fmt.Sprintf("supermarket crm\npending: %d (%s)\nsync: %s\n", len(ids), hex.EncodeToString(h[:6]), sync) if len(ids) > 0 || due { // Hermes skips a run while this file is unchanged. If a run fails // without touching the queue, nothing here would change and it // would never try again: so while work waits, the hour is shown // too, and Hermes tries again at least hourly. out += "waiting, checked " + now.UTC().Truncate(time.Hour).Format("2006-01-02 15h") + "\n" } return out, nil } // writeState updates the state file, if there is one. func writeState(d *db.DB) error { return WriteState(d, time.Now()) } // WriteState writes the state file now (the app also calls it on a timer, // so a sync falls due and a stuck claim comes back). func WriteState(d *db.DB, now time.Time) error { if StateFile == "" { return nil } s, err := State(d, now) if err != nil { return err } if old, err := os.ReadFile(StateFile); err == nil && string(old) == s { return nil } tmp := StateFile + ".tmp" if err := os.WriteFile(tmp, []byte(s), 0o600); err != nil { return err } return os.Rename(tmp, filepath.Clean(StateFile)) } // IsFreeMail reports whether a domain is a free email provider's, which // says nothing about the company. func IsFreeMail(domain string) bool { return freeMail[strings.ToLower(domain)] }