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>
319 lines
13 KiB
Go
319 lines
13 KiB
Go
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} }
|