// Package leadsource imports what outside prospecting tools (origami.chat, // explee.com) learned while testing buying signals: their campaigns (each // the user assigns to a signal), who they contacted, who replied, who was // interested, and who unsubscribed. Contacts become funnel events; // interested people and repliers become prospects to review; unsubscribes // go on the suppression list. It only reads from the tools. package leadsource import ( "context" "errors" "math" "sort" "strconv" "strings" "sync" "time" "supermarket/internal/api/explee" "supermarket/internal/api/origami" "supermarket/internal/db" "supermarket/internal/prospects" "supermarket/internal/signals" ) // Result is what one import did. type Result struct { Source string `json:"source"` At time.Time `json:"at"` Campaigns int `json:"campaigns"` Events int `json:"events"` // new funnel events Prospects int `json:"prospects"` // new people to review Suppressed int `json:"suppressed"` Warnings []string `json:"warnings,omitempty"` Error string `json:"error,omitempty"` } func (r *Result) warn(msg string) { if len(r.Warnings) < 20 { r.Warnings = append(r.Warnings, msg) } } // Every is how often imports run on their own. const Every = 6 * time.Hour func resultKey(source string) string { return "leadsource:" + source } // Last is the last import's result for a source, or nil. func Last(d *db.DB, source string) (*Result, error) { var r Result ok, err := d.GetJSON(resultKey(source), &r) if err != nil || !ok { return nil, err } return &r, nil } // one import per source at a time var running sync.Map // ErrRunning means an import of that source is already under way. var ErrRunning = errors.New("an import is already running") func begin(source string) (func(), error) { if _, busy := running.LoadOrStore(source, true); busy { return nil, ErrRunning } return func() { running.Delete(source) }, nil } func finish(d *db.DB, r *Result, err error) (*Result, error) { if err != nil { r.Error = err.Error() } if perr := d.PutJSON(resultKey(r.Source), r); perr != nil && err == nil { err = perr } return r, err } // importer holds what both imports share. type importer struct { d *db.DB r *Result now time.Time } func (im *importer) event(e signals.Event) { added, err := signals.Record(im.d, e) if err != nil { im.r.warn(err.Error()) } if added { im.r.Events++ } } // suppress puts an address that unsubscribed on the suppression list. func (im *importer) suppress(email, reason string) { if email == "" { return } if sup, err := prospects.IsSuppressed(im.d, email, ""); err != nil || sup { return } if err := prospects.Suppress(im.d, "email", email, reason, im.now); err != nil { im.r.warn(err.Error()) return } im.r.Suppressed++ } // person is someone an outside tool says is worth reviewing. type person struct { first, last, name, title, email, linkedin, phone string company, domain string source, detail string signalID int64 } // prospect adds a person (and their company) for review, tagged with the // campaign's signal. Someone already there gets the signal if they had none. func (im *importer) prospect(p person) { if p.first == "" && p.last == "" && p.name != "" { p.first, p.last, _ = strings.Cut(p.name, " ") if p.last == "" { p.first, p.last = "", p.first } } if p.first == "" && p.last == "" && p.email == "" { return } var companyID int64 if p.company != "" || p.domain != "" { name := p.company if name == "" { name = p.domain } id, added, err := prospects.AddCompany(im.d, prospects.Company{ Name: name, Domain: p.domain, Source: p.source, SourceDetail: p.detail, SignalID: p.signalID, }, im.now) switch { case errors.Is(err, prospects.ErrSuppressed): return case err != nil: im.r.warn(err.Error()) return } companyID = id if !added { im.tagIfUntagged("company", id, p.signalID) } } id, added, err := prospects.AddContact(im.d, prospects.Contact{ CompanyID: companyID, FirstName: p.first, LastName: p.last, Title: p.title, Email: p.email, LinkedIn: p.linkedin, Phone: p.phone, Source: p.source, SourceDetail: p.detail, SignalID: p.signalID, }, im.now) switch { case errors.Is(err, prospects.ErrSuppressed): return case err != nil: im.r.warn(err.Error()) return } if added { im.r.Prospects++ } else { im.tagIfUntagged("contact", id, p.signalID) } } func (im *importer) tagIfUntagged(kind string, id, signalID int64) { if signalID == 0 { return } var current int64 if kind == "company" { if c, err := prospects.GetCompany(im.d, id); err == nil { current = c.SignalID } } else if c, err := prospects.GetContact(im.d, id); err == nil { current = c.SignalID } if current == 0 { if err := prospects.SetSignal(im.d, kind, id, signalID); err != nil { im.r.warn(err.Error()) } } } func cents(usd float64) int64 { return int64(math.Round(usd * 100)) } func orNow(t, now time.Time) time.Time { if t.IsZero() { return now } return t } func truncate(s string, n int) string { s = strings.Join(strings.Fields(s), " ") if len(s) <= n { return s } return strings.TrimSpace(s[:n]) + "…" } // --- explee.com --- // ImportExplee reads every campaign's numbers and contacted leads, and the // hot leads. func ImportExplee(ctx context.Context, d *db.DB, c *explee.Client, now time.Time) (*Result, error) { r := &Result{Source: signals.SourceExplee, At: now} done, err := begin(r.Source) if err != nil { return r, err } defer done() im := &importer{d: d, r: r, now: now} camps, err := c.Campaigns(ctx) if err != nil { return finish(d, r, err) } names := map[int64]string{} for _, camp := range camps { if ctx.Err() != nil { return finish(d, r, ctx.Err()) } id := strconv.FormatInt(camp.ID, 10) name := camp.Name if name == "" { name = "Campaign " + id } names[camp.ID] = name an, err := c.Analytics(ctx, camp.ID) if err != nil { r.warn(name + ": " + err.Error()) an = &explee.Analytics{} } status := an.Status if status == "" { status = camp.Status } if err := signals.SaveCampaign(d, signals.Campaign{ Source: r.Source, ID: id, Name: name, Status: status, SpendCents: cents(an.SpendUSD), SyncedAt: now, Stats: map[string]any{ "Emails sent": an.EmailsSent, "Replies": an.TotalReplies, "Reply rate %": an.ReplyRatePct, "Hot leads": an.HotLeads, "Cost per hot lead $": an.CostPerLeadUSD, "Leads contacted": an.LeadsPoolUsed, "Lost": an.ColdLost, "Booking link": camp.TargetURL, }, }); err != nil { return finish(d, r, err) } r.Campaigns++ sig, err := signals.CampaignSignal(d, r.Source, id) if err != nil { return finish(d, r, err) } leads, err := c.Leads(ctx, camp.ID) if err != nil { r.warn(name + ": " + err.Error()) } for _, l := range leads { if l.PersonID == "" { continue } key := id + ":" + l.PersonID email := l.Email if l.Erased { email = "" } base := signals.Event{SignalID: sig, Channel: r.Source, Subject: "explee:" + l.PersonID, Email: email, Campaign: r.Source + ":" + id, Source: r.Source} e := base e.Stage, e.ExternalID, e.At = signals.StageContacted, "contacted:"+key, orNow(origami.ParseTime(l.FirstSentAt), now) im.event(e) replyAt := orNow(origami.ParseTime(l.LastReplyAt), now) if l.Replied { e := base e.Stage, e.ExternalID, e.At = signals.StageReplied, "replied:"+key, replyAt im.event(e) } if st := strings.ToLower(l.Status); st == "hot" || st == "won" { e := base e.Stage, e.ExternalID, e.At = signals.StageInterested, "interested:"+key, replyAt im.event(e) } if l.Unsubscribed && !l.Erased { im.suppress(email, "Unsubscribed in explee.com ("+name+")") } } } hot, err := c.HotLeads(ctx, time.Time{}) if err != nil { r.warn("hot leads: " + err.Error()) } for _, h := range hot { if h.PersonID == "" { continue } id := strconv.FormatInt(h.CampaignID, 10) sig, _ := signals.CampaignSignal(d, r.Source, id) email := h.Email if h.Erased { email = "" } im.event(signals.Event{SignalID: sig, Stage: signals.StageInterested, Channel: r.Source, Subject: "explee:" + h.PersonID, Email: email, Campaign: r.Source + ":" + id, Source: r.Source, ExternalID: "interested:" + id + ":" + h.PersonID, At: orNow(origami.ParseTime(h.BecameHotAt), now)}) if h.Erased { continue } detail := "explee.com campaign “" + names[h.CampaignID] + "”" if h.WhyHot != "" { detail += ": " + truncate(h.WhyHot, 240) } im.prospect(person{name: h.Name, title: h.JobTitle, email: h.Email, linkedin: h.LinkedInURL, phone: h.Phone, company: h.CompanyName, domain: h.CompanyDomain, source: signals.SourceExplee, detail: detail, signalID: sig}) } return finish(d, r, nil) } // --- origami.chat --- // contactedStatuses are enrolled people's statuses that mean a message went // out. Origami's docs don't list them; these are the likely names. var contactedStatuses = map[string]bool{"active": true, "in_progress": true, "running": true, "sending": true, "completed": true, "finished": true, "replied": true, "stopped": true, "bounced": true, "unsubscribed": true} type sequence struct { campaignID, campaignName string signalID int64 who origami.Object } // ImportOrigami reads every campaign's stats and enrolled people, and the // replies. func ImportOrigami(ctx context.Context, d *db.DB, c *origami.Client, now time.Time) (*Result, error) { r := &Result{Source: signals.SourceOrigami, At: now} done, err := begin(r.Source) if err != nil { return r, err } defer done() im := &importer{d: d, r: r, now: now} camps, err := c.Campaigns(ctx) if err != nil { return finish(d, r, err) } seqs := map[string]sequence{} names := map[string]string{} for _, camp := range camps { if ctx.Err() != nil { return finish(d, r, ctx.Err()) } id := camp.Str("id") if id == "" { continue } name := camp.Str("name") if name == "" { name = "Campaign " + id } names[id] = name stats, err := c.Stats(ctx, id) if err != nil { r.warn(name + ": " + err.Error()) } if err := signals.SaveCampaign(d, signals.Campaign{ Source: r.Source, ID: id, Name: name, Status: camp.Str("status"), SyncedAt: now, Stats: flatten(stats), }); err != nil { return finish(d, r, err) } r.Campaigns++ sig, err := signals.CampaignSignal(d, r.Source, id) if err != nil { return finish(d, r, err) } people, err := c.People(ctx, id) if err != nil { r.warn(name + ": " + err.Error()) } for _, p := range people { seq := p.Str("sequence_id", "id") if seq == "" { continue } seqs[seq] = sequence{campaignID: id, campaignName: name, signalID: sig, who: p} email := strings.ToLower(p.Str("email", "identity.email", "contact.email", "person.email")) status := strings.ToLower(p.Str("status", "state")) sentAt := p.Time("first_sent_at", "started_at", "sent_at", "last_sent_at", "last_step_sent_at") base := signals.Event{SignalID: sig, Channel: r.Source, Subject: "origami:" + seq, Email: email, Campaign: r.Source + ":" + id, Source: r.Source} if !sentAt.IsZero() || contactedStatuses[status] { e := base e.Stage, e.ExternalID, e.At = signals.StageContacted, "contacted:"+seq, orNow(sentAt, now) im.event(e) } if strings.Contains(status, "unsubscribe") { im.suppress(email, "Unsubscribed in origami.chat ("+name+")") } } } replies, err := c.Replies(ctx, time.Time{}) if err != nil { r.warn("replies: " + err.Error()) } // Oldest first, so a person's first reply is the one recorded. sort.SliceStable(replies, func(i, j int) bool { return replies[i].Time("received_at", "created_at", "sent_at", "date").Before(replies[j].Time("received_at", "created_at", "sent_at", "date")) }) for _, rep := range replies { seq := rep.Str("sequence_id", "sequence.id") info, known := seqs[seq] campID := rep.Str("campaign_id", "campaign.id") if campID == "" { campID = info.campaignID } if seq == "" || campID == "" { continue } sig := info.signalID if !known { sig, _ = signals.CampaignSignal(d, r.Source, campID) } email := strings.ToLower(rep.Str("from_email", "from.email", "email", "lead.email")) if email == "" && known { email = strings.ToLower(info.who.Str("email", "identity.email", "contact.email", "person.email")) } im.event(signals.Event{SignalID: sig, Stage: signals.StageReplied, Channel: r.Source, Subject: "origami:" + seq, Email: email, Campaign: r.Source + ":" + campID, Source: r.Source, ExternalID: "replied:" + seq, At: orNow(rep.Time("received_at", "created_at", "sent_at", "date"), now)}) if !known { continue } w := info.who detail := "origami.chat campaign “" + names[campID] + "”" if body := rep.Str("body", "text", "plain_body"); body != "" { detail += ": " + truncate(body, 240) } im.prospect(person{ first: w.Str("first_name", "identity.first_name"), last: w.Str("last_name", "identity.last_name"), name: w.Str("name", "full_name", "identity.name"), title: w.Str("title", "job_title", "identity.title"), email: email, linkedin: w.Str("linkedin_url", "identity.linkedin_url", "linkedin"), company: w.Str("company", "company_name", "identity.company", "identity.company_name"), domain: w.Str("company_domain", "domain", "identity.company_domain", "identity.domain"), source: signals.SourceOrigami, detail: detail, signalID: sig, }) } return finish(d, r, nil) } // flatten keeps a stats object's numbers and short strings, one level of // nesting deep, for showing. func flatten(o origami.Object) map[string]any { out := map[string]any{} for k, v := range o { switch x := v.(type) { case float64, bool: out[k] = x case string: if len(x) < 80 && k != "object" { out[k] = x } case map[string]any: for k2, v2 := range x { if f, ok := v2.(float64); ok { out[k+" "+k2] = f } } } } return out }