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
+31
View File
@@ -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 machine's mcp-token stays. Tried live both ways (the command line and the
page) by restoring a backup taken seconds before. 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
<crm>/api/v1/LeadCapture/<api key>` 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/<key>`) 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 ### Future enhancements
Not in any phase yet; picked up when the user asks. Not in any phase yet; picked up when the user asks.
+18
View File
@@ -620,6 +620,24 @@ Throughout, also notice:
- [ ] A page that went live, or was removed, shows up in SEO → Search - [ ] A page that went live, or was removed, shows up in SEO → Search
engines' IndexNow log (when IndexNow is set up). 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=<signal>`): 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 ## 9. Search
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect - [ ] Searching for an inventory entry, a fetched item, a post, a prospect
+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)
}
}
+89 -2
View File
@@ -136,7 +136,7 @@ func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites [
campaigns = append(campaigns, slug) campaigns = append(campaigns, slug)
} }
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat) yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
visits := 0 visits, leads, leadNote := 0, 0, ""
for _, site := range sites { for _, site := range sites {
var through string var through string
if _, err := d.GetJSON(plausibleStateKey(site), &through); err != nil { 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 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 { if err := d.PutJSON(plausibleStateKey(site), yesterday); err != nil {
return save(d, SourcePlausible, res, err) return save(d, SourcePlausible, res, err)
} }
} }
res.Through = yesterday 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) 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. // none is "" for Plausible's empty values.
func none(v string) string { func none(v string) string {
if v == "(none)" || v == "(not set)" { if v == "(none)" || v == "(not set)" {
@@ -269,3 +327,32 @@ func PageVisitors(ctx context.Context, c *plausible.Client, site string, paths [
} }
return out, nil 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 var q plausible.Query
json.NewDecoder(r.Body).Decode(&q) json.NewDecoder(r.Body).Decode(&q)
got = append(got, 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{ 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-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}}, 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 { if err != nil {
t.Fatal(err) 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) t.Fatalf("result: %+v", res)
} }
q := got[0] 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 { if q.SiteID != "federated.computer" || string(dr) != `["2026-10-23","2026-11-21"]` || len(q.Filters) != 1 {
t.Errorf("query: %+v %s", q, dr) 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) evs, _ := signals.RecentEvents(d, m365, 10)
if len(evs) != 2 || evs[0].Stage != signals.StageVisited || evs[0].Channel != "social" || evs[0].Count != 5 || var stages []string
evs[1].Channel != "email" || !strings.Contains(evs[1].Note, "outreach-3") { for _, e := range evs {
t.Errorf("events: %+v", 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. // 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) t.Errorf("same day: %d queries, %v", len(got), err)
} }
res, _ = ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now.AddDate(0, 0, 1)) 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 { if string(dr) != `["2026-11-22","2026-11-22"]` || res.Added != 0 {
t.Errorf("next day: %s %+v", dr, res) t.Errorf("next day: %s %+v", dr, res)
} }
@@ -198,3 +212,23 @@ func TestSyncStripe(t *testing.T) {
t.Error("a bad key worked") 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)
}
}
+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("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction) mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage) 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("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild) mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete) 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", "/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", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published", "/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"} { "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil) rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK { if rec.Code != http.StatusOK {
+92
View File
@@ -519,3 +519,95 @@ func TestSitesPublishing(t *testing.T) {
t.Errorf("page: %s", body) 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/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/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/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> </div>
{{end}} {{end}}
{{if eq .ID "prospects"}} {{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}}