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
+148
View File
@@ -0,0 +1,148 @@
package web
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/hugorepo"
"supermarket/internal/sites"
"supermarket/internal/tracking"
)
// captureClient is the HTTP client for testing a Lead Capture (a test's
// TLS server's in tests).
var captureClient = sites.TestClient
func captureKey(repo string) string { return "sites:lead-capture:" + repo }
func formsPRKey(repo string) string { return "sites:lead-forms-pr:" + repo }
// formsPR is the pull request that connects a site's forms.
type formsPR struct {
Number int64 `json:"number"`
URL string `json:"url"`
Capture string `json:"capture"`
At time.Time `json:"at"`
State string `json:"state"` // open, merged, closed
}
func (s *Server) sitesFormsPage(w http.ResponseWriter, r *http.Request) {
s.renderForms(w, r, "", "")
}
func (s *Server) renderForms(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
all, cur := s.currentSite(r)
data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Payload": sites.LeadPayloadFields,
"Goal": tracking.LeadGoal, "Plausible": s.plausible() != nil}
if s.Core != nil && s.Core.Domain != "" {
data["CRM"] = "https://espocrm." + s.Core.Domain
}
if cur != nil && cur.Repo != "" {
var capture string
s.DB.GetJSON(captureKey(cur.Repo), &capture)
data["Capture"] = capture
var pr formsPR
if ok, _ := s.DB.GetJSON(formsPRKey(cur.Repo), &pr); ok {
if pr.State == "open" && s.gitea() != nil {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
if pull, err := s.gitea().GetPull(ctx, cur.Repo, pr.Number); err == nil {
switch {
case pull.Merged:
pr.State = "merged"
case pull.State == "closed":
pr.State = "closed"
}
_ = s.DB.PutJSON(formsPRKey(cur.Repo), pr)
}
cancel()
}
data["PR"] = pr
}
var synced siteSynced
if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok && !synced.At.IsZero() {
data["HasSynced"] = true
wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch}
wc.Acquire()
cat, _ := sites.Read(wc.Dir, wc.PathOf)
st := sites.ReadForms(wc, cat)
wc.Release()
data["State"] = st
data["Connected"] = st.Connected(capture)
}
}
data["Leads"], _ = tracking.FormLeads(s.DB, 20)
s.render(w, r, "sites-forms", page{Title: "Lead forms", Nav: "sites/forms", Error: errMsg, Flash: flash, Data: data})
}
func (s *Server) sitesFormsAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, cur := s.currentSite(r)
if cur == nil || cur.Repo == "" {
s.renderForms(w, r, "Set this website's Hugo repository in Settings → Profile first.", "")
return
}
capture := strings.TrimSpace(r.PostFormValue("capture"))
if _, has := r.PostForm["capture"]; !has {
s.DB.GetJSON(captureKey(cur.Repo), &capture)
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
switch r.PathValue("action") {
case "save":
if capture != "" {
if err := sites.CheckCaptureURL(capture); err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
}
if err := s.DB.PutJSON(captureKey(cur.Repo), capture); err != nil {
s.serverError(w, err)
return
}
if capture == "" {
s.renderForms(w, r, "", "The Lead Capture address is removed.")
return
}
if err := sites.TestCapture(ctx, captureClient(), capture, cur.URL); err != nil {
s.renderForms(w, r, "Saved, but the test failed: "+err.Error(), "")
return
}
s.renderForms(w, r, "", "Saved and tested: "+cur.URL+" may post to it. Nothing was created in the CRM.")
case "connect":
if capture == "" {
s.renderForms(w, r, "Save the Lead Capture address first.", "")
return
}
if s.gitea() == nil {
s.renderForms(w, r, "Save a Gitea token under Settings → Search engines first.", "")
return
}
cat, err := s.catalog(ctx, *cur, true)
if err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
formPage := ""
if t := cat.Type("form"); t != nil && len(t.Pages) > 0 {
formPage = t.Pages[0]
}
pull, err := sites.ConnectForms(ctx, s.applier(seoSite{Index: cur.Index, URL: cur.URL}), capture, formPage)
if err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
pr := formsPR{Number: pull.Number, URL: pull.HTMLURL, Capture: capture, At: time.Now(), State: "open"}
if err := s.DB.PutJSON(formsPRKey(cur.Repo), pr); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, "/sites/forms?site="+strconv.Itoa(cur.Index), http.StatusSeeOther)
default:
http.NotFound(w, r)
}
}
+2
View File
@@ -185,6 +185,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
mux.HandleFunc("GET /sites/forms", s.sitesFormsPage)
mux.HandleFunc("POST /sites/forms/{action}", s.sitesFormsAction)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/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/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", "/settings/backups",
"/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/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", "/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 {
+92
View File
@@ -519,3 +519,95 @@ func TestSitesPublishing(t *testing.T) {
t.Errorf("page: %s", body)
}
}
func TestLeadForms(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
partial := "{{/*\n A lead form.\n*/}}\n<div class=\"lead\"><form class=\"lead-form\" action=\"{{ site.Params.leads.action }}\"></form></div>\n" +
"<script>\n (function () {\n var form = document.currentScript.previousElementSibling.querySelector('form');\n" +
" form.addEventListener('submit', function () { var data = new FormData(form);\n" +
" fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } }); });\n })();\n</script>\n"
clone := hugotest.Site(t, map[string]string{
"hugo.toml": "baseURL = 'https://site.example/'\ntitle = 'Site'\ndisableKinds = ['taxonomy', 'term', 'RSS', 'sitemap']\n\n[params.leads]\n action = \"\"\n email = \"info@site.example\"\n",
"layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ partial (printf "sections/%s.html" .type) . }}{{ end }}`,
"layouts/partials/sections/form.html": partial,
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ partial "render-sections.html" . }}{{ end }}`,
"content/churches.md": "---\ntitle: Churches\nsections:\n - type: form\n subject: Church\n---\n",
})
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/site":
fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
case r.URL.Path == "/api/v1/repos/Us/site/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":9,"state":"open","html_url":"https://gitea.example/pulls/9"}`)
case r.URL.Path == "/api/v1/repos/Us/site/pulls/9":
fmt.Fprint(w, `{"number":9,"state":"open"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
crm := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodOptions {
t.Errorf("the test sent a %s", r.Method)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
}))
defer crm.Close()
captureClient = crm.Client
defer func() { captureClient = sites.TestClient }()
capture := crm.URL + "/api/v1/LeadCapture/key123"
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://site.example", Repo: "Us/site"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String()
if !strings.Contains(body, "The forms open an email") || !strings.Contains(body, "Pages with a form: /churches/") ||
!strings.Contains(body, "First Name, Last Name, Email, Account Name, Phone, Description") {
t.Errorf("before: %s", body)
}
if body := postForm(h, "/sites/forms/save", url.Values{"site": {"0"}, "capture": {"https://crm.example/api/v1/Lead"}}).Body.String(); !strings.Contains(body, "isn&#39;t a Lead Capture address") {
t.Errorf("bad address: %s", body)
}
if body := postForm(h, "/sites/forms/save", url.Values{"site": {"0"}, "capture": {capture}}).Body.String(); !strings.Contains(body, "Saved and tested") {
t.Errorf("save: %s", body)
}
if rec := postForm(h, "/sites/forms/connect", url.Values{"site": {"0"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("connect: %d %s", rec.Code, rec.Body.String())
}
if len(opened) != 1 || opened[0]["head"] != "supermarket/lead-forms" || !strings.Contains(opened[0]["body"], "/churches/ loads the script and posts to the Lead Capture") {
t.Fatalf("pull request: %v", opened)
}
show := func(path string) string {
out, err := exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "show", "supermarket/lead-forms:"+path).CombinedOutput()
if err != nil {
t.Fatalf("%s: %s", path, out)
}
return string(out)
}
if cfg := show("hugo.toml"); !strings.Contains(cfg, " action = \""+capture+"\"\n email = \"info@site.example\"") {
t.Errorf("hugo.toml: %s", cfg)
}
if p := show("layouts/partials/sections/form.html"); !strings.Contains(p, "window.leadPost(form, data)") || !strings.Contains(p, "supermarket-leads.js") {
t.Errorf("partial: %s", p)
}
if js := show("static/js/supermarket-leads.js"); !strings.Contains(js, "window.leadPost = function") {
t.Errorf("script: %s", js)
}
if body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String(); !strings.Contains(body, "A pull request is open") || !strings.Contains(body, "https://gitea.example/pulls/9") {
t.Errorf("after: %s", body)
}
// Once merged and read again, the page says they're connected.
exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "update-ref", "refs/heads/main", "refs/heads/supermarket/lead-forms").Run()
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
if body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String(); !strings.Contains(body, "Connected: the forms on https://site.example send their answers to EspoCRM") {
t.Errorf("connected: %s", body)
}
}
+1
View File
@@ -65,6 +65,7 @@
<a href="/sites/pages" {{if hasPrefix $nav "sites/pages"}}aria-current="page"{{end}}>New pages</a>
<a href="/sites/previews" {{if eq $nav "sites/previews"}}aria-current="page"{{end}}>Previews</a>
<a href="/sites/publishing" {{if eq $nav "sites/publishing"}}aria-current="page"{{end}}>Publishing</a>
<a href="/sites/forms" {{if eq $nav "sites/forms"}}aria-current="page"{{end}}>Lead forms</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
+64
View File
@@ -0,0 +1,64 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Lead forms</h1></div>
<p class="lede">Your website's forms ("send me a cost comparison", "become a partner") send each answer to EspoCRM as a new Lead, using EspoCRM's own Lead Capture: Supermarket only runs on this computer, so the forms can't post to it. The Lead's description says which form, which page, and which campaign brought the visitor; Plausible counts the forms sent per buying signal.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your website and its Hugo repository under <a href="/settings/profile">Settings → Profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/sites/forms?site={{.Index}}" {{if and $d.Current (eq .Index $d.Current.Index)}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
{{with .Current}}{{$cur := .}}
{{if .Err}}<section class="card"><p class="warn-text">{{.URL}}: {{.Err}}.</p></section>{{else}}
{{if not $d.HasSynced}}
<section class="card empty"><p>Read {{.Repo}} under <a href="/sites?site={{.Index}}">Sections and pages</a> first.</p></section>
{{else}}{{with $d.State}}
<section class="card">
<h2>Now</h2>
{{if $d.Connected}}<p class="ok">Connected: the forms on {{$cur.URL}} send their answers to EspoCRM.</p>
{{else if .Action}}<p>The forms post to <code>{{.Action}}</code>{{if not .Patched}}, without Supermarket's mapping{{end}}.</p>
{{else}}<p>The forms open an email with the answers filled in: they don't post anywhere yet.</p>{{end}}
{{with .Pages}}<p class="small">Pages with a form: {{join . ", "}}</p>{{else}}<p class="small muted">No page has a form section yet. The page builder can add one where the site has the <code>form</code> section type.</p>{{end}}
{{if not .Supported}}<p class="warn-text">This site's form section doesn't post the way Supermarket knows, so it can't be connected automatically.</p>{{end}}
</section>
{{end}}{{end}}
<section class="card">
<h2>1. In EspoCRM</h2>
<ol>
<li>Open {{with $d.CRM}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">EspoCRM</a>{{else}}EspoCRM{{end}} as an administrator: <em>Administration → Lead Capture → Create Lead Capture</em>.</li>
<li>Name it after the site, tick <em>Is Active</em>, and under <em>Payload Fields</em> add: {{join $d.Payload ", "}}.</li>
<li>Optional: a <em>Campaign</em> (for EspoCRM's own campaign statistics), a <em>Target List</em>, a <em>Target Team</em>, and <em>Double Opt-in</em> if people should confirm by email.</li>
<li>Save, and copy the <em>API URL</em> it shows: <code>https://…/api/v1/LeadCapture/…</code>.</li>
</ol>
<p class="small muted">Your site must be allowed to post to the CRM: EspoCRM allows every site by default (<code>leadCaptureAllowOrigin</code> in its <code>data/config.php</code>). The test below checks it.</p>
</section>
<form method="post" action="/sites/forms/save" class="card">
<h2>2. The Lead Capture's address</h2>
<input type="hidden" name="site" value="{{.Index}}">
<label>API URL <input name="capture" value="{{$d.Capture}}" placeholder="{{or $d.CRM "https://espocrm.example.com"}}/api/v1/LeadCapture/…"></label>
<button type="submit" class="secondary" data-busy="Testing…">Save and test</button>
<p class="small muted">The test asks the CRM whether {{.URL}} may post to it, the way a browser would. Nothing is created.</p>
</form>
<form method="post" action="/sites/forms/connect" class="card">
<h2>3. Connect the forms</h2>
<input type="hidden" name="site" value="{{.Index}}">
<p>Opens a pull request on {{.Repo}} that sets the forms' address, adds a small script mapping their fields onto a Lead's (name, email, organization, phone; the rest, the page and the campaign go in the description), and has the form section post through it. Merging publishes it.</p>
{{with $d.PR}}<p>{{if eq .State "merged"}}<span class="ok">Merged.</span> Send a test form on the live site and look for the Lead in EspoCRM.{{else if eq .State "closed"}}The last pull request was closed without merging.{{else}}A pull request is open{{end}} <a href="{{.URL}}" target="_blank" rel="noopener noreferrer">{{.URL}} ↗</a> <span class="small muted">{{ago .At}}</span></p>{{end}}
<button type="submit" data-busy="Opening…" {{if or (not $d.Capture) (not $d.Gitea)}}disabled{{end}}>{{if $d.Connected}}Open it again{{else}}Open the pull request{{end}}</button>
</form>
{{end}}
{{end}}
{{end}}
<h2>Forms sent, by buying signal</h2>
{{if not .Plausible}}<p class="help">Counted from Plausible: save its key under <a href="/settings/tracking">Settings → Website &amp; sales</a>.</p>{{end}}
<p class="small muted">The forms tell Plausible when they're sent (a <code>{{.Goal}}</code> event). Add a <code>{{.Goal}}</code> goal (a custom event) in Plausible, and the daily import counts the ones from visits tagged with a signal as <em>interested</em> on its scorecard.</p>
{{with .Leads}}
<div class="table-wrap"><table class="compact">
<thead><tr><th>Day</th><th>Signal</th><th class="num">Forms</th><th>From</th></tr></thead>
<tbody>{{range .}}<tr><td>{{.At.Format "2 Jan 2006"}}</td><td>{{.Signal}}</td><td class="num">{{.Count}}</td><td class="small">{{.Note}}</td></tr>{{end}}</tbody>
</table></div>
{{else}}<p class="help">None counted yet.</p>{{end}}
{{end}}{{end}}