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
+318
View File
@@ -0,0 +1,318 @@
package sites
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/seo"
)
// Lead forms: a site's `form` sections post to EspoCRM's Lead Capture
// (Administration → Lead Capture), which takes a JSON POST without a login
// at <crm>/api/v1/LeadCapture/<api key> and allows posts from other sites
// (leadCaptureAllowOrigin, "*" by default). Supermarket is local-only, so
// it can't take the posts itself. The site's form fields are the site's
// own (name, email, organization…), so a small script maps them onto the
// Lead's fields; what doesn't map, the page, the form's name and the visit's
// UTM tags go in the description, so the CRM shows which signal brought it.
// LeadScriptPath is where the script goes in the site.
const LeadScriptPath = "static/js/supermarket-leads.js"
// LeadPayloadFields are the Lead fields the script sends: the Lead
// Capture's "Payload Fields" must list them all.
var LeadPayloadFields = []string{"First Name", "Last Name", "Email", "Account Name", "Phone", "Description"}
// leadScript defines window.leadPost(form, data), which the form's own
// script calls in place of its fetch: it returns the fetch's promise.
const leadScript = `/* Sends the site's lead forms to EspoCRM's Lead Capture. Written by
Supermarket: the form posts here instead of to [params.leads] action
directly, so its fields can be mapped onto a Lead's. */
(function () {
var mapped = { email: 'emailAddress', 'e-mail': 'emailAddress', phone: 'phoneNumber', tel: 'phoneNumber',
company: 'accountName', organization: 'accountName', organisation: 'accountName', church: 'accountName' };
function label(form, name) {
var el = form.querySelector('[name="' + name + '"]');
var l = el && el.id && form.querySelector('label[for="' + el.id + '"]');
return l ? l.childNodes[0].textContent.trim() : name;
}
window.leadPost = function (form, data) {
var lead = { firstName: null, lastName: null, emailAddress: null, accountName: null, phoneNumber: null };
var notes = [];
data.forEach(function (value, name) {
value = String(value).trim();
if (!value) return;
var key = name.toLowerCase();
if (key === 'name' || key === 'full_name' || key === 'fullname') {
var parts = value.split(/\s+/);
lead.lastName = parts.pop();
lead.firstName = parts.length ? parts.join(' ') : null;
} else if (key === 'first_name' || key === 'firstname') {
lead.firstName = value;
} else if (key === 'last_name' || key === 'lastname') {
lead.lastName = value;
} else if (mapped[key]) {
lead[mapped[key]] = value;
} else if (key === 'source') {
notes.unshift('Form: ' + value);
} else if (key === 'page') {
notes.push('Page: ' + location.origin + value);
} else {
notes.push(label(form, name) + ': ' + value);
}
});
if (!lead.lastName) lead.lastName = lead.emailAddress || 'Website visitor';
var q = new URLSearchParams(location.search);
['utm_campaign', 'utm_source', 'utm_medium', 'utm_content'].forEach(function (k) {
if (q.get(k)) notes.push(k + ': ' + q.get(k));
});
if (document.referrer) notes.push('Came from: ' + document.referrer);
lead.description = notes.join('\n') || null;
return fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(lead)
});
};
})();
`
var (
captureURL = regexp.MustCompile(`^https://[^/\s]+/(?:[^\s?#]*/)?api/v1/LeadCapture/[A-Za-z0-9]+$`)
// The form partial's own post, which leadPost takes over.
formFetch = regexp.MustCompile(`fetch\(form\.action,\s*\{(?:[^{}]|\{[^{}]*\})*\bbody:\s*data\b(?:[^{}]|\{[^{}]*\})*\}\s*\)`)
leadsTable = regexp.MustCompile(`(?m)^\[params\.leads\][ \t]*$`)
actionLine = regexp.MustCompile(`(?m)^([ \t]*)action[ \t]*=[ \t]*("[^"\n]*"|'[^'\n]*')(.*)$`)
nextTable = regexp.MustCompile(`(?m)^\[`)
leadsAction = regexp.MustCompile(`(?ms)^\[params\.leads\][ \t]*$.*?^[ \t]*action[ \t]*=[ \t]*["']([^"'\n]*)["']`)
)
// CheckCaptureURL checks a Lead Capture address's shape: https, and the
// /api/v1/LeadCapture/<key> path EspoCRM shows on the Lead Capture.
func CheckCaptureURL(u string) error {
if !captureURL.MatchString(strings.TrimSpace(u)) {
return errors.New("that isn't a Lead Capture address: it looks like https://<your CRM>/api/v1/LeadCapture/<API key>, as shown on the Lead Capture in EspoCRM")
}
return nil
}
// TestCapture asks EspoCRM, the way a browser on the site would before
// posting (a CORS preflight), whether the site may post to the Lead
// Capture. Nothing is created.
func TestCapture(ctx context.Context, client *http.Client, capture, siteURL string) error {
if err := CheckCaptureURL(capture); err != nil {
return err
}
origin := strings.TrimRight(siteURL, "/")
if u, err := url.Parse(siteURL); err == nil {
origin = u.Scheme + "://" + u.Host
}
req, err := http.NewRequestWithContext(ctx, http.MethodOptions, capture, nil)
if err != nil {
return err
}
req.Header.Set("Origin", origin)
req.Header.Set("Access-Control-Request-Method", "POST")
req.Header.Set("Access-Control-Request-Headers", "content-type")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("couldn't reach the CRM: %w", err)
}
res.Body.Close()
if res.StatusCode >= 400 {
return fmt.Errorf("the CRM answered %d: check the address, and that Lead Capture is on (EspoCRM 7 or later)", res.StatusCode)
}
allow := res.Header.Get("Access-Control-Allow-Origin")
if allow != "*" && !strings.EqualFold(allow, origin) {
if allow == "" {
return fmt.Errorf("the CRM doesn't let %s post to it: set leadCaptureAllowOrigin in EspoCRM's data/config.php to \"*\" or to %s", origin, origin)
}
return fmt.Errorf("the CRM only lets %s post to it, not %s: set leadCaptureAllowOrigin in EspoCRM's data/config.php", allow, origin)
}
return nil
}
// SetLeadsAction sets [params.leads] action in a TOML config, adding the
// table if there isn't one.
func SetLeadsAction(cfg, capture string) string {
val := strconv.Quote(capture)
loc := leadsTable.FindStringIndex(cfg)
if loc == nil {
return strings.TrimRight(cfg, "\n") + "\n\n# Where the site's lead forms post: EspoCRM's Lead Capture (set by Supermarket).\n[params.leads]\n action = " + val + "\n"
}
body := cfg[loc[1]:]
end := len(body)
if n := nextTable.FindStringIndex(body[1:]); n != nil {
end = n[0] + 1
}
section := body[:end]
if m := actionLine.FindStringSubmatchIndex(section); m != nil {
indent := section[m[2]:m[3]]
section = section[:m[0]] + indent + "action = " + val + section[m[6]:m[7]] + section[m[1]:]
} else {
section = "\n action = " + val + section
}
return cfg[:loc[1]] + section + body[end:]
}
// LeadsAction reads [params.leads] action from a TOML config.
func LeadsAction(cfg string) string {
if m := leadsAction.FindStringSubmatch(cfg); m != nil {
return m[1]
}
return ""
}
// PatchFormPartial makes the form partial post through leadPost: the
// script is loaded at its top, and its fetch goes through leadPost when
// it's there. ok is false when the partial doesn't post the way
// Supermarket knows (it's left alone then).
func PatchFormPartial(src string) (out string, ok bool) {
if strings.Contains(src, "window.leadPost") {
return src, true // already done
}
call := formFetch.FindString(src)
if call == "" {
return src, false
}
src = strings.Replace(src, call, "(window.leadPost ? window.leadPost(form, data) : "+call+")", 1)
tag := `<script src="{{ "js/supermarket-leads.js" | relURL }}"></script>` + "\n"
// After the opening comment, if there is one, so the comment stays first.
if strings.HasPrefix(strings.TrimSpace(src), "{{/*") {
if i := strings.Index(src, "*/}}"); i >= 0 {
j := i + len("*/}}")
return src[:j] + "\n" + tag + strings.TrimLeft(src[j:], "\n"), true
}
}
return tag + src, true
}
// FormState is how a site's lead forms are set up, read from its working
// copy.
type FormState struct {
Action string // [params.leads] action: where the forms post now
Script bool // the mapping script is in the site
Patched bool // the form partial posts through it
Supported bool // the form partial posts in the way Supermarket knows
Config string // the config file
Pages []string // pages with a form section
}
// ReadForms reads a site's lead form set-up.
func ReadForms(wc *hugorepo.Repo, cat *Catalog) FormState {
st := FormState{Config: wc.ConfigFile()}
if st.Config != "" {
if raw, err := os.ReadFile(wc.Dir + "/" + st.Config); err == nil {
st.Action = LeadsAction(string(raw))
}
}
st.Script = wc.Exists(LeadScriptPath)
if raw, err := os.ReadFile(wc.Dir + "/layouts/partials/sections/form.html"); err == nil {
st.Patched = strings.Contains(string(raw), "window.leadPost")
_, st.Supported = PatchFormPartial(string(raw))
}
if cat != nil {
if t := cat.Type("form"); t != nil {
st.Pages = t.Pages
}
}
return st
}
// Connected says whether the forms post to this Lead Capture.
func (st FormState) Connected(capture string) bool {
return capture != "" && st.Action == capture && st.Script && st.Patched
}
// ConnectForms opens a pull request that points the site's lead forms at
// the Lead Capture: the address in the config, the mapping script, and the
// form partial posting through it. It's checked with a build: a page with
// a form must load the script.
func ConnectForms(ctx context.Context, ap *seo.Applier, capture string, formPage string) (*gitea.Pull, error) {
if err := CheckCaptureURL(capture); err != nil {
return nil, err
}
wc, full, published, err := ap.WorkingCopy(ctx)
if err != nil {
return nil, err
}
defer wc.Release()
cfg := wc.ConfigFile()
if !strings.HasSuffix(cfg, ".toml") {
return nil, errors.New("the site's settings aren't in a TOML file (hugo.toml), which is all Supermarket can change for now")
}
partial := "layouts/partials/sections/form.html"
raw, err := os.ReadFile(wc.Dir + "/" + partial)
if err != nil {
return nil, errors.New("the site has no form section (layouts/partials/sections/form.html)")
}
patched, ok := PatchFormPartial(string(raw))
if !ok {
return nil, errors.New("the site's form section doesn't post the way Supermarket knows (a fetch of form.action with the form's data), so it can't be connected automatically")
}
branch := "supermarket/lead-forms"
if err := wc.NewBranch(ctx, branch); err != nil {
return nil, err
}
cfgRaw, err := os.ReadFile(wc.Dir + "/" + cfg)
if err != nil {
return nil, err
}
for _, f := range []struct{ path, body string }{
{cfg, SetLeadsAction(string(cfgRaw), capture)}, {partial, patched}, {LeadScriptPath, leadScript},
} {
if err := wc.WriteFile(f.path, f.body); err != nil {
return nil, err
}
}
note := "Not checked with a build: there's no Hugo in Supermarket's image."
if hugorepo.HugoVersion(ctx) != "" {
out, err := wc.Build(ctx)
if err != nil {
return nil, fmt.Errorf("with the forms connected, %w", err)
}
defer os.RemoveAll(out)
note = "Checked with a build: the site builds."
if formPage != "" {
html, err := hugorepo.BuiltFile(out, strings.Trim(formPage, "/")+"/index.html")
if err != nil || !strings.Contains(html, "supermarket-leads.js") || !strings.Contains(html, capture) {
return nil, fmt.Errorf("the site builds, but %s doesn't load the script or post to the Lead Capture", formPage)
}
note = "Checked with a build: the site builds, and " + formPage + " loads the script and posts to the Lead Capture."
}
}
subject := "Sites: send the lead forms to EspoCRM"
if err := wc.CommitAndPush(ctx, branch, subject); err != nil {
return nil, err
}
body := fmt.Sprintf(`Points the site's lead forms at EspoCRM's Lead Capture, so each one creates a Lead.
- `+"`%s`"+`: `+"`[params.leads] action`"+` is the Lead Capture's address.
- `+"`%s`"+`: maps the form's fields onto the Lead's (name → first and last name, email, organization → account name, phone); everything else, the form's name, the page and the visit's UTM tags go in the description, so the CRM shows which campaign brought it.
- `+"`%s`"+`: loads the script and posts through it.
The Lead Capture's Payload Fields must include: %s.
%s
Merging publishes it: test a form on the live site afterwards, and look for the Lead in EspoCRM.`,
cfg, LeadScriptPath, partial, strings.Join(LeadPayloadFields, ", "), note)
pull, err := ap.Gitea.OpenPull(ctx, full, branch, published, subject, body)
if err != nil {
return nil, err
}
return pull, nil
}
// TestClient is the HTTP client TestCapture uses in the app.
func TestClient() *http.Client { return &http.Client{Timeout: 20 * time.Second} }
+199
View File
@@ -0,0 +1,199 @@
package sites
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestCheckCaptureURL(t *testing.T) {
for u, ok := range map[string]bool{
"https://espocrm.federated.computer/api/v1/LeadCapture/a1b2c3": true,
"https://crm.example.com/espo/api/v1/LeadCapture/ABC123": true,
"http://espocrm.example.com/api/v1/LeadCapture/abc": false,
"https://espocrm.example.com/api/v1/Lead": false,
"https://espocrm.example.com/api/v1/LeadCapture/": false,
"https://espocrm.example.com/api/v1/LeadCapture/abc?x=1": false,
"javascript:alert(1)": false,
} {
if err := CheckCaptureURL(u); (err == nil) != ok {
t.Errorf("%s: %v", u, err)
}
}
}
func TestSetLeadsAction(t *testing.T) {
const cap = "https://crm.example/api/v1/LeadCapture/k1"
fed := "title = 'Site'\n\n# where forms go\n[params.leads]\n action = \"\" # empty opens an email\n email = \"info@example.com\"\n\n[params.order]\n api = \"\"\n"
got := SetLeadsAction(fed, cap)
want := "title = 'Site'\n\n# where forms go\n[params.leads]\n action = \"https://crm.example/api/v1/LeadCapture/k1\" # empty opens an email\n email = \"info@example.com\"\n\n[params.order]\n api = \"\"\n"
if got != want {
t.Errorf("existing:\n%s\nwant\n%s", got, want)
}
if LeadsAction(got) != cap || LeadsAction(fed) != "" {
t.Errorf("read back: %q", LeadsAction(got))
}
// No action line in the table: added; no table: appended.
got = SetLeadsAction("[params.leads]\n email = \"x@y\"\n[other]\n action = \"keep\"\n", cap)
if !strings.HasPrefix(got, "[params.leads]\n action = \""+cap+"\"\n email") || !strings.Contains(got, "[other]\n action = \"keep\"") {
t.Errorf("no action line:\n%s", got)
}
got = SetLeadsAction("title = 'x'\n", cap)
if !strings.HasSuffix(got, "[params.leads]\n action = \""+cap+"\"\n") || LeadsAction(got) != cap {
t.Errorf("no table:\n%s", got)
}
}
const formPartial = `{{/*
A lead form.
*/}}
{{ $s := . }}
<div class="lead"><form class="lead-form" action="{{ site.Params.leads.action }}"></form></div>
<script>
(function () {
var form = document.currentScript.previousElementSibling.querySelector('form');
form.addEventListener('submit', function (e) {
var data = new FormData(form);
fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } })
.then(function (r) { if (!r.ok) throw new Error(r.status); });
});
})();
</script>
`
func TestPatchFormPartial(t *testing.T) {
out, ok := PatchFormPartial(formPartial)
if !ok {
t.Fatal("not patched")
}
if !strings.HasPrefix(out, "{{/*\n A lead form.\n*/}}\n<script src=\"{{ \"js/supermarket-leads.js\" | relURL }}\"></script>\n{{ $s := . }}") {
t.Errorf("script tag:\n%s", out)
}
if !strings.Contains(out, "(window.leadPost ? window.leadPost(form, data) : fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } }))") {
t.Errorf("fetch:\n%s", out)
}
// The form's script still follows the form's div directly.
if !strings.Contains(out, "</div>\n<script>\n (function") {
t.Error("something came between the form and its script")
}
again, ok := PatchFormPartial(out)
if !ok || again != out {
t.Error("patching twice changed it")
}
if _, ok := PatchFormPartial(`<form action="/x"></form>`); ok {
t.Error("an unknown form was patched")
}
if out, _ := PatchFormPartial(strings.TrimPrefix(formPartial, "{{/*\n A lead form.\n*/}}\n")); !strings.HasPrefix(out, "<script src=") {
t.Errorf("no comment: %s", out[:60])
}
}
func TestTestCapture(t *testing.T) {
allow := "*"
status := 200
var got *http.Request
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r
if allow != "" {
w.Header().Set("Access-Control-Allow-Origin", allow)
}
w.WriteHeader(status)
}))
defer srv.Close()
capture := srv.URL + "/api/v1/LeadCapture/abc123"
site := "https://www.site.example/"
if err := TestCapture(context.Background(), srv.Client(), capture, site); err != nil {
t.Fatal(err)
}
if got.Method != http.MethodOptions || got.Header.Get("Origin") != "https://www.site.example" || got.Header.Get("Access-Control-Request-Method") != "POST" {
t.Errorf("request: %s %v", got.Method, got.Header)
}
allow = "https://www.site.example"
if err := TestCapture(context.Background(), srv.Client(), capture, site); err != nil {
t.Errorf("exact origin: %v", err)
}
for _, c := range []struct {
allow string
status int
want string
}{{"https://other.example", 200, "only lets https://other.example"}, {"", 200, "doesn't let https://www.site.example"}, {"*", 404, "answered 404"}} {
allow, status = c.allow, c.status
if err := TestCapture(context.Background(), srv.Client(), capture, site); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%+v: %v", c, err)
}
}
}
// TestLeadScript runs the mapping script in Node, with a form's data.
func TestLeadScript(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("no node")
}
harness := `
globalThis.window = globalThis;
globalThis.location = { search: '?utm_campaign=churches&utm_source=email&utm_medium=outreach', origin: 'https://site.example' };
globalThis.document = { referrer: 'https://mail.example/' };
let sent;
globalThis.fetch = (url, opts) => { sent = { url, opts }; return Promise.resolve({ ok: true }); };
const labels = { users: 'How many people?' };
const form = {
action: 'https://crm.example/api/v1/LeadCapture/k1',
querySelector(sel) {
let m = sel.match(/name="([^"]+)"/);
if (m) return { id: 'lead-' + m[1] };
m = sel.match(/for="lead-([^"]+)"/);
if (m && labels[m[1]]) return { childNodes: [{ textContent: labels[m[1]] + ' ' }] };
return null;
}
};
` + leadScript + `
const data = new FormData();
data.append('source', 'Church cost comparison');
data.append('name', 'Mary Ann Smith');
data.append('email', 'mary@church.example');
data.append('organization', 'First Church');
data.append('users', '40');
data.append('notes', '');
data.append('page', '/churches/');
window.leadPost(form, data).then(r => {
console.log(JSON.stringify({ ok: r.ok, url: sent.url, method: sent.opts.method, type: sent.opts.headers['Content-Type'], body: JSON.parse(sent.opts.body) }));
});
`
path := filepath.Join(t.TempDir(), "harness.js")
os.WriteFile(path, []byte(harness), 0o600)
out, err := exec.Command(node, path).CombinedOutput()
if err != nil {
t.Fatalf("node: %v %s", err, out)
}
var got struct {
OK bool
URL string
Method string
Type string
Body map[string]any
}
if err := json.Unmarshal(out, &got); err != nil {
t.Fatalf("%v: %s", err, out)
}
if !got.OK || got.URL != "https://crm.example/api/v1/LeadCapture/k1" || got.Method != "POST" || got.Type != "application/json" {
t.Errorf("request: %+v", got)
}
want := map[string]any{"firstName": "Mary Ann", "lastName": "Smith", "emailAddress": "mary@church.example",
"accountName": "First Church", "phoneNumber": nil,
"description": "Form: Church cost comparison\nHow many people?: 40\nPage: https://site.example/churches/\nutm_campaign: churches\nutm_source: email\nutm_medium: outreach\nCame from: https://mail.example/"}
for k, v := range want {
if got.Body[k] != v {
t.Errorf("%s: %#v, want %#v", k, got.Body[k], v)
}
}
if len(got.Body) != len(want) {
t.Errorf("fields sent: %v", got.Body)
}
}