diff --git a/TEST.md b/TEST.md index c04a064..24592a9 100644 --- a/TEST.md +++ b/TEST.md @@ -297,6 +297,23 @@ Throughout, also notice: - [ ] With more queued than the daily limit, the rest wait for the next day. - [ ] *Draft* for several accepted people writes up to 5 drafts. +### Mailing lists (Listmonk) + +- [ ] Settings → Email → *Mailing lists*: Listmonk's address is your + Core's; with an API user and its token saved, *Test* lists your + lists, with their opt-in. +- [ ] On a person in Review, *Add to a mailing list* to a double opt-in + list: they appear in Listmonk as unconfirmed, Listmonk emails them to + confirm, and the card says "asked to confirm". +- [ ] A single opt-in list refuses them unless *They agreed to receive it* + is ticked; an address on the suppression list is refused. +- [ ] In Listmonk, the subscriber carries their company, title, signal and + source "supermarket". +- [ ] Unsubscribe a test address from a list in Listmonk (or blocklist it), + then *Sync unsubscribes now*: it's on the suppression list with the + reason, the person's card no longer shows that list, and an address + already on the list keeps your reason. It also runs every hour. + ### CRM queue (EspoCRM through Hermes) - [x] The page lists queued, done and failed actions, and when Hermes last diff --git a/internal/api/listmonk/client.go b/internal/api/listmonk/client.go new file mode 100644 index 0000000..a1762d9 --- /dev/null +++ b/internal/api/listmonk/client.go @@ -0,0 +1,230 @@ +// Package listmonk adds people to mailing lists on a Listmonk server +// (https://listmonk.app/docs/apis/apis/), such as the one on a Federated +// Core. It reads the lists and adds subscribers; it never sends campaigns. +package listmonk + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// ErrUnauthorized means the API user or its token was refused. +var ErrUnauthorized = errors.New("Listmonk refused the API user or its token") + +// Client calls one Listmonk as one API user. +type Client struct { + base, user, token string + http *http.Client +} + +// New takes Listmonk's address and an API user with its token (Listmonk: +// Admin → Users → API user). +func New(base, user, token string) *Client { + return &Client{base: strings.TrimRight(strings.TrimSpace(base), "/"), user: strings.TrimSpace(user), token: strings.TrimSpace(token), + http: &http.Client{Timeout: 30 * time.Second}} +} + +func (c *Client) do(ctx context.Context, method, path string, in, out any) (int, error) { + var body io.Reader + if in != nil { + raw, err := json.Marshal(in) + if err != nil { + return 0, err + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, c.base+path, body) + if err != nil { + return 0, err + } + req.Header.Set("Authorization", "token "+c.user+":"+c.token) + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + res, err := c.http.Do(req) + if err != nil { + return 0, err + } + defer res.Body.Close() + raw, err := io.ReadAll(io.LimitReader(res.Body, 8<<20)) + if err != nil { + return res.StatusCode, err + } + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + return res.StatusCode, ErrUnauthorized + } + if res.StatusCode >= 300 { + var e struct { + Message string `json:"message"` + } + if json.Unmarshal(raw, &e) == nil && e.Message != "" { + return res.StatusCode, fmt.Errorf("Listmonk: %s", e.Message) + } + return res.StatusCode, fmt.Errorf("Listmonk: HTTP %d", res.StatusCode) + } + if out != nil { + var env struct { + Data json.RawMessage `json:"data"` + } + if err := json.Unmarshal(raw, &env); err != nil { + return res.StatusCode, fmt.Errorf("Listmonk: %w", err) + } + return res.StatusCode, json.Unmarshal(env.Data, out) + } + return res.StatusCode, nil +} + +// List is a mailing list. +type List struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` // public, private + Optin string `json:"optin"` // single, double + Subscribers int `json:"subscriber_count"` +} + +// Double says whether people must confirm before they get the list's mail. +func (l List) Double() bool { return l.Optin == "double" } + +// Lists are the server's mailing lists. +func (c *Client) Lists(ctx context.Context) ([]List, error) { + var out struct { + Results []List `json:"results"` + } + _, err := c.do(ctx, http.MethodGet, "/api/lists?per_page=all", nil, &out) + return out.Results, err +} + +// Subscriber is someone to add. +type Subscriber struct { + Email string + Name string + Attribs map[string]any // kept with them in Listmonk +} + +// Subscribe adds someone to a list. confirmed says they've already agreed +// to receive it; otherwise a double opt-in list asks them by email first. +// It returns the subscriber's ID, and whether they were already in +// Listmonk (on any list). +func (c *Client) Subscribe(ctx context.Context, s Subscriber, list List, confirmed bool) (id int64, existed bool, err error) { + var created struct { + ID int64 `json:"id"` + } + status, err := c.do(ctx, http.MethodPost, "/api/subscribers", map[string]any{ + "email": s.Email, "name": s.Name, "status": "enabled", "lists": []int64{list.ID}, + "attribs": s.Attribs, "preconfirm_subscriptions": confirmed, + }, &created) + if err == nil { + return created.ID, false, nil + } + if status != http.StatusConflict { + return 0, false, err + } + // Already a subscriber: add them to this list too. + id, err = c.find(ctx, s.Email) + if err != nil { + return 0, true, err + } + subStatus := "unconfirmed" + if confirmed || !list.Double() { + subStatus = "confirmed" + } + if _, err := c.do(ctx, http.MethodPut, "/api/subscribers/lists", map[string]any{ + "ids": []int64{id}, "action": "add", "target_list_ids": []int64{list.ID}, "status": subStatus, + }, nil); err != nil { + return id, true, err + } + if subStatus == "unconfirmed" { + // Ask them to confirm, as a new subscriber would be asked. + if _, err := c.do(ctx, http.MethodPost, "/api/subscribers/"+strconv.FormatInt(id, 10)+"/optin", nil, nil); err != nil { + return id, true, err + } + } + return id, true, nil +} + +// find is a subscriber's ID by email. +func (c *Client) find(ctx context.Context, email string) (int64, error) { + q := url.Values{"query": {"subscribers.email = '" + strings.ReplaceAll(strings.ToLower(email), "'", "''") + "'"}, "per_page": {"1"}} + var out struct { + Results []struct { + ID int64 `json:"id"` + } `json:"results"` + } + if _, err := c.do(ctx, http.MethodGet, "/api/subscribers?"+q.Encode(), nil, &out); err != nil { + return 0, err + } + if len(out.Results) == 0 { + return 0, errors.New("Listmonk says the address exists, but couldn't find it") + } + return out.Results[0].ID, nil +} + +// OptedOut is someone who doesn't want mail: blocklisted (from all lists) +// or unsubscribed from one list. +type OptedOut struct { + Email string + List string // the list they left; "" when blocklisted +} + +// pageSize is how many subscribers one request reads. +const pageSize = 1000 + +// subscribers reads every page of a subscriber query. +func (c *Client) subscribers(ctx context.Context, q url.Values) ([]string, error) { + var out []string + for page := 1; page < 1000; page++ { + q.Set("per_page", strconv.Itoa(pageSize)) + q.Set("page", strconv.Itoa(page)) + var res struct { + Results []struct { + Email string `json:"email"` + } `json:"results"` + Total int `json:"total"` + } + if _, err := c.do(ctx, http.MethodGet, "/api/subscribers?"+q.Encode(), nil, &res); err != nil { + return out, err + } + for _, r := range res.Results { + if r.Email != "" { + out = append(out, strings.ToLower(r.Email)) + } + } + if len(res.Results) < pageSize || len(out) >= res.Total { + return out, nil + } + } + return out, nil +} + +// OptedOut lists everyone blocklisted, and everyone unsubscribed from any +// of the lists. +func (c *Client) OptedOut(ctx context.Context, lists []List) ([]OptedOut, error) { + var out []OptedOut + blocked, err := c.subscribers(ctx, url.Values{"query": {"subscribers.status = 'blocklisted'"}}) + if err != nil { + return nil, err + } + for _, e := range blocked { + out = append(out, OptedOut{Email: e}) + } + for _, l := range lists { + left, err := c.subscribers(ctx, url.Values{"list_id": {strconv.FormatInt(l.ID, 10)}, "subscription_status": {"unsubscribed"}}) + if err != nil { + return out, fmt.Errorf("%s: %w", l.Name, err) + } + for _, e := range left { + out = append(out, OptedOut{Email: e, List: l.Name}) + } + } + return out, nil +} diff --git a/internal/api/listmonk/client_test.go b/internal/api/listmonk/client_test.go new file mode 100644 index 0000000..8c1200b --- /dev/null +++ b/internal/api/listmonk/client_test.go @@ -0,0 +1,89 @@ +package listmonk + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestSubscribe(t *testing.T) { + var calls []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "token sm:tok" { + w.WriteHeader(http.StatusForbidden) + return + } + calls = append(calls, r.Method+" "+r.URL.Path) + var body map[string]any + json.NewDecoder(r.Body).Decode(&body) + switch { + case r.URL.Path == "/api/lists": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{ + {"id": 3, "name": "Newsletter", "type": "public", "optin": "double", "subscriber_count": 40}}}}) + case r.URL.Path == "/api/subscribers" && r.Method == http.MethodPost: + if body["email"] == "old@x.example" { + w.WriteHeader(http.StatusConflict) + json.NewEncoder(w).Encode(map[string]any{"message": "E-mail already exists."}) + return + } + if body["preconfirm_subscriptions"] != false || body["name"] != "Ann Lee" { + t.Errorf("create: %v", body) + } + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"id": 11}}) + case r.URL.Path == "/api/subscribers" && r.Method == http.MethodGet: + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{{"id": 12}}}}) + case r.URL.Path == "/api/subscribers/lists": + if body["status"] != "unconfirmed" || body["action"] != "add" { + t.Errorf("lists: %v", body) + } + json.NewEncoder(w).Encode(map[string]any{"data": true}) + case r.URL.Path == "/api/subscribers/12/optin": + json.NewEncoder(w).Encode(map[string]any{"data": true}) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + c := New(srv.URL+"/", "sm", "tok") + lists, err := c.Lists(context.Background()) + if err != nil || len(lists) != 1 || !lists[0].Double() { + t.Fatal(lists, err) + } + id, existed, err := c.Subscribe(context.Background(), Subscriber{Email: "ann@x.example", Name: "Ann Lee"}, lists[0], false) + if err != nil || id != 11 || existed { + t.Errorf("new: %d %v %v", id, existed, err) + } + calls = nil + id, existed, err = c.Subscribe(context.Background(), Subscriber{Email: "old@x.example", Name: "Old"}, lists[0], false) + if err != nil || id != 12 || !existed || len(calls) != 4 || calls[3] != "POST /api/subscribers/12/optin" { + t.Errorf("existing: %d %v %v %v", id, existed, err, calls) + } + if _, err := New(srv.URL, "sm", "bad").Lists(context.Background()); err != ErrUnauthorized { + t.Errorf("bad token: %v", err) + } +} + +func TestOptedOut(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + var emails []string + switch { + case q.Get("query") == "subscribers.status = 'blocklisted'": + emails = []string{"Spam@X.example"} + case q.Get("list_id") == "3" && q.Get("subscription_status") == "unsubscribed": + emails = []string{"ann@lee.example"} + } + var res []map[string]any + for _, e := range emails { + res = append(res, map[string]any{"email": e}) + } + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": res, "total": len(res)}}) + })) + defer srv.Close() + out, err := New(srv.URL, "sm", "tok").OptedOut(context.Background(), []List{{ID: 3, Name: "Newsletter"}, {ID: 4, Name: "Quiet"}}) + if err != nil || len(out) != 2 || out[0] != (OptedOut{Email: "spam@x.example"}) || out[1] != (OptedOut{Email: "ann@lee.example", List: "Newsletter"}) { + t.Errorf("opted out: %+v %v", out, err) + } +} diff --git a/internal/db/db.go b/internal/db/db.go index 215772d..d452173 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -671,6 +671,17 @@ CREATE TABLE link_opportunities ( updated_at TEXT NOT NULL, UNIQUE (site, page_url) ); +`, + // 29: the mailing lists (Listmonk) a prospect was added to. + ` +CREATE TABLE list_members ( + contact_id INTEGER NOT NULL REFERENCES prospect_contacts (id) ON DELETE CASCADE, + list_id INTEGER NOT NULL, -- Listmonk's + list_name TEXT NOT NULL, + confirmed INTEGER NOT NULL DEFAULT 0, -- 1: added as agreed; 0: Listmonk asked them to confirm + at TEXT NOT NULL, + PRIMARY KEY (contact_id, list_id) +); `, } diff --git a/internal/prospects/lists.go b/internal/prospects/lists.go new file mode 100644 index 0000000..1e4a59e --- /dev/null +++ b/internal/prospects/lists.go @@ -0,0 +1,50 @@ +package prospects + +import ( + "time" + + "supermarket/internal/db" +) + +// ListMember is a mailing list a person was added to. +type ListMember struct { + ListID int64 + List string + Confirmed bool // added as having agreed; else the list asked them to confirm + At time.Time +} + +// AddedToList records that a person was added to a mailing list. +func AddedToList(d *db.DB, contactID, listID int64, list string, confirmed bool, now time.Time) error { + c := 0 + if confirmed { + c = 1 + } + _, err := d.Exec(`INSERT INTO list_members (contact_id, list_id, list_name, confirmed, at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT (contact_id, list_id) DO UPDATE SET list_name = excluded.list_name, confirmed = max(confirmed, excluded.confirmed)`, + contactID, listID, list, c, now.UTC().Format(time.RFC3339)) + return err +} + +// ListsOf are the mailing lists each person was added to, by contact ID. +func ListsOf(d *db.DB) (map[int64][]ListMember, error) { + rows, err := d.Query(`SELECT contact_id, list_id, list_name, confirmed, at FROM list_members ORDER BY at`) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[int64][]ListMember{} + for rows.Next() { + var id int64 + var m ListMember + var at string + var c int + if err := rows.Scan(&id, &m.ListID, &m.List, &c, &at); err != nil { + return nil, err + } + m.Confirmed = c == 1 + m.At, _ = time.Parse(time.RFC3339, at) + out[id] = append(out[id], m) + } + return out, rows.Err() +} diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index 25af964..c30ef21 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -43,6 +43,8 @@ const ( MailPassword = "mail.password" // the outreach mailbox on the Core + ListmonkToken = "listmonk.token" // an API user's token, to add people to mailing lists + GoogleClientID = "google.client_id" GoogleClientSecret = "google.client_secret" GoogleRefreshToken = "google.refresh_token" // Search Console, read-only diff --git a/internal/web/listmonk.go b/internal/web/listmonk.go new file mode 100644 index 0000000..aef9904 --- /dev/null +++ b/internal/web/listmonk.go @@ -0,0 +1,298 @@ +package web + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "supermarket/internal/api/listmonk" + "supermarket/internal/prospects" + "supermarket/internal/secrets" + "supermarket/internal/signals" +) + +// Mailing lists: adding a prospect to a list on Listmonk (Settings → +// Email → Mailing lists, and Add to a mailing list on a person in Review). + +type listmonkSettings struct { + URL string `json:"url"` + User string `json:"user"` +} + +const ( + listmonkKey = "listmonk:settings" + listmonkListsKey = "listmonk:lists" // the lists, as last read + listsFresh = time.Hour +) + +var listmonkToken = secretField{"listmonk", secrets.ListmonkToken, "API token", + "In Listmonk: Admin → Users → New, of the API type; it shows the token once.", ""} + +// listmonkConfig is the saved settings, with Listmonk's usual address on +// the Core when none is saved. +func (s *Server) listmonkConfig() listmonkSettings { + var set listmonkSettings + _, _ = s.DB.GetJSON(listmonkKey, &set) + if set.URL == "" && s.Core != nil { + set.URL = "https://listmonk." + s.Core.Domain + } + return set +} + +// listmonk is the client, or nil until a user and token are saved. +func (s *Server) listmonk() *listmonk.Client { + set := s.listmonkConfig() + tok := s.Secrets.Get(secrets.ListmonkToken) + if set.URL == "" || set.User == "" || tok == "" { + return nil + } + return listmonk.New(set.URL, set.User, tok) +} + +type cachedLists struct { + At time.Time `json:"at"` + Lists []listmonk.List `json:"lists"` +} + +// mailingLists are Listmonk's lists, read at most once an hour (or now, +// with fresh). +func (s *Server) mailingLists(ctx context.Context, fresh bool) ([]listmonk.List, error) { + c := s.listmonk() + if c == nil { + return nil, nil + } + var cached cachedLists + if ok, _ := s.DB.GetJSON(listmonkListsKey, &cached); ok && !fresh && time.Since(cached.At) < listsFresh { + return cached.Lists, nil + } + lists, err := c.Lists(ctx) + if err != nil { + return cached.Lists, err + } + _ = s.DB.PutJSON(listmonkListsKey, cachedLists{At: time.Now(), Lists: lists}) + return lists, nil +} + +// listmonkSave saves the address, the API user and its token. +func (s *Server) listmonkSave(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + set := listmonkSettings{URL: strings.TrimRight(strings.TrimSpace(r.PostFormValue("listmonk_url")), "/"), User: strings.TrimSpace(r.PostFormValue("listmonk_user"))} + if set.URL != "" && !strings.HasPrefix(set.URL, "https://") && !strings.HasPrefix(set.URL, "http://") { + set, _ := s.outreachSettings() + s.renderEmail(w, r, set, "Listmonk's address starts with https://") + return + } + if err := s.DB.PutJSON(listmonkKey, set); err != nil { + s.serverError(w, err) + return + } + if err := s.saveSecrets(r, []secretField{listmonkToken}); err != nil { + s.serverError(w, err) + return + } + _, _ = s.DB.Exec(`DELETE FROM settings WHERE key = ?`, listmonkListsKey) // read them again + redirect(w, r, "/settings/email#lists", "saved") +} + +// listmonkTest reads the lists: the user and token work if it can. +func (s *Server) listmonkTest(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + data := map[string]any{} + if s.listmonk() == nil { + data["Error"] = "Save the API user and its token first." + } else if lists, err := s.mailingLists(ctx, true); err != nil { + data["Error"] = err.Error() + } else { + data["Lists"] = lists + } + s.fragment(w, "email", "listmonk-test", data) +} + +// addToList adds a person to a mailing list. +func (s *Server) addToList(r *http.Request, id int64) error { + c := s.listmonk() + if c == nil { + return errors.New("set up Listmonk under Settings → Email first") + } + p, err := prospects.GetContact(s.DB, id) + if err != nil { + return err + } + if p.Email == "" { + return errors.New(p.Name() + " has no email address") + } + domain := "" + if _, after, ok := strings.Cut(p.Email, "@"); ok { + domain = after + } + if sup, err := prospects.IsSuppressed(s.DB, p.Email, domain); err != nil { + return err + } else if sup { + return errors.New(p.Email + " is on your suppression list, so it can't go on a mailing list") + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + lists, err := s.mailingLists(ctx, false) + if err != nil && len(lists) == 0 { + return err + } + var list *listmonk.List + for i := range lists { + if fmt.Sprint(lists[i].ID) == r.PostFormValue("list") { + list = &lists[i] + } + } + if list == nil { + return errors.New("choose a mailing list") + } + confirmed := r.PostFormValue("agreed") == "on" + if !confirmed && !list.Double() { + return errors.New(list.Name + " sends its mail without asking first: add someone there only once they've agreed to receive it, or choose a double opt-in list") + } + attribs := map[string]any{"source": "supermarket"} + if p.Title != "" { + attribs["title"] = p.Title + } + if p.CompanyID != 0 { + if co, err := prospects.GetCompany(s.DB, p.CompanyID); err == nil { + attribs["company"] = co.Name + } + } + if p.SignalID != 0 { + if sig, err := signals.Get(s.DB, p.SignalID); err == nil { + attribs["signal"] = sig.Slug + } + } + if _, _, err := c.Subscribe(ctx, listmonk.Subscriber{Email: p.Email, Name: p.Name(), Attribs: attribs}, *list, confirmed); err != nil { + return err + } + return prospects.AddedToList(s.DB, id, list.ID, list.Name, confirmed || !list.Double(), time.Now()) +} + +// reviewLists are the lists Review offers, quickly: what's cached, or a +// short read; nil until Listmonk is set up. +func (s *Server) reviewLists(r *http.Request) []listmonk.List { + if s.listmonk() == nil { + return nil + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + lists, _ := s.mailingLists(ctx, false) + return lists +} + +// onLists are the lists each person was added to, by contact ID. +func (s *Server) onLists() map[int64][]prospects.ListMember { + m, _ := prospects.ListsOf(s.DB) + return m +} + +// optOutSync is what the last sync of Listmonk's opt-outs did. +type optOutSync struct { + At time.Time `json:"at"` + Seen int `json:"seen"` // people Listmonk says don't want mail + Added int `json:"added"` // of them, newly on the suppression list + Error string `json:"error,omitempty"` +} + +const ( + optOutKey = "listmonk:optouts" + optOutEvery = time.Hour +) + +// syncOptOuts puts everyone blocklisted in Listmonk, or unsubscribed from +// one of its lists, on the suppression list (an address already there +// keeps its reason), and forgets the list they left. +func (s *Server) syncOptOuts(ctx context.Context) (*optOutSync, error) { + res := &optOutSync{At: time.Now()} + finish := func(err error) (*optOutSync, error) { + if err != nil { + res.Error = err.Error() + } + _ = s.DB.PutJSON(optOutKey, res) + return res, err + } + c := s.listmonk() + if c == nil { + return finish(errors.New("set up Listmonk first")) + } + lists, err := s.mailingLists(ctx, true) + if err != nil { + return finish(err) + } + out, err := c.OptedOut(ctx, lists) + if err != nil && len(out) == 0 { + return finish(err) + } + seen := map[string]bool{} + for _, o := range out { + if !seen[o.Email] { + seen[o.Email] = true + res.Seen++ + } + if o.List != "" { + if _, derr := s.DB.Exec(`DELETE FROM list_members WHERE list_name = ? AND contact_id IN (SELECT id FROM prospect_contacts WHERE email = ?)`, o.List, o.Email); derr != nil { + return finish(derr) + } + } + if already, serr := prospects.IsSuppressed(s.DB, o.Email, ""); serr != nil { + return finish(serr) + } else if already { + continue + } + reason := "Blocklisted in Listmonk" + if o.List != "" { + reason = "Unsubscribed from “" + o.List + "” in Listmonk" + } + if serr := prospects.Suppress(s.DB, "email", o.Email, reason, res.At); serr != nil { + return finish(serr) + } + res.Added++ + } + return finish(err) // a list that failed partway still reports its error +} + +// listmonkSync syncs the opt-outs now. +func (s *Server) listmonkSync(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) + defer cancel() + res, err := s.syncOptOuts(ctx) + if err != nil { + redirect(w, r, "/settings/email#lists", "") // the card shows the error + return + } + redirectCounts(w, r, "/settings/email#lists", "optouts-synced", res.Added) +} + +// hourlyOptOuts syncs Listmonk's opt-outs once an hour. +func (s *Server) hourlyOptOuts(ctx context.Context) { + if s.listmonk() == nil { + return + } + var last optOutSync + if ok, _ := s.DB.GetJSON(optOutKey, &last); ok && time.Since(last.At) < optOutEvery { + return + } + sctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + if res, err := s.syncOptOuts(sctx); err != nil { + s.Log.Warn("listmonk: syncing opt-outs", "err", err) + } else if res.Added > 0 { + s.Log.Info("listmonk: opt-outs added to the suppression list", "count", res.Added) + } +} + +func (s *Server) lastOptOuts() *optOutSync { + var last optOutSync + if ok, _ := s.DB.GetJSON(optOutKey, &last); !ok { + return nil + } + return &last +} diff --git a/internal/web/listmonk_test.go b/internal/web/listmonk_test.go new file mode 100644 index 0000000..f2d0e33 --- /dev/null +++ b/internal/web/listmonk_test.go @@ -0,0 +1,124 @@ +package web + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "supermarket/internal/prospects" + "supermarket/internal/secrets" +) + +func TestMailingLists(t *testing.T) { + var added []map[string]any + lm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/api/lists": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{ + {"id": 3, "name": "Newsletter", "optin": "double"}, {"id": 4, "name": "Announcements", "optin": "single"}}}}) + case r.URL.Path == "/api/subscribers" && r.Method == http.MethodPost: + var b map[string]any + json.NewDecoder(r.Body).Decode(&b) + added = append(added, b) + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"id": 9}}) + default: + http.NotFound(w, r) + } + })) + defer lm.Close() + s, h := newTestServer(t, nil) + now := time.Now() + ann, _, _ := prospects.AddContact(s.DB, prospects.Contact{FirstName: "Ann", LastName: "Lee", Email: "ann@lee.example", Title: "IT lead", Source: prospects.SourceManual}, now) + bob, _, _ := prospects.AddContact(s.DB, prospects.Contact{FirstName: "Bob", LastName: "Ray", Email: "bob@nope.example", Source: prospects.SourceManual}, now) + prospects.Suppress(s.DB, "domain", "nope.example", "", now) + + if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); strings.Contains(body, "Add to a mailing list") { + t.Error("offered before Listmonk is set up") + } + postForm(h, "/settings/email/listmonk", url.Values{"listmonk_url": {lm.URL}, "listmonk_user": {"sm"}, secrets.ListmonkToken: {"tok"}}) + if body := postForm(h, "/settings/email/listmonk/test", nil).Body.String(); !strings.Contains(body, "It works: 2 lists") { + t.Errorf("test: %s", body) + } + body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String() + if !strings.Contains(body, "Add to a mailing list") || !strings.Contains(body, "Newsletter (double opt-in)") { + t.Fatalf("review: no list form") + } + + add := func(id int64, list string, agreed bool) *httptest.ResponseRecorder { + v := url.Values{"list": {list}, "tab": {"new"}} + if agreed { + v.Set("agreed", "on") + } + return postForm(h, "/prospects/contact/"+strconv.FormatInt(id, 10)+"/list", v) + } + if rec := add(ann, "4", false); !strings.Contains(rec.Body.String(), "sends its mail without asking first") || len(added) != 0 { + t.Errorf("single opt-in without agreement: %d %v", rec.Code, added) + } + if rec := add(bob, "3", false); !strings.Contains(rec.Body.String(), "suppression list") || len(added) != 0 { + t.Errorf("suppressed: %d", rec.Code) + } + if rec := add(ann, "3", false); rec.Code != http.StatusSeeOther || len(added) != 1 { + t.Fatalf("add: %d %s", rec.Code, rec.Body.String()) + } + if a := added[0]; a["email"] != "ann@lee.example" || a["preconfirm_subscriptions"] != false || a["attribs"].(map[string]any)["title"] != "IT lead" { + t.Errorf("sent: %v", a) + } + if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); !strings.Contains(body, "Newsletter (asked to confirm)") { + t.Error("the card doesn't say she's on the list") + } + if rec := add(ann, "4", true); rec.Code != http.StatusSeeOther || added[1]["preconfirm_subscriptions"] != true { + t.Errorf("agreed: %d %v", rec.Code, added) + } +} + +func TestOptOutSync(t *testing.T) { + lm := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + switch { + case r.URL.Path == "/api/lists": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{{"id": 3, "name": "Newsletter", "optin": "double"}}}}) + case q.Get("query") != "": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{{"email": "spam@x.example"}, {"email": "kept@x.example"}}, "total": 2}}) + case q.Get("list_id") == "3": + json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"results": []map[string]any{{"email": "ann@lee.example"}}, "total": 1}}) + default: + http.NotFound(w, r) + } + })) + defer lm.Close() + s, h := newTestServer(t, nil) + now := time.Now() + ann, _, _ := prospects.AddContact(s.DB, prospects.Contact{FirstName: "Ann", LastName: "Lee", Email: "ann@lee.example", Source: prospects.SourceManual}, now) + prospects.AddedToList(s.DB, ann, 3, "Newsletter", false, now) + prospects.Suppress(s.DB, "email", "kept@x.example", "My own reason", now) + postForm(h, "/settings/email/listmonk", url.Values{"listmonk_url": {lm.URL}, "listmonk_user": {"sm"}, secrets.ListmonkToken: {"tok"}}) + + rec := postForm(h, "/settings/email/listmonk/sync", nil) + if !strings.Contains(rec.Header().Get("Location"), "msg=optouts-synced") || !strings.Contains(rec.Header().Get("Location"), "n1=2") { + t.Fatalf("sync: %d %s", rec.Code, rec.Header().Get("Location")) + } + list, _ := prospects.Suppressions(s.DB) + reasons := map[string]string{} + for _, e := range list { + reasons[e.Value] = e.Reason + } + if reasons["spam@x.example"] != "Blocklisted in Listmonk" || reasons["ann@lee.example"] != "Unsubscribed from “Newsletter” in Listmonk" || reasons["kept@x.example"] != "My own reason" { + t.Errorf("reasons: %v", reasons) + } + if on, _ := prospects.ListsOf(s.DB); len(on[ann]) != 0 { + t.Errorf("Ann still shows on the list: %+v", on[ann]) + } + if body := do(h, http.MethodGet, "/settings/email", nil, nil).Body.String(); !strings.Contains(body, "3 people don't want mail; 2 new on the suppression list") { + i := strings.Index(body, "Last synced") + t.Errorf("the card doesn't show the sync: %s", body[max(0, i):min(len(body), max(0, i)+300)]) + } + // Again: nothing new. + if rec := postForm(h, "/settings/email/listmonk/sync", nil); !strings.Contains(rec.Header().Get("Location"), "n1=0") { + t.Errorf("again: %s", rec.Header().Get("Location")) + } +} diff --git a/internal/web/outreach.go b/internal/web/outreach.go index b740945..db70ff4 100644 --- a/internal/web/outreach.go +++ b/internal/web/outreach.go @@ -64,6 +64,10 @@ func (s *Server) renderEmail(w http.ResponseWriter, r *http.Request, set outreac "Password": mailPassword, "Set": s.Secrets.Has(secrets.MailPassword), "Hours": hours(), + "Listmonk": s.listmonkConfig(), + "LMToken": listmonkToken, + "LMSet": s.Secrets.Has(secrets.ListmonkToken), + "OptOuts": s.lastOptOuts(), }}) } diff --git a/internal/web/prospects.go b/internal/web/prospects.go index d2b2457..214f9ec 100644 --- a/internal/web/prospects.go +++ b/internal/web/prospects.go @@ -137,26 +137,28 @@ func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab str } } s.render(w, r, "prospects", page{Title: "Review prospects", Nav: "prospects/review", Error: errMsg, Data: map[string]any{ - "Tab": tab, - "Statuses": prospects.Statuses, - "Counts": counts, - "Companies": companies, - "Loose": loose, - "Matches": matches, - "Synced": sync.Last, - "Signals": list, - "SignalNames": names, - "Signal": signalID, - "Events": events, - "Stages": signals.Stages[1:], // found is recorded on its own - "Channels": signals.Channels, - "Back": reviewURL(tab, signalID), - "Today": time.Now().Format("2006-01-02"), - "Hunter": s.Secrets.Has(secrets.HunterAPIKey), - "Runs": runs, - "Messages": messages, - "Unverified": len(unverified(companies, loose)), - "MaxVerify": maxVerify, + "Tab": tab, + "Statuses": prospects.Statuses, + "Counts": counts, + "Companies": companies, + "Loose": loose, + "Matches": matches, + "Synced": sync.Last, + "Signals": list, + "SignalNames": names, + "Signal": signalID, + "Events": events, + "Stages": signals.Stages[1:], // found is recorded on its own + "MailingLists": s.reviewLists(r), + "OnLists": s.onLists(), + "Channels": signals.Channels, + "Back": reviewURL(tab, signalID), + "Today": time.Now().Format("2006-01-02"), + "Hunter": s.Secrets.Has(secrets.HunterAPIKey), + "Runs": runs, + "Messages": messages, + "Unverified": len(unverified(companies, loose)), + "MaxVerify": maxVerify, }}) } @@ -197,6 +199,8 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) { if action == "verify" { msg = "verified" } + case "contact/list": + err, msg = s.addToList(r, id), "listed" case "company/delete", "contact/delete": err, msg = prospects.Delete(s.DB, kind, id), "deleted" case "company/reconsider", "contact/reconsider": diff --git a/internal/web/server.go b/internal/web/server.go index 7656fa3..21033d7 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -227,6 +227,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus) mux.HandleFunc("GET /seo/report", s.seoReportPage) mux.HandleFunc("GET /seo/next", s.seoNextPage) + mux.HandleFunc("POST /settings/email/listmonk", s.listmonkSave) + mux.HandleFunc("POST /settings/email/listmonk/test", s.listmonkTest) + mux.HandleFunc("POST /settings/email/listmonk/sync", s.listmonkSync) mux.HandleFunc("GET /seo/links", s.seoLinksPage) mux.HandleFunc("POST /seo/links/bing", s.seoLinksBing) mux.HandleFunc("POST /seo/links/{action}", s.seoLinksAction) @@ -569,6 +572,8 @@ var flashes = map[string]string{ "link-forgotten": "Forgotten.", "partners-read": "Looked at the partners' pages: %d new places to ask for a link.", "alternatives-read": "Searched: %d new lists that leave you out.", + "optouts-synced": "Synced: %d new on the suppression list.", + "listed": "Added to the mailing list.", "bing-read": "Read the links from Bing.", "audited": "The audit is done.", "auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.", diff --git a/internal/web/templates/email.html b/internal/web/templates/email.html index 13e1ae7..e6089e0 100644 --- a/internal/web/templates/email.html +++ b/internal/web/templates/email.html @@ -64,8 +64,39 @@
+ + {{end}}{{template "settings-end"}}{{end}} {{define "email-test"}}On {{range $i, $m := .}}{{if $i}}, {{end}}{{$m.List}}{{if not $m.Confirmed}} (asked to confirm){{end}} since {{ago $m.At}}{{end}}.
{{end}} +{{if and $d.MailingLists $p.Email}} +Without their agreement, only a double opt-in list takes them: Listmonk asks them to confirm, and they get nothing until they do. A single opt-in list sends its mail straight away, so it needs their agreement.
+