package outreach import ( "database/sql" "errors" "fmt" "strconv" "strings" "time" "supermarket/internal/db" "supermarket/internal/prospects" "supermarket/internal/signals" ) // Channels. const ( ChannelEmail = "email" ChannelLinkedIn = "linkedin" ) // Statuses, in the order the outreach page's tabs show them. const ( StatusDraft = "draft" StatusQueued = "queued" StatusSent = "sent" StatusFailed = "failed" StatusBounced = "bounced" StatusDiscarded = "discarded" ) // LinkedInLimit is the most characters a LinkedIn message draft should // have: short enough for a connection note's longer limits and to be read. const LinkedInLimit = 600 // Message is one email or LinkedIn message to a prospect. type Message struct { ID int64 ContactID int64 SignalID int64 Channel string Status string Subject string Body string To string MessageID string CreatedAt time.Time QueuedAt time.Time SentAt time.Time RepliedAt time.Time Reply string Error string // Filled in when listing. Contact prospects.Contact Company string } // ErrNotFound means there's no such message. var ErrNotFound = errors.New("no such message") const timeFormat = time.RFC3339 func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) } func nullTime(t time.Time) any { if t.IsZero() { return nil } return formatTime(t) } func parseTime(s sql.NullString) time.Time { if !s.Valid { return time.Time{} } t, _ := time.Parse(timeFormat, s.String) return t } func nullID(id int64) any { if id == 0 { return nil } return id } const columns = `o.id, o.contact_id, coalesce(o.signal_id, 0), o.channel, o.status, o.subject, o.body, o.to_addr, o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error, p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, coalesce(p.company_id, 0), coalesce(c.name, '')` const from = ` FROM outreach o JOIN prospect_contacts p ON p.id = o.contact_id LEFT JOIN prospect_companies c ON c.id = p.company_id` func scan(rows *sql.Rows) ([]Message, error) { defer rows.Close() var out []Message for rows.Next() { var m Message var created string var queued, sent, replied sql.NullString if err := rows.Scan(&m.ID, &m.ContactID, &m.SignalID, &m.Channel, &m.Status, &m.Subject, &m.Body, &m.To, &m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error, &m.Contact.FirstName, &m.Contact.LastName, &m.Contact.Title, &m.Contact.Email, &m.Contact.EmailStatus, &m.Contact.LinkedIn, &m.Contact.CompanyID, &m.Company); err != nil { return nil, err } m.Contact.ID = m.ContactID m.CreatedAt, _ = time.Parse(timeFormat, created) m.QueuedAt, m.SentAt, m.RepliedAt = parseTime(queued), parseTime(sent), parseTime(replied) out = append(out, m) } return out, rows.Err() } // Get returns one message. func Get(d *db.DB, id int64) (*Message, error) { rows, err := d.Query(`SELECT `+columns+from+` WHERE o.id = ?`, id) if err != nil { return nil, err } ms, err := scan(rows) if err != nil { return nil, err } if len(ms) == 0 { return nil, ErrNotFound } return &ms[0], nil } // Tab is a list on the outreach page. type Tab struct{ ID, Label string } // Tabs on the outreach page. Replies are sent messages with a reply. var Tabs = []Tab{ {StatusDraft, "Drafts"}, {StatusQueued, "Queued"}, {StatusSent, "Sent"}, {"replied", "Replies"}, {StatusFailed, "Didn't go"}, } // List returns one tab's messages: newest first, except the queue, which // is in sending order. func List(d *db.DB, tab string, limit int) ([]Message, error) { where, order := `o.status = ?`, `o.id DESC` args := []any{tab} switch tab { case StatusQueued: order = `o.queued_at, o.id` case StatusSent: order = `o.sent_at DESC, o.id DESC` case "replied": where, args, order = `o.replied_at IS NOT NULL`, nil, `o.replied_at DESC` case StatusFailed: where, args = `o.status IN ('failed', 'bounced')`, nil } rows, err := d.Query(`SELECT `+columns+from+` WHERE `+where+` ORDER BY `+order+` LIMIT ?`, append(args, limit)...) if err != nil { return nil, err } return scan(rows) } // Counts is how many messages each tab has. func Counts(d *db.DB) (map[string]int, error) { out := map[string]int{} rows, err := d.Query(`SELECT status, count(*) FROM outreach GROUP BY status UNION ALL SELECT 'replied', count(*) FROM outreach WHERE replied_at IS NOT NULL`) if err != nil { return nil, err } defer rows.Close() for rows.Next() { var s string var n int if err := rows.Scan(&s, &n); err != nil { return nil, err } if s == StatusBounced { s = StatusFailed } out[s] += n } return out, rows.Err() } // ForContacts lists the messages to each of these people, newest first. func ForContacts(d *db.DB, ids []int64) (map[int64][]Message, error) { out := map[int64][]Message{} if len(ids) == 0 { return out, nil } strs := make([]string, len(ids)) for i, id := range ids { strs[i] = strconv.FormatInt(id, 10) } // The IDs are integers, so joining them is safe. rows, err := d.Query(`SELECT ` + columns + from + ` WHERE o.contact_id IN (` + strings.Join(strs, ",") + `) AND o.status != 'discarded' ORDER BY o.id DESC`) if err != nil { return nil, err } ms, err := scan(rows) for _, m := range ms { out[m.ContactID] = append(out[m.ContactID], m) } return out, err } // insert stores a new draft. func insert(d *db.DB, m *Message) error { res, err := d.Exec(`INSERT INTO outreach (contact_id, signal_id, channel, status, subject, body, to_addr, created_at) VALUES (?, ?, ?, 'draft', ?, ?, ?, ?)`, m.ContactID, nullID(m.SignalID), m.Channel, m.Subject, m.Body, m.To, formatTime(m.CreatedAt)) if err != nil { return err } m.ID, err = res.LastInsertId() m.Status = StatusDraft return err } // Edit changes a draft's (or a queued message's) subject and text. func Edit(d *db.DB, id int64, subject, body string) error { subject, body = strings.TrimSpace(subject), strings.TrimSpace(body) if body == "" { return errors.New("the message is empty") } return change(d, id, `subject = ?, body = ?`, []any{subject, body}, StatusDraft, StatusQueued) } // Queue approves an email for sending: it goes out in turn, within the // sending hours and the daily limit. func Queue(d *db.DB, id int64, now time.Time) error { m, err := Get(d, id) if err != nil { return err } if m.Channel != ChannelEmail { return errors.New("LinkedIn messages are sent by hand: copy it, send it on LinkedIn, then mark it sent") } if err := sendable(d, m); err != nil { return err } return change(d, id, `status = 'queued', queued_at = ?, error = ''`, []any{formatTime(now)}, StatusDraft, StatusFailed) } // Unqueue takes an email out of the queue, back to the drafts. func Unqueue(d *db.DB, id int64) error { return change(d, id, `status = 'draft', queued_at = NULL`, nil, StatusQueued) } // Discard drops a draft, or a message that didn't go. func Discard(d *db.DB, id int64) error { return change(d, id, `status = 'discarded'`, nil, StatusDraft, StatusQueued, StatusFailed) } // change updates a message that has one of the given statuses. func change(d *db.DB, id int64, set string, args []any, from ...string) error { marks := strings.TrimSuffix(strings.Repeat("?,", len(from)), ",") all := append(args, id) for _, f := range from { all = append(all, f) } res, err := d.Exec(`UPDATE outreach SET `+set+` WHERE id = ? AND status IN (`+marks+`)`, all...) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { var status string if err := d.QueryRow(`SELECT status FROM outreach WHERE id = ?`, id).Scan(&status); err != nil { return ErrNotFound } return fmt.Errorf("that message is already %s", status) } return nil } // sendable checks that a message may go to its person now: they aren't on // the suppression list, the address doesn't bounce, and nobody wrote to // them in the last two weeks. func sendable(d *db.DB, m *Message) error { p, err := prospects.GetContact(d, m.ContactID) if err != nil { return err } if p.Status == prospects.StatusRejected { return errors.New(p.Name() + " was set aside") } if m.Channel == ChannelLinkedIn { return nil } if m.To == "" { return errors.New(p.Name() + " has no email address") } if sup, err := prospects.IsSuppressed(d, m.To, ""); err != nil || sup { if err == nil { err = fmt.Errorf("%s: %w", m.To, prospects.ErrSuppressed) } return err } if p.Email == m.To && p.EmailStatus == prospects.EmailInvalid { return errors.New(m.To + " bounces") } var last sql.NullString if err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE to_addr = ? AND id != ? AND status IN ('sent', 'bounced')`, m.To, m.ID).Scan(&last); err != nil { return err } if t := parseTime(last); !t.IsZero() && time.Since(t) < 14*24*time.Hour { return fmt.Errorf("%s was already emailed on %s", m.To, t.Local().Format("2 Jan")) } return nil } // markSent records that a message went out, and the funnel step. func markSent(d *db.DB, m *Message, messageID string, now time.Time) error { if _, err := d.Exec(`UPDATE outreach SET status = 'sent', sent_at = ?, message_id = ?, error = '' WHERE id = ?`, formatTime(now), messageID, m.ID); err != nil { return err } m.Status, m.SentAt, m.MessageID = StatusSent, now, messageID _, err := signals.Record(d, signals.Event{ SignalID: m.SignalID, Stage: signals.StageContacted, Channel: m.Channel, Subject: prospects.Subject("contact", m.ContactID), Email: m.To, Source: signals.SourceSupermarket, ExternalID: "outreach:" + strconv.FormatInt(m.ID, 10), Note: m.Subject, At: now, }) return err } // MarkSent records that the user sent a LinkedIn message by hand. func MarkSent(d *db.DB, id int64, body string, now time.Time) error { m, err := Get(d, id) if err != nil { return err } if m.Channel != ChannelLinkedIn { return errors.New("emails are sent from the queue") } if m.Status != StatusDraft { return fmt.Errorf("that message is already %s", m.Status) } if b := strings.TrimSpace(body); b != "" { m.Body = b if _, err := d.Exec(`UPDATE outreach SET body = ? WHERE id = ?`, b, id); err != nil { return err } } return markSent(d, m, "", now) } // MarkReplied records a reply: read from the mailbox, or noted by hand for // LinkedIn. Only the first reply to a message counts. func MarkReplied(d *db.DB, id int64, reply, externalID string, at time.Time) error { m, err := Get(d, id) if err != nil { return err } if m.Status != StatusSent { return errors.New("only a sent message can have a reply") } if !m.RepliedAt.IsZero() { return nil } reply = strings.TrimSpace(reply) if _, err := d.Exec(`UPDATE outreach SET replied_at = ?, reply = ? WHERE id = ?`, formatTime(at), reply, id); err != nil { return err } if externalID == "" { externalID = "reply:outreach:" + strconv.FormatInt(id, 10) } _, err = signals.Record(d, signals.Event{ SignalID: m.SignalID, Stage: signals.StageReplied, Channel: m.Channel, Subject: prospects.Subject("contact", m.ContactID), Email: m.To, Source: signals.SourceSupermarket, ExternalID: externalID, Note: truncate(reply, 300), At: at, }) return err } func truncate(s string, n int) string { r := []rune(s) if len(r) <= n { return s } return string(r[:n-1]) + "…" } // fail records why an email didn't go. func fail(d *db.DB, id int64, status string, err error) error { _, dberr := d.Exec(`UPDATE outreach SET status = ?, error = ? WHERE id = ?`, status, err.Error(), id) return dberr } // SentToday is how many emails went out since local midnight. func SentToday(d *db.DB, now time.Time) (int, error) { y, mo, day := now.Local().Date() midnight := time.Date(y, mo, day, 0, 0, 0, 0, time.Local) var n int err := d.QueryRow(`SELECT count(*) FROM outreach WHERE channel = 'email' AND sent_at >= ?`, formatTime(midnight)).Scan(&n) return n, err } // lastSent is when the last email went out. func lastSent(d *db.DB) (time.Time, error) { var s sql.NullString err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE channel = 'email'`).Scan(&s) return parseTime(s), err }