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>
200 lines
7.3 KiB
Go
200 lines
7.3 KiB
Go
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)
|
|
}
|
|
}
|