Phase 2 part 3: buying signals, the funnel and the scorecard
Schema 7 adds signals (hypothesis, how to spot it, angle, status, utm slug), funnel_events (stage, channel, subject, campaign, source, deduped by external ID) and outside_campaigns. Prospects -> Signals is the scorecard: each signal's funnel from found to paid, people once per stage, with revenue and outside spend, by period and channel. Each signal's page shows its funnel by channel, its campaigns and its latest steps. Prospects carry a signal (filter, change, "found" recorded) and outcomes can be recorded by hand. Settings -> Lead sources holds origami.chat and explee.com API keys. Every 6 hours (or Import now) Supermarket reads their campaigns, numbers and spend, contacted people, replies and hot leads, read-only: interested people and repliers become prospects, unsubscribes are suppressed, and each campaign is assigned to a signal. The explee.com client follows its OpenAPI schema; origami.chat's responses are undocumented, so its client reads fields loosely and its Test shows the real response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,448 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/explee"
|
||||
"supermarket/internal/api/origami"
|
||||
"supermarket/internal/leadsource"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// --- The scorecard ---
|
||||
|
||||
// periods the scorecard can show.
|
||||
var periods = []struct{ ID, Label string }{
|
||||
{"", "All time"}, {"90d", "90 days"}, {"30d", "30 days"}, {"7d", "7 days"},
|
||||
}
|
||||
|
||||
func since(period string, now time.Time) time.Time {
|
||||
switch period {
|
||||
case "90d":
|
||||
return now.AddDate(0, 0, -90)
|
||||
case "30d":
|
||||
return now.AddDate(0, 0, -30)
|
||||
case "7d":
|
||||
return now.AddDate(0, 0, -7)
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
func (s *Server) signalsPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderSignals(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSignals(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
q := r.URL.Query()
|
||||
period, channel := q.Get("period"), q.Get("channel")
|
||||
rows, err := signals.Scorecard(s.DB, signals.Filter{Since: since(period, time.Now()), Channel: channel})
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
list, err := signals.List(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
camps, err := signals.Campaigns(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.render(w, r, "signals", page{Title: "Signals", Nav: "prospects/signals", Error: errMsg, Data: map[string]any{
|
||||
"Rows": rows,
|
||||
"Signals": list,
|
||||
"Stages": signals.Stages,
|
||||
"Channels": signals.Channels,
|
||||
"Periods": periods,
|
||||
"Period": period,
|
||||
"Channel": channel,
|
||||
"Campaigns": camps,
|
||||
"Sources": s.leadSources(),
|
||||
}})
|
||||
}
|
||||
|
||||
// --- One signal ---
|
||||
|
||||
type signalData struct {
|
||||
S *signals.Signal
|
||||
Statuses []string
|
||||
Stages []signals.Stage
|
||||
ByChannel []channelRow // its funnel per channel
|
||||
Total *signals.Row
|
||||
Campaigns []signals.Campaign
|
||||
Events []signals.Event
|
||||
Prospects int // new prospects tagged with it
|
||||
}
|
||||
|
||||
type channelRow struct {
|
||||
Channel string
|
||||
Row signals.Row
|
||||
}
|
||||
|
||||
func (s *Server) signalPage(w http.ResponseWriter, r *http.Request) {
|
||||
sig := &signals.Signal{Status: signals.StatusIdea}
|
||||
if idStr := r.PathValue("id"); idStr != "" {
|
||||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if sig, err = signals.Get(s.DB, id); errors.Is(err, signals.ErrNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
} else if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
s.renderSignal(w, r, sig, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signals.Signal, errMsg string) {
|
||||
d := signalData{S: sig, Statuses: signals.Statuses, Stages: signals.Stages}
|
||||
title := "New signal"
|
||||
if sig.ID != 0 {
|
||||
title = sig.Name
|
||||
all, err := signals.Scorecard(s.DB, signals.Filter{})
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
for i := range all {
|
||||
if all[i].Signal != nil && all[i].Signal.ID == sig.ID {
|
||||
d.Total = &all[i]
|
||||
}
|
||||
}
|
||||
for _, ch := range signals.Channels {
|
||||
rows, err := signals.Scorecard(s.DB, signals.Filter{Channel: ch.ID})
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Signal != nil && row.Signal.ID == sig.ID && (row.Total() > 0 || row.SpendCents > 0) {
|
||||
d.ByChannel = append(d.ByChannel, channelRow{ch.ID, row})
|
||||
}
|
||||
}
|
||||
}
|
||||
camps, err := signals.Campaigns(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
for _, c := range camps {
|
||||
if c.SignalID == sig.ID {
|
||||
d.Campaigns = append(d.Campaigns, c)
|
||||
}
|
||||
}
|
||||
if d.Events, err = signals.RecentEvents(s.DB, sig.ID, 30); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
cs, ps, err := prospects.Review(s.DB, prospects.StatusNew, sig.ID, 1000)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
d.Prospects = len(cs) + len(ps)
|
||||
}
|
||||
s.render(w, r, "signal", page{Title: title, Nav: "prospects/signals", Error: errMsg, Data: d})
|
||||
}
|
||||
|
||||
func (s *Server) signalSave(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sig := &signals.Signal{}
|
||||
if idStr := r.PathValue("id"); idStr != "" {
|
||||
id, err := strconv.ParseInt(idStr, 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if sig, err = signals.Get(s.DB, id); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
f := r.PostFormValue
|
||||
sig.Name, sig.Slug, sig.Hypothesis, sig.Spot, sig.Angle, sig.Status =
|
||||
f("name"), f("slug"), f("hypothesis"), f("spot"), f("angle"), f("status")
|
||||
if err := signals.Save(s.DB, sig); err != nil {
|
||||
s.renderSignal(w, r, sig, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/signals/"+strconv.FormatInt(sig.ID, 10), "saved")
|
||||
}
|
||||
|
||||
func (s *Server) signalDelete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := signals.Delete(s.DB, id); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/signals", "deleted")
|
||||
}
|
||||
|
||||
// signalCampaign assigns an outside campaign to a signal.
|
||||
func (s *Server) signalCampaign(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
|
||||
if err := signals.AssignCampaign(s.DB, r.PostFormValue("source"), r.PostFormValue("id"), sig); err != nil {
|
||||
s.renderSignals(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/signals#campaigns", "saved")
|
||||
}
|
||||
|
||||
// --- Outcomes recorded by hand ---
|
||||
|
||||
// prospectOutcome records a funnel step for a prospect: until Supermarket
|
||||
// sends and reads its own outreach, this is how replies, bookings and
|
||||
// payments get onto the scorecard.
|
||||
func (s *Server) prospectOutcome(w http.ResponseWriter, r *http.Request, kind string, id int64, tab string) error {
|
||||
var subject, email string
|
||||
var sig int64
|
||||
if kind == "company" {
|
||||
c, err := prospects.GetCompany(s.DB, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subject, sig = prospects.Subject(kind, id), c.SignalID
|
||||
} else {
|
||||
c, err := prospects.GetContact(s.DB, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subject, sig, email = prospects.Subject(kind, id), c.SignalID, c.Email
|
||||
}
|
||||
var value int64
|
||||
if amount := strings.TrimSpace(strings.TrimPrefix(r.PostFormValue("amount"), "$")); amount != "" {
|
||||
f, err := strconv.ParseFloat(strings.ReplaceAll(amount, ",", ""), 64)
|
||||
if err != nil || f < 0 {
|
||||
return fmt.Errorf("%q isn't an amount", amount)
|
||||
}
|
||||
value = int64(f*100 + 0.5)
|
||||
}
|
||||
at := time.Now()
|
||||
if day := r.PostFormValue("date"); day != "" {
|
||||
t, err := time.ParseInLocation("2006-01-02", day, time.Local)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%q isn't a date", day)
|
||||
}
|
||||
at = t.Add(12 * time.Hour)
|
||||
}
|
||||
_, err := signals.Record(s.DB, signals.Event{
|
||||
SignalID: sig, Stage: r.PostFormValue("stage"), Channel: r.PostFormValue("channel"), Subject: subject,
|
||||
Email: email, Source: signals.SourceManual, ValueCents: value, Note: r.PostFormValue("note"), At: at,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) funnelDelete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := signals.DeleteEvent(s.DB, id); err != nil {
|
||||
s.renderProspects(w, r, reviewTab(r.PostFormValue("tab")), 0, err.Error())
|
||||
return
|
||||
}
|
||||
back := r.PostFormValue("back")
|
||||
if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") {
|
||||
back = "/prospects"
|
||||
}
|
||||
redirect(w, r, back, "deleted")
|
||||
}
|
||||
|
||||
// --- Lead sources: origami.chat and explee.com ---
|
||||
|
||||
const origamiProjectKey = "leadsource:origami-project"
|
||||
|
||||
// leadSource is one tool, as the pages show it.
|
||||
type leadSource struct {
|
||||
ID, Name, Site string
|
||||
Key secretField
|
||||
Set bool
|
||||
Last *leadsource.Result
|
||||
}
|
||||
|
||||
var leadSourceKeys = []secretField{
|
||||
{"origami", secrets.OrigamiAPIKey, "API key",
|
||||
"In origami.chat, Settings → Developers → Create API key, with Full API access. It starts og_live_ and is shown once.", "https://origami.chat"},
|
||||
{"explee", secrets.ExpleeAPIKey, "API key",
|
||||
"In explee.com, Organization Settings → API keys.", "https://explee.com/app-auto-gtm/api-keys"},
|
||||
}
|
||||
|
||||
func (s *Server) leadSources() []leadSource {
|
||||
out := []leadSource{
|
||||
{ID: signals.SourceOrigami, Name: "origami.chat", Site: "https://origami.chat", Key: leadSourceKeys[0]},
|
||||
{ID: signals.SourceExplee, Name: "explee.com", Site: "https://explee.com", Key: leadSourceKeys[1]},
|
||||
}
|
||||
for i := range out {
|
||||
out[i].Set = s.Secrets.Has(out[i].Key.Name)
|
||||
out[i].Last, _ = leadsource.Last(s.DB, out[i].ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) origamiProject() string {
|
||||
var p string
|
||||
_, _ = s.DB.GetJSON(origamiProjectKey, &p)
|
||||
return p
|
||||
}
|
||||
|
||||
func (s *Server) sourcesPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.render(w, r, "sources", page{Title: "Lead sources", Nav: "settings/sources", Data: map[string]any{
|
||||
"Sources": s.leadSources(),
|
||||
"Project": s.origamiProject(),
|
||||
}})
|
||||
}
|
||||
|
||||
func (s *Server) sourcesSave(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.saveSecrets(r, leadSourceKeys); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.DB.PutJSON(origamiProjectKey, strings.TrimSpace(r.PostFormValue("origami_project"))); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/settings/sources", "saved")
|
||||
}
|
||||
|
||||
// sourcesTest checks a key, and for origami.chat shows what the API sends,
|
||||
// since its responses aren't documented.
|
||||
func (s *Server) sourcesTest(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
data := map[string]any{}
|
||||
switch r.PathValue("source") {
|
||||
case signals.SourceExplee:
|
||||
key := s.Secrets.Get(secrets.ExpleeAPIKey)
|
||||
if key == "" {
|
||||
data["Error"] = "Save the key first."
|
||||
break
|
||||
}
|
||||
who, err := explee.New(key).Me(ctx)
|
||||
if err != nil {
|
||||
data["Error"] = err.Error()
|
||||
break
|
||||
}
|
||||
data["OK"] = "The key works (" + who + ")."
|
||||
case signals.SourceOrigami:
|
||||
key := s.Secrets.Get(secrets.OrigamiAPIKey)
|
||||
if key == "" {
|
||||
data["Error"] = "Save the key first."
|
||||
break
|
||||
}
|
||||
c := origami.New(key, s.origamiProject())
|
||||
who, err := c.Account(ctx)
|
||||
if err != nil {
|
||||
data["Error"] = err.Error()
|
||||
break
|
||||
}
|
||||
data["OK"] = "The key works (" + who + ")."
|
||||
if sample, err := c.Sample(ctx); err == nil {
|
||||
raw, _ := json.MarshalIndent(sample, "", " ")
|
||||
data["Sample"] = string(raw)
|
||||
}
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.fragment(w, "sources", "test-result", data)
|
||||
}
|
||||
|
||||
// importSource runs one tool's import now.
|
||||
func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
|
||||
source := r.PathValue("source")
|
||||
if source != signals.SourceExplee && source != signals.SourceOrigami {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
|
||||
defer cancel()
|
||||
res, err := s.runImport(ctx, source)
|
||||
if err != nil && res == nil {
|
||||
s.renderSignals(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.renderSignals(w, r, "Importing from "+source+": "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/signals#campaigns", "imported")
|
||||
}
|
||||
|
||||
// runImport imports from one tool, if its key is saved. It returns nil, nil
|
||||
// without one.
|
||||
func (s *Server) runImport(ctx context.Context, source string) (*leadsource.Result, error) {
|
||||
now := time.Now()
|
||||
switch source {
|
||||
case signals.SourceExplee:
|
||||
if key := s.Secrets.Get(secrets.ExpleeAPIKey); key != "" {
|
||||
return leadsource.ImportExplee(ctx, s.DB, explee.New(key), now)
|
||||
}
|
||||
case signals.SourceOrigami:
|
||||
if key := s.Secrets.Get(secrets.OrigamiAPIKey); key != "" {
|
||||
return leadsource.ImportOrigami(ctx, s.DB, origami.New(key, s.origamiProject()), now)
|
||||
}
|
||||
}
|
||||
return nil, errors.New("save the tool's API key first, under Settings → Lead sources")
|
||||
}
|
||||
|
||||
// RunImports imports from each tool with a saved key, every
|
||||
// leadsource.Every.
|
||||
func (s *Server) RunImports(ctx context.Context) {
|
||||
tick := time.NewTicker(10 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
|
||||
last, _ := leadsource.Last(s.DB, src)
|
||||
if last != nil && time.Since(last.At) < leadsource.Every {
|
||||
continue
|
||||
}
|
||||
ictx, cancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||
res, err := s.runImport(ictx, src)
|
||||
cancel()
|
||||
switch {
|
||||
case res == nil:
|
||||
case err != nil:
|
||||
s.Log.Warn("lead source import failed", "source", src, "err", err)
|
||||
default:
|
||||
s.Log.Info("lead source imported", "source", src, "campaigns", res.Campaigns, "events", res.Events,
|
||||
"prospects", res.Prospects, "suppressed", res.Suppressed)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user