diff --git a/PLAN.md b/PLAN.md index 5f289fb..bc7784d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1424,6 +1424,37 @@ secrets.json too (the old one kept in the backups folder), while this machine's mcp-token stays. Tried live both ways (the command line and the page) by restoring a backup taken seconds before. +**Part 3 built (2026-11-22; no schema change).** EspoCRM's Lead Capture +(docs: docs.espocrm.com/administration/web-to-lead/) takes a JSON `POST +/api/v1/LeadCapture/` without a login, allows other sites +by default (`leadCaptureAllowOrigin`, "*"), and has one fixed Campaign per +Lead Capture: a per-submission campaign can't be passed. So the signal +travels in the Lead's description, and Plausible counts it. Sites → Lead +forms: +- shows how the site's forms post now (`[params.leads] action`), which + pages have a form, and whether this site's form section can be + connected; +- gives the EspoCRM steps (a Lead Capture whose Payload Fields are First + Name, Last Name, Email, Account Name, Phone, Description); +- saves its API URL (checked: https, `/api/v1/LeadCapture/`) and + tests it with a CORS preflight from the site's origin (nothing created); +- opens a pull request (`supermarket/lead-forms`): `[params.leads] + action` in `hugo.toml`, `static/js/supermarket-leads.js` defining + `window.leadPost(form, data)`, and the form partial loading it and + calling it in place of its own `fetch(form.action, …)` (patched only if + that call is there; matched on federated-website's). The script maps + name (split), email, organization/company, phone onto the Lead; the + form's name, other answers (by label), the page, the visit's UTM tags + and the referrer go in the description. Checked with a build: a page + with a form loads the script and posts to the Lead Capture. +- counts form leads: the forms already send Plausible a `Lead` event, so + the daily Plausible import also reads the `Lead` goal by the visit's + UTM tags and records them as *interested* on the signal's funnel (or + says to add the goal in Plausible). +Tested with Node running the script on a form's data. Not done for real: +creating the Lead Capture in EspoCRM, and the pull request on the real +site. + ### Future enhancements Not in any phase yet; picked up when the user asks. diff --git a/TEST.md b/TEST.md index ab42c3d..745eca6 100644 --- a/TEST.md +++ b/TEST.md @@ -620,6 +620,24 @@ Throughout, also notice: - [ ] A page that went live, or was removed, shows up in SEO → Search engines' IndexNow log (when IndexNow is set up). +### Lead forms + +- [ ] Sites → Lead forms says how the forms send today (an email), and + lists the pages with a form (/churches/, /partners/, /saas-savings/). +- [ ] Following the steps, create a Lead Capture in EspoCRM with the + payload fields listed; paste its API URL and *Save and test*: it + says the site may post to it, and no Lead appears in EspoCRM. +- [ ] A wrong address (not …/api/v1/LeadCapture/…) is refused. +- [ ] *Open the pull request*: on Gitea it changes `hugo.toml`, the form + section and adds `static/js/supermarket-leads.js`; preview it under + Sites → Previews. +- [ ] After merging, send a form on the live site from a link tagged with a + signal (`?utm_campaign=`): EspoCRM gets a Lead with the name + split, the email and organization, and the form, page and campaign + in its description. The page says "Connected". +- [ ] With a `Lead` goal added in Plausible, the next day's import counts + it as *interested* on the signal; Lead forms lists it. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/sites/leadforms.go b/internal/sites/leadforms.go new file mode 100644 index 0000000..449515a --- /dev/null +++ b/internal/sites/leadforms.go @@ -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 /api/v1/LeadCapture/ 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/ 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:///api/v1/LeadCapture/, 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 := `` + "\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} } diff --git a/internal/sites/leadforms_test.go b/internal/sites/leadforms_test.go new file mode 100644 index 0000000..a47c29e --- /dev/null +++ b/internal/sites/leadforms_test.go @@ -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 := . }} +
+ +` + +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\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, "\n\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" }}

{{ .Title }}

{{ 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'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) + } +} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index f5d82c8..82629e1 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -65,6 +65,7 @@ New pages Previews Publishing + Lead forms {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/sites-forms.html b/internal/web/templates/sites-forms.html new file mode 100644 index 0000000..c9aa7da --- /dev/null +++ b/internal/web/templates/sites-forms.html @@ -0,0 +1,64 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +

Lead forms

+

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.

+ +{{if not .Sites}} +

Add your website and its Hugo repository under Settings → Profile first.

+{{else}} +{{if gt (len .Sites) 1}}{{end}} +{{with .Current}}{{$cur := .}} +{{if .Err}}

{{.URL}}: {{.Err}}.

{{else}} + +{{if not $d.HasSynced}} +

Read {{.Repo}} under Sections and pages first.

+{{else}}{{with $d.State}} +
+

Now

+ {{if $d.Connected}}

Connected: the forms on {{$cur.URL}} send their answers to EspoCRM.

+ {{else if .Action}}

The forms post to {{.Action}}{{if not .Patched}}, without Supermarket's mapping{{end}}.

+ {{else}}

The forms open an email with the answers filled in: they don't post anywhere yet.

{{end}} + {{with .Pages}}

Pages with a form: {{join . ", "}}

{{else}}

No page has a form section yet. The page builder can add one where the site has the form section type.

{{end}} + {{if not .Supported}}

This site's form section doesn't post the way Supermarket knows, so it can't be connected automatically.

{{end}} +
+{{end}}{{end}} + +
+

1. In EspoCRM

+
    +
  1. Open {{with $d.CRM}}EspoCRM{{else}}EspoCRM{{end}} as an administrator: Administration → Lead Capture → Create Lead Capture.
  2. +
  3. Name it after the site, tick Is Active, and under Payload Fields add: {{join $d.Payload ", "}}.
  4. +
  5. Optional: a Campaign (for EspoCRM's own campaign statistics), a Target List, a Target Team, and Double Opt-in if people should confirm by email.
  6. +
  7. Save, and copy the API URL it shows: https://…/api/v1/LeadCapture/….
  8. +
+

Your site must be allowed to post to the CRM: EspoCRM allows every site by default (leadCaptureAllowOrigin in its data/config.php). The test below checks it.

+
+ +
+

2. The Lead Capture's address

+ + + +

The test asks the CRM whether {{.URL}} may post to it, the way a browser would. Nothing is created.

+
+ +
+

3. Connect the forms

+ +

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.

+ {{with $d.PR}}

{{if eq .State "merged"}}Merged. 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}} {{.URL}} ↗ {{ago .At}}

{{end}} + +
+{{end}} +{{end}} +{{end}} + +

Forms sent, by buying signal

+{{if not .Plausible}}

Counted from Plausible: save its key under Settings → Website & sales.

{{end}} +

The forms tell Plausible when they're sent (a {{.Goal}} event). Add a {{.Goal}} goal (a custom event) in Plausible, and the daily import counts the ones from visits tagged with a signal as interested on its scorecard.

+{{with .Leads}} +
+ + {{range .}}{{end}} +
DaySignalFormsFrom
{{.At.Format "2 Jan 2006"}}{{.Signal}}{{.Count}}{{.Note}}
+{{else}}

None counted yet.

{{end}} +{{end}}{{end}}