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" "supermarket/internal/theme" ) // 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. It's // the theme's, so new sites have it from the start. var leadScript = theme.LeadScript() 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) || wc.Exists(theme.Dir+"/"+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)) } else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/layouts/partials/sections/form.html"); err == nil { // The theme's form already posts through the script. st.Patched = strings.Contains(string(raw), "window.leadPost") st.Supported = st.Patched } 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" var files []struct{ path, body string } if raw, err := os.ReadFile(wc.Dir + "/" + partial); err == nil { 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") } files = append(files, struct{ path, body string }{partial, patched}, struct{ path, body string }{LeadScriptPath, leadScript}) } else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/" + partial); err == nil && strings.Contains(string(raw), "window.leadPost") { // Supermarket's theme: its form and script are ready; only the address is needed. } else { return nil, errors.New("the site has no form section (layouts/partials/sections/form.html)") } 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 } files = append(files, struct{ path, body string }{cfg, SetLeadsAction(string(cfgRaw), capture)}) for _, f := range files { 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} }