Phase 6 part 3: website lead forms into EspoCRM

Sites → Lead forms sets up the site's forms to create EspoCRM Leads
through its Lead Capture: the address saved and tested with a CORS
preflight, and a pull request adding a script that maps the form's fields
onto a Lead (campaign, page and form in the description). Plausible's
Lead goal is imported per signal as interested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 14:54:26 -07:00
co-authored by Claude Opus 5.5
parent fa4792e0fe
commit 2c42857419
12 changed files with 1003 additions and 9 deletions
+89 -2
View File
@@ -136,7 +136,7 @@ func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites [
campaigns = append(campaigns, slug)
}
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
visits := 0
visits, leads, leadNote := 0, 0, ""
for _, site := range sites {
var through string
if _, err := d.GetJSON(plausibleStateKey(site), &through); err != nil {
@@ -192,15 +192,73 @@ func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites [
visits += n
}
}
n, err := importLeads(ctx, d, c, site, from, yesterday, campaigns, tags)
if err != nil {
leadNote = fmt.Sprintf(" Form leads weren't read from %s: %v.", site, err)
}
leads += n
if err := d.PutJSON(plausibleStateKey(site), yesterday); err != nil {
return save(d, SourcePlausible, res, err)
}
}
res.Through = yesterday
res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal.", visits)
res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal; %d form leads.", visits, leads) + leadNote
return save(d, SourcePlausible, res, nil)
}
// LeadGoal is the Plausible goal (a custom event) the sites' lead forms
// send when they're submitted.
const LeadGoal = "Lead"
// importLeads counts the lead forms sent on visits tagged with a signal
// (Plausible's Lead goal, by the visit's UTM tags) as interested, on the
// signal's funnel. Without the goal set up in Plausible, it reports why.
func importLeads(ctx context.Context, d *db.DB, c *plausible.Client, site, from, to string, campaigns []any, tags map[string]int64) (int, error) {
rows, err := c.Run(ctx, plausible.Query{
SiteID: site,
Metrics: []string{"events"},
DateRange: []string{from, to},
Dimensions: []string{"time:day", "visit:utm_campaign", "visit:utm_source", "visit:utm_medium"},
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}, {"is", "visit:utm_campaign", campaigns}},
Pagination: &plausible.Pagination{Limit: 10000},
})
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "goal") {
return 0, fmt.Errorf("add a %q goal (a custom event) in Plausible to count them", LeadGoal)
}
return 0, err
}
n := 0
for _, r := range rows {
if len(r.Dimensions) < 4 || len(r.Metrics) < 1 || r.Metrics[0] < 1 {
continue
}
day, campaign, source, medium := r.Dimensions[0], r.Dimensions[1], r.Dimensions[2], r.Dimensions[3]
sig, ok := tags[strings.ToLower(campaign)]
if !ok {
continue
}
at, err := time.ParseInLocation(dayFormat, day[:min(len(day), 10)], time.Local)
if err != nil {
continue
}
count := int(r.Metrics[0])
note := strings.Trim(none(source)+" / "+none(medium), " /")
added, err := signals.Record(d, signals.Event{
SignalID: sig, Stage: signals.StageInterested, Channel: Channel(none(source), none(medium)),
Source: SourcePlausible, Count: count, Note: site + ": sent a lead form" + strings.TrimSuffix(" ("+note+")", " ()"),
At: at.Add(12 * time.Hour), ExternalID: strings.Join([]string{"lead", site, day, campaign, source, medium}, "|"),
})
if err != nil {
return n, err
}
if added {
n += count
}
}
return n, nil
}
// none is "" for Plausible's empty values.
func none(v string) string {
if v == "(none)" || v == "(not set)" {
@@ -269,3 +327,32 @@ func PageVisitors(ctx context.Context, c *plausible.Client, site string, paths [
}
return out, nil
}
// FormLead is a day's lead forms for a signal, as counted from Plausible.
type FormLead struct {
Signal string
Count int
Note string
At time.Time
}
// FormLeads are the latest lead forms counted, newest first.
func FormLeads(d *db.DB, limit int) ([]FormLead, error) {
rows, err := d.Query(`SELECT coalesce(s.name, ''), e.count, e.note, e.at FROM funnel_events e LEFT JOIN signals s ON s.id = e.signal_id
WHERE e.source = ? AND e.external_id LIKE 'lead|%' ORDER BY e.at DESC, e.id DESC LIMIT ?`, SourcePlausible, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []FormLead
for rows.Next() {
var f FormLead
var at string
if err := rows.Scan(&f.Signal, &f.Count, &f.Note, &at); err != nil {
return nil, err
}
f.At, _ = time.Parse(time.RFC3339, at)
out = append(out, f)
}
return out, rows.Err()
}
+40 -6
View File
@@ -70,6 +70,13 @@ func TestImportPlausible(t *testing.T) {
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
got = append(got, q)
if len(q.Filters) == 2 { // the lead forms (the Lead goal)
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social"}, "metrics": []float64{1}},
map[string]any{"dimensions": []string{"2026-11-21", "old-campaign", "x", "social"}, "metrics": []float64{3}},
}})
return
}
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-20", "leaving-m365", "email", "outreach", "outreach-3"}, "metrics": []float64{2}},
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social", "(none)"}, "metrics": []float64{5}},
@@ -82,7 +89,7 @@ func TestImportPlausible(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") {
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") || !strings.Contains(res.Detail, "1 form leads") {
t.Fatalf("result: %+v", res)
}
q := got[0]
@@ -90,17 +97,24 @@ func TestImportPlausible(t *testing.T) {
if q.SiteID != "federated.computer" || string(dr) != `["2026-10-23","2026-11-21"]` || len(q.Filters) != 1 {
t.Errorf("query: %+v %s", q, dr)
}
if lq, _ := json.Marshal(got[1].Filters); !strings.Contains(string(lq), `["is","event:goal",["Lead"]]`) {
t.Errorf("leads query: %s", lq)
}
evs, _ := signals.RecentEvents(d, m365, 10)
if len(evs) != 2 || evs[0].Stage != signals.StageVisited || evs[0].Channel != "social" || evs[0].Count != 5 ||
evs[1].Channel != "email" || !strings.Contains(evs[1].Note, "outreach-3") {
t.Errorf("events: %+v", evs)
var stages []string
for _, e := range evs {
stages = append(stages, e.Stage+"/"+e.Channel)
}
if len(evs) != 3 || strings.Join(stages, " ") != "interested/social visited/social visited/email" ||
!strings.Contains(evs[0].Note, "sent a lead form (linkedin / social)") || !strings.Contains(evs[2].Note, "outreach-3") {
t.Errorf("events: %v %+v", stages, evs)
}
// The next day reads only the new day; running again the same day reads nothing.
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 1 {
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 2 {
t.Errorf("same day: %d queries, %v", len(got), err)
}
res, _ = ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now.AddDate(0, 0, 1))
dr, _ = json.Marshal(got[1].DateRange)
dr, _ = json.Marshal(got[2].DateRange)
if string(dr) != `["2026-11-22","2026-11-22"]` || res.Added != 0 {
t.Errorf("next day: %s %+v", dr, res)
}
@@ -198,3 +212,23 @@ func TestSyncStripe(t *testing.T) {
t.Error("a bad key worked")
}
}
func TestImportLeadsWithoutTheGoal(t *testing.T) {
d := openDB(t)
signal(t, d, "Leaving M365", "leaving-m365")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
if len(q.Filters) == 2 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"The goal ` + "`Lead`" + ` is not configured for this site."}`))
return
}
w.Write([]byte(`{"results":[]}`))
}))
defer srv.Close()
res, err := ImportPlausible(context.Background(), d, plausible.New(srv.URL, "k"), []string{"federated.computer"}, now)
if err != nil || !strings.Contains(res.Detail, `add a "Lead" goal`) || res.Through != "2026-11-21" {
t.Errorf("%+v %v", res, err)
}
}