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,205 @@
|
||||
// Package explee reads outreach campaigns and their results from
|
||||
// explee.com's public API (https://api.explee.com/public/api/docs). It only
|
||||
// reads: Supermarket never starts, changes or sends anything there.
|
||||
package explee
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const apiBase = "https://api.explee.com/public/api/v1"
|
||||
|
||||
// ErrUnauthorized means the key was refused.
|
||||
var ErrUnauthorized = errors.New("explee.com refused the API key")
|
||||
|
||||
// Client calls the API with one key.
|
||||
type Client struct {
|
||||
key, base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(key string) *Client {
|
||||
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: 60 * time.Second}}
|
||||
}
|
||||
|
||||
// WithBase points the client at another server (for tests).
|
||||
func (c *Client) WithBase(u string) *Client {
|
||||
c.base = strings.TrimRight(u, "/")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
|
||||
u := c.base + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("X-API-Key", c.key)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("explee.com %s: HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body[:min(len(body), 300)])))
|
||||
}
|
||||
return json.Unmarshal(body, out)
|
||||
}
|
||||
|
||||
// Me checks the key; it returns the key owner's email or name.
|
||||
func (c *Client) Me(ctx context.Context) (string, error) {
|
||||
var out map[string]any
|
||||
if err := c.get(ctx, "/me", nil, &out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, k := range []string{"email", "name", "organization_name"} {
|
||||
if v, ok := out[k].(string); ok && v != "" {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return "the key works", nil
|
||||
}
|
||||
|
||||
// Campaign is an outreach campaign.
|
||||
type Campaign struct {
|
||||
ID int64 `json:"id"`
|
||||
ProjectID int64 `json:"project_id"`
|
||||
Name string `json:"name"`
|
||||
TargetURL string `json:"target_url"` // the booking link
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// Campaigns lists every campaign, archived ones too.
|
||||
func (c *Client) Campaigns(ctx context.Context) ([]Campaign, error) {
|
||||
var out struct {
|
||||
Campaigns []Campaign `json:"campaigns"`
|
||||
}
|
||||
err := c.get(ctx, "/autogtm/campaigns", url.Values{"include_archived": {"true"}}, &out)
|
||||
return out.Campaigns, err
|
||||
}
|
||||
|
||||
// Analytics are a campaign's lifetime numbers.
|
||||
type Analytics struct {
|
||||
Status string `json:"status"`
|
||||
EmailsSent int `json:"emails_sent"`
|
||||
TotalReplies int `json:"total_replies"`
|
||||
ReplyRatePct float64 `json:"reply_rate_pct"`
|
||||
HotLeads int `json:"hot_leads"`
|
||||
SpendUSD float64 `json:"spend_usd"`
|
||||
CostPerLeadUSD float64 `json:"cost_per_lead_usd"`
|
||||
LeadsPoolUsed int `json:"leads_pool_used"`
|
||||
ManualStatus map[string]int `json:"manual_status_counts"`
|
||||
ColdLost int `json:"cold_lost"`
|
||||
}
|
||||
|
||||
func (c *Client) Analytics(ctx context.Context, campaignID int64) (*Analytics, error) {
|
||||
var out Analytics
|
||||
err := c.get(ctx, "/autogtm/campaigns/"+strconv.FormatInt(campaignID, 10)+"/analytics", url.Values{"period": {"all"}}, &out)
|
||||
return &out, err
|
||||
}
|
||||
|
||||
// Lead is a contacted lead.
|
||||
type Lead struct {
|
||||
PersonID string `json:"person_id"`
|
||||
CampaignID int64 `json:"campaign_id"`
|
||||
Erased bool `json:"erased"` // they asked to be removed: no personal data
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
JobTitle string `json:"job_title"`
|
||||
LinkedInURL string `json:"linkedin_url"`
|
||||
CompanyName string `json:"company_name"`
|
||||
CompanyDomain string `json:"company_domain"`
|
||||
FirstSentAt string `json:"first_sent_at"`
|
||||
Status string `json:"status"` // set by the team in the inbox, e.g. Hot, Won
|
||||
Replied bool `json:"replied"`
|
||||
Bounced bool `json:"bounced"`
|
||||
Unsubscribed bool `json:"unsubscribed"`
|
||||
LastReplyAt string `json:"last_reply_at"`
|
||||
}
|
||||
|
||||
// Leads lists every contacted lead of a campaign.
|
||||
func (c *Client) Leads(ctx context.Context, campaignID int64) ([]Lead, error) {
|
||||
var all []Lead
|
||||
offset := 0
|
||||
for page := 0; page < 200; page++ {
|
||||
var out struct {
|
||||
Leads []Lead `json:"leads"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextOffset *int `json:"next_offset"`
|
||||
}
|
||||
q := url.Values{"limit": {"1000"}, "offset": {strconv.Itoa(offset)}}
|
||||
if err := c.get(ctx, "/autogtm/campaigns/"+strconv.FormatInt(campaignID, 10)+"/leads", q, &out); err != nil {
|
||||
return all, err
|
||||
}
|
||||
all = append(all, out.Leads...)
|
||||
if !out.HasMore || out.NextOffset == nil {
|
||||
break
|
||||
}
|
||||
offset = *out.NextOffset
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// HotLead is a lead whose reply showed interest.
|
||||
type HotLead struct {
|
||||
PersonID string `json:"person_id"`
|
||||
CampaignID int64 `json:"campaign_id"`
|
||||
Erased bool `json:"erased"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
JobTitle string `json:"job_title"`
|
||||
CompanyName string `json:"company_name"`
|
||||
CompanyDomain string `json:"company_domain"`
|
||||
LinkedInURL string `json:"linkedin_url"`
|
||||
Phone string `json:"phone"`
|
||||
WhyHot string `json:"why_hot"`
|
||||
BecameHotAt string `json:"became_hot_at"`
|
||||
}
|
||||
|
||||
// HotLeads lists hot leads that became hot at or after since (zero: all).
|
||||
func (c *Client) HotLeads(ctx context.Context, since time.Time) ([]HotLead, error) {
|
||||
var all []HotLead
|
||||
offset := 0
|
||||
for page := 0; page < 200; page++ {
|
||||
var out struct {
|
||||
Leads []HotLead `json:"leads"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextOffset *int `json:"next_offset"`
|
||||
}
|
||||
q := url.Values{"limit": {"500"}, "offset": {strconv.Itoa(offset)}}
|
||||
if !since.IsZero() {
|
||||
q.Set("since", since.UTC().Format(time.RFC3339))
|
||||
}
|
||||
if err := c.get(ctx, "/autogtm/hot-leads", q, &out); err != nil {
|
||||
return all, err
|
||||
}
|
||||
all = append(all, out.Leads...)
|
||||
if !out.HasMore || out.NextOffset == nil {
|
||||
break
|
||||
}
|
||||
offset = *out.NextOffset
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
// Package origami reads outreach campaigns and their results from
|
||||
// origami.chat's v3 API (https://docs.origami.chat). It only reads:
|
||||
// Supermarket never starts, changes or sends anything there.
|
||||
//
|
||||
// The v3 spec documents requests but not response bodies, so responses
|
||||
// are read as loose JSON and fields are looked up by the names the docs
|
||||
// use. Check them against a real account with Sample.
|
||||
package origami
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const apiBase = "https://origami.chat/api/v3"
|
||||
|
||||
// ErrUnauthorized means the key was refused.
|
||||
var ErrUnauthorized = errors.New("origami.chat refused the API key")
|
||||
|
||||
// Object is one JSON object from the API.
|
||||
type Object map[string]any
|
||||
|
||||
// Client calls the API with one key, optionally scoped to a project.
|
||||
type Client struct {
|
||||
key, project, base string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(key, project string) *Client {
|
||||
return &Client{key: key, project: strings.TrimSpace(project), base: apiBase, http: &http.Client{Timeout: 60 * time.Second}}
|
||||
}
|
||||
|
||||
// WithBase points the client at another server (for tests).
|
||||
func (c *Client) WithBase(u string) *Client {
|
||||
c.base = strings.TrimRight(u, "/")
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Client) get(ctx context.Context, path string, q url.Values) (Object, error) {
|
||||
u := c.base + path
|
||||
if len(q) > 0 {
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.key)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if c.project != "" {
|
||||
req.Header.Set("x-origami-project", c.project)
|
||||
}
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode == http.StatusUnauthorized {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("origami.chat %s: HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body[:min(len(body), 300)])))
|
||||
}
|
||||
var out Object
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return nil, fmt.Errorf("origami.chat %s: %w", path, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// list pages through a list endpoint ({items, next_cursor}).
|
||||
func (c *Client) list(ctx context.Context, path string, q url.Values) ([]Object, error) {
|
||||
if q == nil {
|
||||
q = url.Values{}
|
||||
}
|
||||
q.Set("limit", "100")
|
||||
var all []Object
|
||||
for page := 0; page < 500; page++ {
|
||||
out, err := c.get(ctx, path, q)
|
||||
if err != nil {
|
||||
return all, err
|
||||
}
|
||||
items, _ := out["items"].([]any)
|
||||
for _, it := range items {
|
||||
if o, ok := it.(map[string]any); ok {
|
||||
all = append(all, o)
|
||||
}
|
||||
}
|
||||
next := out.Str("next_cursor")
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
q.Set("cursor", next)
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// Account checks the key; it returns the organization's name.
|
||||
func (c *Client) Account(ctx context.Context) (string, error) {
|
||||
out, err := c.get(ctx, "/account", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if n := out.Str("name", "org.name", "organization.name"); n != "" {
|
||||
return n, nil
|
||||
}
|
||||
return "the key works", nil
|
||||
}
|
||||
|
||||
// Campaigns lists every campaign.
|
||||
func (c *Client) Campaigns(ctx context.Context) ([]Object, error) {
|
||||
return c.list(ctx, "/send/campaigns", nil)
|
||||
}
|
||||
|
||||
// Stats are a campaign's counts and rates.
|
||||
func (c *Client) Stats(ctx context.Context, campaignID string) (Object, error) {
|
||||
return c.get(ctx, "/send/campaigns/"+url.PathEscape(campaignID)+"/stats", nil)
|
||||
}
|
||||
|
||||
// People lists a campaign's enrolled people.
|
||||
func (c *Client) People(ctx context.Context, campaignID string) ([]Object, error) {
|
||||
return c.list(ctx, "/send/campaigns/"+url.PathEscape(campaignID)+"/people", nil)
|
||||
}
|
||||
|
||||
// Replies lists replies from leads since a time (zero: all).
|
||||
func (c *Client) Replies(ctx context.Context, since time.Time) ([]Object, error) {
|
||||
q := url.Values{"from": {"lead"}}
|
||||
if !since.IsZero() {
|
||||
q.Set("since", since.UTC().Format(time.RFC3339))
|
||||
}
|
||||
return c.list(ctx, "/send/replies", q)
|
||||
}
|
||||
|
||||
// Sample returns the first campaign, its stats, one enrolled person and one
|
||||
// reply, as the API sent them, to check the field names against.
|
||||
func (c *Client) Sample(ctx context.Context) (map[string]any, error) {
|
||||
out := map[string]any{}
|
||||
camps, err := c.Campaigns(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["campaigns"] = len(camps)
|
||||
if len(camps) > 0 {
|
||||
out["campaign"] = camps[0]
|
||||
id := camps[0].Str("id")
|
||||
if st, err := c.Stats(ctx, id); err == nil {
|
||||
out["stats"] = st
|
||||
} else {
|
||||
out["stats_error"] = err.Error()
|
||||
}
|
||||
if p, err := c.get(ctx, "/send/campaigns/"+url.PathEscape(id)+"/people", url.Values{"limit": {"1"}}); err == nil {
|
||||
out["people"] = p
|
||||
} else {
|
||||
out["people_error"] = err.Error()
|
||||
}
|
||||
}
|
||||
if r, err := c.get(ctx, "/send/replies", url.Values{"limit": {"1"}, "from": {"lead"}}); err == nil {
|
||||
out["replies"] = r
|
||||
} else {
|
||||
out["replies_error"] = err.Error()
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Str is the first non-empty string (or number) among these fields; a
|
||||
// dotted name looks inside nested objects.
|
||||
func (o Object) Str(names ...string) string {
|
||||
for _, n := range names {
|
||||
var v any = map[string]any(o)
|
||||
for _, part := range strings.Split(n, ".") {
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
v = nil
|
||||
break
|
||||
}
|
||||
v = m[part]
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
if s := strings.TrimSpace(x); s != "" {
|
||||
return s
|
||||
}
|
||||
case float64:
|
||||
return strings.TrimSuffix(fmt.Sprintf("%f", x), ".000000")
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Num is the first numeric field among these names.
|
||||
func (o Object) Num(names ...string) (float64, bool) {
|
||||
for _, n := range names {
|
||||
var v any = map[string]any(o)
|
||||
for _, part := range strings.Split(n, ".") {
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
v = nil
|
||||
break
|
||||
}
|
||||
v = m[part]
|
||||
}
|
||||
if f, ok := v.(float64); ok {
|
||||
return f, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Time is the first field among these names that parses as a time.
|
||||
func (o Object) Time(names ...string) time.Time {
|
||||
for _, n := range names {
|
||||
if t := ParseTime(o.Str(n)); !t.IsZero() {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// ParseTime reads the ISO 8601 forms these APIs send.
|
||||
func ParseTime(s string) time.Time {
|
||||
for _, f := range []string{time.RFC3339Nano, "2006-01-02T15:04:05", "2006-01-02 15:04:05", "2006-01-02"} {
|
||||
if t, err := time.Parse(f, s); err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
@@ -220,6 +220,60 @@ CREATE TABLE suppressions (
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
PRIMARY KEY (kind, value)
|
||||
);
|
||||
`,
|
||||
// 7: buying signals and the funnel. A signal is a hypothesis about why a
|
||||
// company buys now; everything Supermarket and the outside tools do is
|
||||
// tagged with one, and every step through the funnel is an event.
|
||||
`
|
||||
CREATE TABLE signals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
slug TEXT NOT NULL UNIQUE, -- used as utm_campaign
|
||||
name TEXT NOT NULL,
|
||||
hypothesis TEXT NOT NULL DEFAULT '',
|
||||
spot TEXT NOT NULL DEFAULT '', -- how to find it: queries, keywords, one per line
|
||||
angle TEXT NOT NULL DEFAULT '', -- the pain and promise for messages and content
|
||||
status TEXT NOT NULL DEFAULT 'idea', -- idea, testing, proven, retired
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
|
||||
ALTER TABLE prospect_companies ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
|
||||
ALTER TABLE prospect_contacts ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
|
||||
|
||||
-- Campaigns in outside tools (origami.chat, explee.com), each assigned to a
|
||||
-- signal by the user.
|
||||
CREATE TABLE outside_campaigns (
|
||||
source TEXT NOT NULL, -- origami, explee
|
||||
id TEXT NOT NULL,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT '',
|
||||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||||
spend_cents INTEGER NOT NULL DEFAULT 0, -- lifetime, as the tool reports it
|
||||
stats TEXT NOT NULL DEFAULT '{}', -- JSON: the tool's own numbers
|
||||
synced_at TEXT NOT NULL,
|
||||
PRIMARY KEY (source, id)
|
||||
);
|
||||
|
||||
-- One row per step someone (or a group, for counts) took through the funnel.
|
||||
CREATE TABLE funnel_events (
|
||||
id INTEGER PRIMARY KEY,
|
||||
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
|
||||
stage TEXT NOT NULL, -- found, contacted, replied, interested, booked, visited, signed_up, paid
|
||||
channel TEXT NOT NULL, -- email, linkedin, social, blog, website, origami, explee, other
|
||||
subject TEXT NOT NULL DEFAULT '', -- who: contact:12, company:3, explee:<person>…
|
||||
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE, -- to tie it to the CRM and Stripe later
|
||||
campaign TEXT NOT NULL DEFAULT '', -- origami:<id>, explee:<id>; its signal is set there
|
||||
source TEXT NOT NULL, -- supermarket, manual, origami, explee
|
||||
external_id TEXT NOT NULL DEFAULT '', -- dedupes imports
|
||||
count INTEGER NOT NULL DEFAULT 1, -- for aggregate numbers (visits)
|
||||
value_cents INTEGER NOT NULL DEFAULT 0, -- for paid
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX funnel_events_external ON funnel_events (source, external_id) WHERE external_id != '';
|
||||
CREATE INDEX funnel_events_by_signal ON funnel_events (signal_id, stage, at);
|
||||
CREATE INDEX funnel_events_by_subject ON funnel_events (subject);
|
||||
CREATE INDEX funnel_events_by_campaign ON funnel_events (campaign);
|
||||
`,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package leadsource
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/explee"
|
||||
"supermarket/internal/api/origami"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
func openDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
func serve(t *testing.T, key string, routes map[string]any) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-API-Key") != key && r.Header.Get("Authorization") != "Bearer "+key {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
body, ok := routes[r.URL.Path]
|
||||
if !ok {
|
||||
t.Errorf("unexpected %s", r.URL)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(body)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
var now = time.Date(2026, 11, 21, 18, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestImportExplee(t *testing.T) {
|
||||
d := openDB(t)
|
||||
sig := &signals.Signal{Name: "Price rise", Status: signals.StatusTesting}
|
||||
signals.Save(d, sig)
|
||||
srv := serve(t, "k", map[string]any{
|
||||
"/autogtm/campaigns": map[string]any{"campaigns": []any{
|
||||
map[string]any{"id": 7, "name": "M365 movers", "status": "outreach", "target_url": "https://cal.example/x"},
|
||||
}},
|
||||
"/autogtm/campaigns/7/analytics": map[string]any{"status": "sending", "emails_sent": 40, "total_replies": 3,
|
||||
"hot_leads": 1, "spend_usd": 12.5},
|
||||
"/autogtm/campaigns/7/leads": map[string]any{"has_more": false, "leads": []any{
|
||||
map[string]any{"person_id": "p1", "email": "pat@acme.example", "first_sent_at": "2026-11-01T10:00:00Z",
|
||||
"replied": true, "last_reply_at": "2026-11-02T09:00:00Z", "status": "Hot"},
|
||||
map[string]any{"person_id": "p2", "email": "sam@other.example", "first_sent_at": "2026-11-01T10:00:00Z", "unsubscribed": true},
|
||||
map[string]any{"person_id": "p3", "erased": true, "first_sent_at": "2026-11-01T10:00:00Z"},
|
||||
}},
|
||||
"/autogtm/hot-leads": map[string]any{"has_more": false, "leads": []any{
|
||||
map[string]any{"person_id": "p1", "campaign_id": 7, "name": "Pat Lee", "email": "pat@acme.example",
|
||||
"job_title": "CTO", "company_name": "Acme", "company_domain": "acme.example",
|
||||
"why_hot": "Yes, let's talk next week.", "became_hot_at": "2026-11-02T09:05:00Z"},
|
||||
}},
|
||||
})
|
||||
c := explee.New("k").WithBase(srv.URL)
|
||||
|
||||
r, err := ImportExplee(context.Background(), d, c, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 3 contacted + 1 replied + 1 interested (the hot lead repeats it).
|
||||
if r.Campaigns != 1 || r.Events != 5 || r.Prospects != 1 || r.Suppressed != 1 || len(r.Warnings) != 0 {
|
||||
t.Fatalf("result: %+v", r)
|
||||
}
|
||||
if sup, _ := prospects.IsSuppressed(d, "sam@other.example", ""); !sup {
|
||||
t.Error("the unsubscribe wasn't suppressed")
|
||||
}
|
||||
cs, _, _ := prospects.Review(d, prospects.StatusNew, 0, 10)
|
||||
if len(cs) != 1 || cs[0].Name != "Acme" || len(cs[0].Contacts) != 1 || cs[0].Contacts[0].Title != "CTO" ||
|
||||
cs[0].Source != signals.SourceExplee {
|
||||
t.Fatalf("prospects: %+v", cs)
|
||||
}
|
||||
|
||||
// Assigning the campaign tags its events; the next import tags the
|
||||
// prospect too, and adds nothing twice.
|
||||
if err := signals.AssignCampaign(d, signals.SourceExplee, "7", sig.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err = ImportExplee(context.Background(), d, c, now)
|
||||
if err != nil || r.Events != 0 || r.Prospects != 0 || r.Suppressed != 0 {
|
||||
t.Fatalf("second import: %+v %v", r, err)
|
||||
}
|
||||
if c, _ := prospects.GetCompany(d, cs[0].ID); c.SignalID != sig.ID || c.Contacts[0].SignalID != sig.ID {
|
||||
t.Errorf("prospect not tagged: %+v", c)
|
||||
}
|
||||
rows, _ := signals.Scorecard(d, signals.Filter{})
|
||||
if rows[0].Signal.ID != sig.ID || rows[0].Counts[signals.StageContacted] != 3 || rows[0].Counts[signals.StageInterested] != 1 ||
|
||||
rows[0].SpendCents != 1250 {
|
||||
t.Errorf("scorecard: %+v spend %d", rows[0].Counts, rows[0].SpendCents)
|
||||
}
|
||||
if last, _ := Last(d, signals.SourceExplee); last == nil || last.Campaigns != 1 {
|
||||
t.Errorf("last: %+v", last)
|
||||
}
|
||||
|
||||
if _, err := ImportExplee(context.Background(), d, explee.New("wrong").WithBase(srv.URL), now); err != explee.ErrUnauthorized {
|
||||
t.Errorf("bad key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportOrigami(t *testing.T) {
|
||||
d := openDB(t)
|
||||
srv := serve(t, "og", map[string]any{
|
||||
"/send/campaigns": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
|
||||
map[string]any{"object": "campaign", "id": "c1", "name": "Self-hosters", "status": "active"},
|
||||
}},
|
||||
"/send/campaigns/c1/stats": map[string]any{"object": "campaign_stats", "sent": 20, "replies": 2,
|
||||
"rates": map[string]any{"reply": 0.1}},
|
||||
"/send/campaigns/c1/people": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
|
||||
map[string]any{"sequence_id": "s1", "status": "replied", "first_name": "Ana", "last_name": "Ruiz",
|
||||
"email": "ana@coop.example", "company": "Co-op", "company_domain": "coop.example", "first_sent_at": "2026-11-03T08:00:00Z"},
|
||||
map[string]any{"sequence_id": "s2", "status": "unsubscribed", "email": "no@thanks.example"},
|
||||
map[string]any{"sequence_id": "s3", "status": "scheduled"},
|
||||
}},
|
||||
"/send/replies": map[string]any{"object": "list", "next_cursor": nil, "items": []any{
|
||||
map[string]any{"sequence_id": "s1", "campaign_id": "c1", "received_at": "2026-11-04T08:00:00Z", "body": "Sounds interesting"},
|
||||
map[string]any{"sequence_id": "s1", "campaign_id": "c1", "received_at": "2026-11-03T12:00:00Z", "body": "Tell me more"},
|
||||
}},
|
||||
})
|
||||
c := origami.New("og", "").WithBase(srv.URL)
|
||||
r, err := ImportOrigami(context.Background(), d, c, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// s1 and s2 contacted (s3 is only scheduled), s1 replied once.
|
||||
if r.Campaigns != 1 || r.Events != 3 || r.Prospects != 1 || r.Suppressed != 1 {
|
||||
t.Fatalf("result: %+v", r)
|
||||
}
|
||||
evs, _ := signals.SubjectEvents(d, "origami:s1")
|
||||
if len(evs) != 2 || evs[1].Stage != signals.StageReplied || !evs[1].At.Equal(time.Date(2026, 11, 3, 12, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("s1 events: %+v", evs)
|
||||
}
|
||||
cs, _ := signals.Campaigns(d)
|
||||
if len(cs) != 1 || cs[0].Stats["sent"] != float64(20) || cs[0].Stats["rates reply"] != 0.1 {
|
||||
t.Errorf("campaign: %+v", cs)
|
||||
}
|
||||
sample, err := c.Sample(context.Background())
|
||||
if err != nil || sample["campaigns"] != 1 || sample["stats"] == nil {
|
||||
t.Errorf("sample: %+v %v", sample, err)
|
||||
}
|
||||
}
|
||||
+112
-17
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -48,6 +49,7 @@ type Company struct {
|
||||
DecidedAt time.Time
|
||||
ActionID int64
|
||||
CRM CRMState
|
||||
SignalID int64 // the buying signal it was found for; 0: none
|
||||
|
||||
Contacts []Contact // filled in by Review and GetCompany
|
||||
}
|
||||
@@ -70,6 +72,7 @@ type Contact struct {
|
||||
DecidedAt time.Time
|
||||
ActionID int64
|
||||
CRM CRMState
|
||||
SignalID int64
|
||||
}
|
||||
|
||||
// CRMState is how the CRM action an accepted prospect queued is doing.
|
||||
@@ -156,13 +159,46 @@ func AddCompany(d *db.DB, c Company, now time.Time) (id int64, added bool, err e
|
||||
}
|
||||
}
|
||||
res, err := d.Exec(`INSERT INTO prospect_companies (name, domain, website, linkedin, industry, size, location, why,
|
||||
source, source_detail, found_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
c.Name, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, c.Source, c.SourceDetail, formatTime(now))
|
||||
source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
c.Name, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, c.Source, c.SourceDetail, formatTime(now),
|
||||
nullID(c.SignalID))
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
return id, true, err
|
||||
if id, err = res.LastInsertId(); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
return id, true, found(d, "company", id, c.SignalID, c.Source, "", now)
|
||||
}
|
||||
|
||||
func nullID(id int64) any {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Subject is how funnel events refer to a prospect.
|
||||
func Subject(kind string, id int64) string { return kind + ":" + strconv.FormatInt(id, 10) }
|
||||
|
||||
// channelOf is the funnel channel a prospect source belongs to.
|
||||
func channelOf(source string) string {
|
||||
switch source {
|
||||
case signals.SourceOrigami, signals.SourceExplee:
|
||||
return source
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
|
||||
// found records that a prospect turned up. A company counts once, with its
|
||||
// people; a person on their own counts once.
|
||||
func found(d *db.DB, kind string, id, signalID int64, source, email string, now time.Time) error {
|
||||
_, err := signals.Record(d, signals.Event{
|
||||
SignalID: signalID, Stage: signals.StageFound, Channel: channelOf(source),
|
||||
Subject: Subject(kind, id), Email: email, Source: signals.SourceSupermarket,
|
||||
ExternalID: "found:" + Subject(kind, id), At: now,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// AddContact stores a person for review. A contact with the same email is
|
||||
@@ -186,7 +222,8 @@ func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err e
|
||||
domain := crm.EmailDomain(c.Email)
|
||||
if c.CompanyID != 0 {
|
||||
var cd string
|
||||
if err := d.QueryRow(`SELECT domain FROM prospect_companies WHERE id = ?`, c.CompanyID).Scan(&cd); err != nil {
|
||||
var companySignal int64
|
||||
if err := d.QueryRow(`SELECT domain, coalesce(signal_id, 0) FROM prospect_companies WHERE id = ?`, c.CompanyID).Scan(&cd, &companySignal); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, false, ErrNotFound
|
||||
}
|
||||
@@ -198,6 +235,9 @@ func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err e
|
||||
}
|
||||
return 0, false, err
|
||||
}
|
||||
if c.SignalID == 0 {
|
||||
c.SignalID = companySignal
|
||||
}
|
||||
}
|
||||
if sup, err := IsSuppressed(d, c.Email, domain); err != nil || sup {
|
||||
if err == nil {
|
||||
@@ -228,20 +268,72 @@ func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err e
|
||||
}
|
||||
}
|
||||
res, err := d.Exec(`INSERT INTO prospect_contacts (company_id, first_name, last_name, title, email, email_status,
|
||||
linkedin, phone, source, source_detail, found_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
company, c.FirstName, c.LastName, c.Title, c.Email, c.EmailStatus, c.LinkedIn, c.Phone, c.Source, c.SourceDetail, formatTime(now))
|
||||
linkedin, phone, source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
company, c.FirstName, c.LastName, c.Title, c.Email, c.EmailStatus, c.LinkedIn, c.Phone, c.Source, c.SourceDetail, formatTime(now),
|
||||
nullID(c.SignalID))
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
if id, err = res.LastInsertId(); err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if c.CompanyID == 0 {
|
||||
err = found(d, "contact", id, c.SignalID, c.Source, c.Email, now)
|
||||
}
|
||||
return id, true, err
|
||||
}
|
||||
|
||||
// SetSignal changes the signal a company or person is tagged with (0:
|
||||
// none), and moves their funnel events with them. A company's people who
|
||||
// had the company's old signal follow it.
|
||||
func SetSignal(d *db.DB, kind string, id, signalID int64) error {
|
||||
table, err := table(kind)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var old int64
|
||||
if err := d.QueryRow(`SELECT coalesce(signal_id, 0) FROM `+table+` WHERE id = ?`, id).Scan(&old); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
if _, err := d.Exec(`UPDATE `+table+` SET signal_id = ? WHERE id = ?`, nullID(signalID), id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := signals.RetagSubject(d, Subject(kind, id), signalID); err != nil {
|
||||
return err
|
||||
}
|
||||
if kind != "company" {
|
||||
return nil
|
||||
}
|
||||
rows, err := d.Query(`SELECT id FROM prospect_contacts WHERE company_id = ? AND coalesce(signal_id, 0) = ?`, id, old)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var people []int64
|
||||
for rows.Next() {
|
||||
var pid int64
|
||||
if err := rows.Scan(&pid); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
people = append(people, pid)
|
||||
}
|
||||
rows.Close()
|
||||
for _, pid := range people {
|
||||
if err := SetSignal(d, "contact", pid, signalID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Reading ---
|
||||
|
||||
const companyColumns = `c.id, c.name, c.domain, c.website, c.linkedin, c.industry, c.size, c.location, c.why,
|
||||
c.source, c.source_detail, c.found_at, c.status, c.decided_at, coalesce(c.action_id, 0),
|
||||
coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, '')`
|
||||
coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, ''), coalesce(c.signal_id, 0)`
|
||||
|
||||
const companyFrom = ` FROM prospect_companies c LEFT JOIN crm_actions a ON a.id = c.action_id`
|
||||
|
||||
@@ -254,7 +346,7 @@ func scanCompanies(rows *sql.Rows) ([]Company, error) {
|
||||
var decided sql.NullString
|
||||
if err := rows.Scan(&c.ID, &c.Name, &c.Domain, &c.Website, &c.LinkedIn, &c.Industry, &c.Size, &c.Location, &c.Why,
|
||||
&c.Source, &c.SourceDetail, &found, &c.Status, &decided, &c.ActionID,
|
||||
&c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error); err != nil {
|
||||
&c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error, &c.SignalID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.FoundAt, _ = time.Parse(timeFormat, found)
|
||||
@@ -266,7 +358,7 @@ func scanCompanies(rows *sql.Rows) ([]Company, error) {
|
||||
|
||||
const contactColumns = `p.id, coalesce(p.company_id, 0), p.first_name, p.last_name, p.title, p.email, p.email_status,
|
||||
p.linkedin, p.phone, p.source, p.source_detail, p.found_at, p.status, p.decided_at, coalesce(p.action_id, 0),
|
||||
coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, '')`
|
||||
coalesce(a.status, ''), coalesce(a.outcome, ''), coalesce(a.espo_id, ''), coalesce(a.error, ''), coalesce(p.signal_id, 0)`
|
||||
|
||||
const contactFrom = ` FROM prospect_contacts p LEFT JOIN crm_actions a ON a.id = p.action_id`
|
||||
|
||||
@@ -279,7 +371,7 @@ func scanContacts(rows *sql.Rows) ([]Contact, error) {
|
||||
var decided sql.NullString
|
||||
if err := rows.Scan(&c.ID, &c.CompanyID, &c.FirstName, &c.LastName, &c.Title, &c.Email, &c.EmailStatus,
|
||||
&c.LinkedIn, &c.Phone, &c.Source, &c.SourceDetail, &found, &c.Status, &decided, &c.ActionID,
|
||||
&c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error); err != nil {
|
||||
&c.CRM.Status, &c.CRM.Outcome, &c.CRM.EspoID, &c.CRM.Error, &c.SignalID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.FoundAt, _ = time.Parse(timeFormat, found)
|
||||
@@ -328,14 +420,16 @@ func GetContact(d *db.DB, id int64) (*Contact, error) {
|
||||
return &cs[0], nil
|
||||
}
|
||||
|
||||
// Review lists what the review screen shows for one status: companies
|
||||
// Review lists what the review screen shows for one status (and one
|
||||
// signal, unless signalID is 0): companies
|
||||
// with that status or with contacts that have it (with only those
|
||||
// contacts), and contacts with that status who aren't at a company.
|
||||
// Newest first.
|
||||
func Review(d *db.DB, status string, limit int) ([]Company, []Contact, error) {
|
||||
func Review(d *db.DB, status string, signalID int64, limit int) ([]Company, []Contact, error) {
|
||||
rows, err := d.Query(`SELECT `+companyColumns+companyFrom+`
|
||||
WHERE c.status = ? OR EXISTS (SELECT 1 FROM prospect_contacts p WHERE p.company_id = c.id AND p.status = ?)
|
||||
ORDER BY c.id DESC LIMIT ?`, status, status, limit)
|
||||
WHERE (c.status = ? OR EXISTS (SELECT 1 FROM prospect_contacts p WHERE p.company_id = c.id AND p.status = ?))
|
||||
AND (? = 0 OR c.signal_id = ?)
|
||||
ORDER BY c.id DESC LIMIT ?`, status, status, signalID, signalID, limit)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -365,7 +459,8 @@ func Review(d *db.DB, status string, limit int) ([]Company, []Contact, error) {
|
||||
}
|
||||
}
|
||||
rows, err = d.Query(`SELECT `+contactColumns+contactFrom+`
|
||||
WHERE p.status = ? AND p.company_id IS NULL ORDER BY p.id DESC LIMIT ?`, status, limit)
|
||||
WHERE p.status = ? AND p.company_id IS NULL AND (? = 0 OR p.signal_id = ?) ORDER BY p.id DESC LIMIT ?`,
|
||||
status, signalID, signalID, limit)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -114,12 +114,12 @@ func TestReviewAndReject(t *testing.T) {
|
||||
p2, _, _ := AddContact(d, Contact{CompanyID: cid, LastName: "Two", Source: SourceManual}, now)
|
||||
loose, _, _ := AddContact(d, Contact{LastName: "Loose", Email: "l@else.org", Source: SourceManual}, now)
|
||||
|
||||
cs, ps, err := Review(d, StatusNew, 50)
|
||||
cs, ps, err := Review(d, StatusNew, 0, 50)
|
||||
if err != nil || len(cs) != 1 || len(cs[0].Contacts) != 2 || len(ps) != 1 || ps[0].ID != loose {
|
||||
t.Fatalf("new: %+v %+v %v", cs, ps, err)
|
||||
}
|
||||
AcceptContact(d, p1, now)
|
||||
cs, _, _ = Review(d, StatusAccepted, 50)
|
||||
cs, _, _ = Review(d, StatusAccepted, 0, 50)
|
||||
if len(cs) != 1 || len(cs[0].Contacts) != 1 || cs[0].Contacts[0].ID != p1 {
|
||||
t.Errorf("accepted tab: %+v", cs)
|
||||
}
|
||||
|
||||
@@ -32,6 +32,9 @@ const (
|
||||
|
||||
YouTubeAPIKey = "youtube.api_key"
|
||||
|
||||
OrigamiAPIKey = "origami.api_key"
|
||||
ExpleeAPIKey = "explee.api_key"
|
||||
|
||||
RedditClientID = "reddit.client_id"
|
||||
RedditClientSecret = "reddit.client_secret"
|
||||
RedditAccessToken = "reddit.access_token"
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
package signals
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Stages of the funnel, in order. Each is a success where it happens.
|
||||
const (
|
||||
StageFound = "found" // a prospect turned up
|
||||
StageContacted = "contacted" // an email or message went out, or a post reached them
|
||||
StageReplied = "replied" // they wrote back
|
||||
StageInterested = "interested" // the reply was positive (a "hot lead")
|
||||
StageBooked = "booked" // clicked the scheduling link, or booked
|
||||
StageVisited = "visited" // came to the website or a landing page
|
||||
StageSignedUp = "signed_up" // a trial or the free tier
|
||||
StagePaid = "paid" // the biggest success
|
||||
)
|
||||
|
||||
// Stage is a funnel stage and how it's shown.
|
||||
type Stage struct{ ID, Label string }
|
||||
|
||||
var Stages = []Stage{
|
||||
{StageFound, "Found"},
|
||||
{StageContacted, "Contacted"},
|
||||
{StageReplied, "Replied"},
|
||||
{StageInterested, "Interested"},
|
||||
{StageBooked, "Booked"},
|
||||
{StageVisited, "Visited"},
|
||||
{StageSignedUp, "Signed up"},
|
||||
{StagePaid, "Paid"},
|
||||
}
|
||||
|
||||
// StageLabel is how a stage is shown.
|
||||
func StageLabel(id string) string {
|
||||
for _, s := range Stages {
|
||||
if s.ID == id {
|
||||
return s.Label
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func validStage(id string) bool {
|
||||
for _, s := range Stages {
|
||||
if s.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Channels: direct (email, LinkedIn), indirect (social, blog, website), and
|
||||
// the outside tools.
|
||||
var Channels = []Stage{
|
||||
{"email", "Email"},
|
||||
{"linkedin", "LinkedIn"},
|
||||
{"social", "Social posts"},
|
||||
{"blog", "Blog"},
|
||||
{"website", "Website"},
|
||||
{"origami", "origami.chat"},
|
||||
{"explee", "explee.com"},
|
||||
{"other", "Other"},
|
||||
}
|
||||
|
||||
// ChannelLabel is how a channel is shown.
|
||||
func ChannelLabel(id string) string {
|
||||
for _, c := range Channels {
|
||||
if c.ID == id {
|
||||
return c.Label
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func validChannel(id string) bool {
|
||||
for _, c := range Channels {
|
||||
if c.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Event sources.
|
||||
const (
|
||||
SourceSupermarket = "supermarket" // recorded by Supermarket itself
|
||||
SourceManual = "manual" // recorded by the user
|
||||
SourceOrigami = "origami"
|
||||
SourceExplee = "explee"
|
||||
)
|
||||
|
||||
// Event is one step through the funnel.
|
||||
type Event struct {
|
||||
ID int64
|
||||
SignalID int64 // 0: none
|
||||
Stage string
|
||||
Channel string
|
||||
Subject string // contact:12, company:3, explee:<person>…
|
||||
Email string
|
||||
Campaign string // origami:<id>, explee:<id>
|
||||
Source string
|
||||
ExternalID string // dedupes imports: the same ID is recorded once
|
||||
Count int // 1 for a person; more for aggregate numbers
|
||||
ValueCents int64 // for paid
|
||||
Note string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
func nullID(id int64) any {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Record stores an event. One with an external ID already recorded from the
|
||||
// same source is skipped, and added is false.
|
||||
func Record(d *db.DB, e Event) (added bool, err error) {
|
||||
if !validStage(e.Stage) {
|
||||
return false, fmt.Errorf("unknown stage %q", e.Stage)
|
||||
}
|
||||
if !validChannel(e.Channel) {
|
||||
return false, fmt.Errorf("unknown channel %q", e.Channel)
|
||||
}
|
||||
if e.Source == "" {
|
||||
return false, errors.New("an event needs a source")
|
||||
}
|
||||
if e.Count <= 0 {
|
||||
e.Count = 1
|
||||
}
|
||||
if e.At.IsZero() {
|
||||
e.At = time.Now()
|
||||
}
|
||||
res, err := d.Exec(`INSERT INTO funnel_events (signal_id, stage, channel, subject, email, campaign, source, external_id,
|
||||
count, value_cents, note, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (source, external_id) WHERE external_id != '' DO NOTHING`,
|
||||
nullID(e.SignalID), e.Stage, e.Channel, e.Subject, strings.ToLower(strings.TrimSpace(e.Email)), e.Campaign, e.Source,
|
||||
e.ExternalID, e.Count, e.ValueCents, strings.TrimSpace(e.Note), formatTime(e.At))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// DeleteEvent removes an event the user recorded by hand.
|
||||
func DeleteEvent(d *db.DB, id int64) error {
|
||||
res, err := d.Exec(`DELETE FROM funnel_events WHERE id = ? AND source = 'manual'`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return errors.New("only outcomes you recorded yourself can be removed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const eventColumns = `id, coalesce(signal_id, 0), stage, channel, subject, email, campaign, source, external_id,
|
||||
count, value_cents, note, at`
|
||||
|
||||
func scanEvents(rows *sql.Rows) ([]Event, error) {
|
||||
defer rows.Close()
|
||||
var out []Event
|
||||
for rows.Next() {
|
||||
var e Event
|
||||
var at string
|
||||
if err := rows.Scan(&e.ID, &e.SignalID, &e.Stage, &e.Channel, &e.Subject, &e.Email, &e.Campaign, &e.Source,
|
||||
&e.ExternalID, &e.Count, &e.ValueCents, &e.Note, &at); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.At, _ = time.Parse(timeFormat, at)
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SubjectEvents are the events about these subjects, oldest first.
|
||||
func SubjectEvents(d *db.DB, subjects ...string) ([]Event, error) {
|
||||
if len(subjects) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
args := make([]any, len(subjects))
|
||||
for i, s := range subjects {
|
||||
args[i] = s
|
||||
}
|
||||
rows, err := d.Query(`SELECT `+eventColumns+` FROM funnel_events WHERE subject IN (?`+
|
||||
strings.Repeat(", ?", len(subjects)-1)+`) ORDER BY at, id`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return scanEvents(rows)
|
||||
}
|
||||
|
||||
// RecentEvents are the newest events, for a signal (0: all).
|
||||
func RecentEvents(d *db.DB, signalID int64, limit int) ([]Event, error) {
|
||||
q := `SELECT ` + eventColumns + ` FROM funnel_events`
|
||||
args := []any{}
|
||||
if signalID != 0 {
|
||||
q += ` WHERE signal_id = ?`
|
||||
args = append(args, signalID)
|
||||
}
|
||||
rows, err := d.Query(q+` ORDER BY at DESC, id DESC LIMIT ?`, append(args, limit)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return scanEvents(rows)
|
||||
}
|
||||
|
||||
// RetagSubject moves a subject's events to another signal, when its
|
||||
// prospect's signal changes. Events from a campaign keep the campaign's.
|
||||
func RetagSubject(d *db.DB, subject string, signalID int64) error {
|
||||
_, err := d.Exec(`UPDATE funnel_events SET signal_id = ? WHERE subject = ? AND campaign = ''`, nullID(signalID), subject)
|
||||
return err
|
||||
}
|
||||
|
||||
// --- Campaigns in outside tools ---
|
||||
|
||||
// Campaign is a campaign in origami.chat or explee.com.
|
||||
type Campaign struct {
|
||||
Source string
|
||||
ID string
|
||||
Name string
|
||||
Status string
|
||||
SignalID int64
|
||||
SpendCents int64
|
||||
Stats map[string]any
|
||||
SyncedAt time.Time
|
||||
}
|
||||
|
||||
// Key is how events refer to the campaign.
|
||||
func (c *Campaign) Key() string { return c.Source + ":" + c.ID }
|
||||
|
||||
// SaveCampaign stores what a tool says about a campaign, keeping the signal
|
||||
// the user gave it.
|
||||
func SaveCampaign(d *db.DB, c Campaign) error {
|
||||
stats, err := json.Marshal(c.Stats)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = d.Exec(`INSERT INTO outside_campaigns (source, id, name, status, spend_cents, stats, synced_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (source, id) DO UPDATE SET name = excluded.name, status = excluded.status,
|
||||
spend_cents = excluded.spend_cents, stats = excluded.stats, synced_at = excluded.synced_at`,
|
||||
c.Source, c.ID, c.Name, c.Status, c.SpendCents, string(stats), formatTime(c.SyncedAt))
|
||||
return err
|
||||
}
|
||||
|
||||
// CampaignSignal is the signal a campaign is assigned to, or 0.
|
||||
func CampaignSignal(d *db.DB, source, id string) (int64, error) {
|
||||
var sig int64
|
||||
err := d.QueryRow(`SELECT coalesce(signal_id, 0) FROM outside_campaigns WHERE source = ? AND id = ?`, source, id).Scan(&sig)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, nil
|
||||
}
|
||||
return sig, err
|
||||
}
|
||||
|
||||
// AssignCampaign gives a campaign a signal (0: none), and moves its events.
|
||||
func AssignCampaign(d *db.DB, source, id string, signalID int64) error {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
res, err := tx.Exec(`UPDATE outside_campaigns SET signal_id = ? WHERE source = ? AND id = ?`, nullID(signalID), source, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return errors.New("no such campaign")
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE funnel_events SET signal_id = ? WHERE campaign = ?`, nullID(signalID), source+":"+id); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Campaigns lists the outside campaigns, unassigned first, newest sync first.
|
||||
func Campaigns(d *db.DB) ([]Campaign, error) {
|
||||
rows, err := d.Query(`SELECT source, id, name, status, coalesce(signal_id, 0), spend_cents, stats, synced_at
|
||||
FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Campaign
|
||||
for rows.Next() {
|
||||
var c Campaign
|
||||
var stats, synced string
|
||||
if err := rows.Scan(&c.Source, &c.ID, &c.Name, &c.Status, &c.SignalID, &c.SpendCents, &stats, &synced); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(stats), &c.Stats)
|
||||
c.SyncedAt, _ = time.Parse(timeFormat, synced)
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// --- The scorecard ---
|
||||
|
||||
// Row is one signal's line on the scorecard.
|
||||
type Row struct {
|
||||
Signal *Signal // nil: events without a signal
|
||||
Counts map[string]int
|
||||
RevenueCents int64
|
||||
SpendCents int64 // what the outside tools report spending on its campaigns (lifetime)
|
||||
}
|
||||
|
||||
// Cell is one stage's number on a row.
|
||||
type Cell struct {
|
||||
Stage string
|
||||
Count int
|
||||
Rate string // as a share of those contacted, for later stages
|
||||
}
|
||||
|
||||
// Cells are the row's numbers in stage order.
|
||||
func (r *Row) Cells() []Cell {
|
||||
contacted := r.Counts[StageContacted]
|
||||
out := make([]Cell, len(Stages))
|
||||
past := false
|
||||
for i, s := range Stages {
|
||||
c := Cell{Stage: s.ID, Count: r.Counts[s.ID]}
|
||||
if past && contacted > 0 && c.Count > 0 && s.ID != StageVisited {
|
||||
c.Rate = fmt.Sprintf("%.0f%%", 100*float64(c.Count)/float64(contacted))
|
||||
}
|
||||
if s.ID == StageContacted {
|
||||
past = true
|
||||
}
|
||||
out[i] = c
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Total is the number of events on the row.
|
||||
func (r *Row) Total() int {
|
||||
n := 0
|
||||
for _, c := range r.Counts {
|
||||
n += c
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Filter narrows the scorecard.
|
||||
type Filter struct {
|
||||
Since time.Time // zero: all time
|
||||
Channel string // "": all
|
||||
}
|
||||
|
||||
// Scorecard counts each signal's funnel. A person counts once per stage
|
||||
// however many events they have; aggregate events add their count.
|
||||
func Scorecard(d *db.DB, f Filter) ([]Row, error) {
|
||||
list, err := List(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := make([]Row, 0, len(list)+1)
|
||||
index := map[int64]int{}
|
||||
for i := range list {
|
||||
index[list[i].ID] = len(rows)
|
||||
rows = append(rows, Row{Signal: &list[i], Counts: map[string]int{}})
|
||||
}
|
||||
index[0] = len(rows)
|
||||
rows = append(rows, Row{Counts: map[string]int{}})
|
||||
|
||||
where, args := []string{"1 = 1"}, []any{}
|
||||
if !f.Since.IsZero() {
|
||||
where = append(where, "at >= ?")
|
||||
args = append(args, formatTime(f.Since))
|
||||
}
|
||||
if f.Channel != "" {
|
||||
where = append(where, "channel = ?")
|
||||
args = append(args, f.Channel)
|
||||
}
|
||||
q, err := d.Query(`SELECT coalesce(signal_id, 0), stage,
|
||||
count(DISTINCT CASE WHEN subject != '' THEN subject END) + sum(CASE WHEN subject = '' THEN count ELSE 0 END),
|
||||
sum(CASE WHEN stage = 'paid' THEN value_cents ELSE 0 END)
|
||||
FROM funnel_events WHERE `+strings.Join(where, " AND ")+` GROUP BY 1, 2`, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer q.Close()
|
||||
for q.Next() {
|
||||
var sig, value int64
|
||||
var stage string
|
||||
var n int
|
||||
if err := q.Scan(&sig, &stage, &n, &value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i, ok := index[sig]
|
||||
if !ok {
|
||||
i = index[0]
|
||||
}
|
||||
rows[i].Counts[stage] += n
|
||||
rows[i].RevenueCents += value
|
||||
}
|
||||
if err := q.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.Channel == "" || f.Channel == SourceOrigami || f.Channel == SourceExplee {
|
||||
sq, err := d.Query(`SELECT coalesce(signal_id, 0), sum(spend_cents) FROM outside_campaigns
|
||||
WHERE ? = '' OR source = ? GROUP BY 1`, f.Channel, f.Channel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer sq.Close()
|
||||
for sq.Next() {
|
||||
var sig, spend int64
|
||||
if err := sq.Scan(&sig, &spend); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if i, ok := index[sig]; ok {
|
||||
rows[i].SpendCents += spend
|
||||
}
|
||||
}
|
||||
if err := sq.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// The "no signal" row only when it has something.
|
||||
if last := rows[len(rows)-1]; last.Total() == 0 && last.SpendCents == 0 {
|
||||
rows = rows[:len(rows)-1]
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Package signals keeps the buying signals (hypotheses about why a company
|
||||
// buys now) and the funnel: every step someone takes, from being found to
|
||||
// paying, recorded as an event tagged with a signal and a channel. The
|
||||
// scorecard counts them, so signals can be tested against what was done
|
||||
// for them, directly (email, LinkedIn) and indirectly (posts, pages).
|
||||
package signals
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Statuses of a signal, in order.
|
||||
const (
|
||||
StatusIdea = "idea"
|
||||
StatusTesting = "testing"
|
||||
StatusProven = "proven"
|
||||
StatusRetired = "retired"
|
||||
)
|
||||
|
||||
var Statuses = []string{StatusIdea, StatusTesting, StatusProven, StatusRetired}
|
||||
|
||||
// Signal is one buying signal.
|
||||
type Signal struct {
|
||||
ID int64
|
||||
Slug string // utm_campaign
|
||||
Name string
|
||||
Hypothesis string
|
||||
Spot string // how to find it: queries and keywords, one per line
|
||||
Angle string // the pain and promise for messages and content
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// SpotLines are the non-empty lines of Spot.
|
||||
func (s *Signal) SpotLines() []string {
|
||||
var out []string
|
||||
for _, l := range strings.Split(s.Spot, "\n") {
|
||||
if l = strings.TrimSpace(l); l != "" {
|
||||
out = append(out, l)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ErrNotFound means there's no signal with that ID.
|
||||
var ErrNotFound = errors.New("no such signal")
|
||||
|
||||
const timeFormat = time.RFC3339
|
||||
|
||||
func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) }
|
||||
|
||||
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
|
||||
// Slugify makes a utm_campaign-safe slug from a name.
|
||||
func Slugify(name string) string {
|
||||
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-")
|
||||
if len(s) > 60 {
|
||||
s = strings.TrimRight(s[:60], "-")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func validStatus(s string) bool {
|
||||
for _, st := range Statuses {
|
||||
if s == st {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Save creates or updates a signal. An empty slug is made from the name;
|
||||
// slugs are unique, so a taken one gets a number.
|
||||
func Save(d *db.DB, s *Signal) error {
|
||||
s.Name = strings.TrimSpace(s.Name)
|
||||
s.Hypothesis = strings.TrimSpace(s.Hypothesis)
|
||||
s.Spot = strings.TrimSpace(s.Spot)
|
||||
s.Angle = strings.TrimSpace(s.Angle)
|
||||
if s.Name == "" {
|
||||
return errors.New("a signal needs a name")
|
||||
}
|
||||
if s.Status == "" {
|
||||
s.Status = StatusIdea
|
||||
}
|
||||
if !validStatus(s.Status) {
|
||||
return fmt.Errorf("unknown status %q", s.Status)
|
||||
}
|
||||
s.Slug = Slugify(s.Slug)
|
||||
if s.Slug == "" {
|
||||
s.Slug = Slugify(s.Name)
|
||||
}
|
||||
if s.Slug == "" {
|
||||
return errors.New("the name needs some letters or digits, for the campaign tag")
|
||||
}
|
||||
base := s.Slug
|
||||
for i := 2; ; i++ {
|
||||
var other int64
|
||||
err := d.QueryRow(`SELECT id FROM signals WHERE slug = ?`, s.Slug).Scan(&other)
|
||||
if errors.Is(err, sql.ErrNoRows) || other == s.ID {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.Slug = fmt.Sprintf("%s-%d", base, i)
|
||||
}
|
||||
now := formatTime(time.Now())
|
||||
if s.ID == 0 {
|
||||
res, err := d.Exec(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.ID, err = res.LastInsertId()
|
||||
return err
|
||||
}
|
||||
res, err := d.Exec(`UPDATE signals SET slug = ?, name = ?, hypothesis = ?, spot = ?, angle = ?, status = ?, updated_at = ?
|
||||
WHERE id = ?`, s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, s.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete removes a signal. Its prospects, campaigns and events stay, without
|
||||
// a signal.
|
||||
func Delete(d *db.DB, id int64) error {
|
||||
_, err := d.Exec(`DELETE FROM signals WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const columns = `id, slug, name, hypothesis, spot, angle, status, created_at, updated_at`
|
||||
|
||||
func scan(rows *sql.Rows) ([]Signal, error) {
|
||||
defer rows.Close()
|
||||
var out []Signal
|
||||
for rows.Next() {
|
||||
var s Signal
|
||||
var created, updated string
|
||||
if err := rows.Scan(&s.ID, &s.Slug, &s.Name, &s.Hypothesis, &s.Spot, &s.Angle, &s.Status, &created, &updated); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.CreatedAt, _ = time.Parse(timeFormat, created)
|
||||
s.UpdatedAt, _ = time.Parse(timeFormat, updated)
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Get returns one signal.
|
||||
func Get(d *db.DB, id int64) (*Signal, error) {
|
||||
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE id = ?`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ss, err := scan(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ss) == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return &ss[0], nil
|
||||
}
|
||||
|
||||
// List returns every signal: in testing first, then ideas, proven and
|
||||
// retired; by name within each.
|
||||
func List(d *db.DB) ([]Signal, error) {
|
||||
rows, err := d.Query(`SELECT ` + columns + ` FROM signals ORDER BY
|
||||
CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return scan(rows)
|
||||
}
|
||||
|
||||
// Search finds signals containing every (lower-case) word.
|
||||
func Search(d *db.DB, words []string, limit int) ([]Signal, error) {
|
||||
if len(words) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
hay := "lower(name || ' ' || slug || ' ' || hypothesis || ' ' || spot || ' ' || angle)"
|
||||
conds := make([]string, len(words))
|
||||
args := make([]any, 0, len(words)+1)
|
||||
for i, w := range words {
|
||||
conds[i] = "instr(" + hay + ", ?) > 0"
|
||||
args = append(args, w)
|
||||
}
|
||||
rows, err := d.Query(`SELECT `+columns+` FROM signals WHERE `+strings.Join(conds, " AND ")+` ORDER BY name LIMIT ?`,
|
||||
append(args, limit)...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return scan(rows)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package signals
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
func openDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
func TestSaveSlugsAndList(t *testing.T) {
|
||||
d := openDB(t)
|
||||
a := &Signal{Name: "Leaving Microsoft 365!", Hypothesis: "Price rise", Spot: "m365 alternative\n\n leaving microsoft 365 "}
|
||||
if err := Save(d, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Slug != "leaving-microsoft-365" || a.Status != StatusIdea || len(a.SpotLines()) != 2 {
|
||||
t.Errorf("saved: %+v %q", a, a.SpotLines())
|
||||
}
|
||||
b := &Signal{Name: "Leaving Microsoft 365", Status: StatusTesting}
|
||||
if err := Save(d, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b.Slug != "leaving-microsoft-365-2" {
|
||||
t.Errorf("taken slug: %q", b.Slug)
|
||||
}
|
||||
a.Name = "Leaving M365"
|
||||
if err := Save(d, a); err != nil || a.Slug != "leaving-microsoft-365" {
|
||||
t.Errorf("an update keeps its own slug: %q %v", a.Slug, err)
|
||||
}
|
||||
if err := Save(d, &Signal{Name: "x", Status: "maybe"}); err == nil {
|
||||
t.Error("a bad status was accepted")
|
||||
}
|
||||
if err := Save(d, &Signal{Name: "!!!"}); err == nil {
|
||||
t.Error("a name with no letters was accepted")
|
||||
}
|
||||
list, _ := List(d)
|
||||
if len(list) != 2 || list[0].ID != b.ID {
|
||||
t.Errorf("testing first: %+v", list)
|
||||
}
|
||||
if found, _ := Search(d, []string{"m365", "alternative"}, 10); len(found) != 1 {
|
||||
t.Errorf("search: %+v", found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScorecard(t *testing.T) {
|
||||
d := openDB(t)
|
||||
sig := &Signal{Name: "Price rise", Status: StatusTesting}
|
||||
Save(d, sig)
|
||||
now := time.Now()
|
||||
rec := func(e Event) {
|
||||
t.Helper()
|
||||
if _, err := Record(d, e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, who := range []string{"contact:1", "contact:2", "contact:3", "contact:4"} {
|
||||
rec(Event{SignalID: sig.ID, Stage: StageContacted, Channel: "email", Subject: who, Source: SourceManual})
|
||||
}
|
||||
// Two replies from the same person count once.
|
||||
rec(Event{SignalID: sig.ID, Stage: StageReplied, Channel: "email", Subject: "contact:1", Source: SourceManual})
|
||||
rec(Event{SignalID: sig.ID, Stage: StageReplied, Channel: "email", Subject: "contact:1", Source: SourceManual})
|
||||
rec(Event{SignalID: sig.ID, Stage: StagePaid, Channel: "email", Subject: "contact:1", Source: SourceManual, ValueCents: 7000})
|
||||
// Aggregate visits add their count.
|
||||
rec(Event{SignalID: sig.ID, Stage: StageVisited, Channel: "website", Source: SourceSupermarket, ExternalID: "v1", Count: 30})
|
||||
// An import seen twice is recorded once.
|
||||
if added, _ := Record(d, Event{Stage: StageContacted, Channel: "explee", Subject: "explee:p1", Source: SourceExplee, ExternalID: "x"}); !added {
|
||||
t.Error("first import not added")
|
||||
}
|
||||
if added, _ := Record(d, Event{Stage: StageContacted, Channel: "explee", Subject: "explee:p1", Source: SourceExplee, ExternalID: "x"}); added {
|
||||
t.Error("a repeated import was added")
|
||||
}
|
||||
if _, err := Record(d, Event{Stage: "won", Channel: "email", Source: SourceManual}); err == nil {
|
||||
t.Error("a bad stage was accepted")
|
||||
}
|
||||
|
||||
rows, err := Scorecard(d, Filter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 2 || rows[0].Signal.ID != sig.ID || rows[1].Signal != nil {
|
||||
t.Fatalf("rows: %+v", rows)
|
||||
}
|
||||
r := rows[0]
|
||||
if r.Counts[StageContacted] != 4 || r.Counts[StageReplied] != 1 || r.Counts[StageVisited] != 30 || r.RevenueCents != 7000 {
|
||||
t.Errorf("counts: %+v %d", r.Counts, r.RevenueCents)
|
||||
}
|
||||
for _, c := range r.Cells() {
|
||||
if c.Stage == StageReplied && c.Rate != "25%" {
|
||||
t.Errorf("reply rate: %+v", c)
|
||||
}
|
||||
if c.Stage == StageVisited && c.Rate != "" {
|
||||
t.Errorf("visits aren't a share of those contacted: %+v", c)
|
||||
}
|
||||
}
|
||||
if rows, _ := Scorecard(d, Filter{Channel: "website"}); rows[0].Counts[StageContacted] != 0 || rows[0].Counts[StageVisited] != 30 {
|
||||
t.Errorf("channel filter: %+v", rows[0].Counts)
|
||||
}
|
||||
if rows, _ := Scorecard(d, Filter{Since: now.Add(time.Hour)}); rows[0].Total() != 0 {
|
||||
t.Errorf("since filter: %+v", rows[0].Counts)
|
||||
}
|
||||
|
||||
// Assigning a campaign moves its events and its spend.
|
||||
SaveCampaign(d, Campaign{Source: SourceExplee, ID: "9", Name: "M365 movers", SpendCents: 1234, SyncedAt: now})
|
||||
Record(d, Event{Stage: StageReplied, Channel: "explee", Subject: "explee:p1", Campaign: "explee:9", Source: SourceExplee, ExternalID: "r"})
|
||||
if err := AssignCampaign(d, SourceExplee, "9", sig.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows, _ = Scorecard(d, Filter{})
|
||||
if rows[0].SpendCents != 1234 || rows[0].Counts[StageReplied] != 2 {
|
||||
t.Errorf("after assigning: %+v spend %d", rows[0].Counts, rows[0].SpendCents)
|
||||
}
|
||||
if sigID, _ := CampaignSignal(d, SourceExplee, "9"); sigID != sig.ID {
|
||||
t.Errorf("campaign signal: %d", sigID)
|
||||
}
|
||||
// Saving the campaign again keeps the assignment.
|
||||
SaveCampaign(d, Campaign{Source: SourceExplee, ID: "9", Name: "renamed", SyncedAt: now})
|
||||
if cs, _ := Campaigns(d); len(cs) != 1 || cs[0].SignalID != sig.ID || cs[0].Name != "renamed" {
|
||||
t.Errorf("campaigns: %+v", cs)
|
||||
}
|
||||
|
||||
// Only manual events can be deleted.
|
||||
evs, _ := SubjectEvents(d, "contact:1")
|
||||
if len(evs) != 4 {
|
||||
t.Fatalf("subject events: %+v", evs)
|
||||
}
|
||||
if err := DeleteEvent(d, evs[0].ID); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
imported, _ := SubjectEvents(d, "explee:p1")
|
||||
if err := DeleteEvent(d, imported[0].ID); err == nil {
|
||||
t.Error("an imported event was deleted")
|
||||
}
|
||||
|
||||
// Deleting a signal keeps its events, without a signal.
|
||||
Delete(d, sig.ID)
|
||||
if rows, _ := Scorecard(d, Filter{}); len(rows) != 1 || rows[0].Signal != nil || rows[0].Counts[StageContacted] == 0 {
|
||||
t.Errorf("after delete: %+v", rows)
|
||||
}
|
||||
}
|
||||
+74
-12
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// newProspects is how many companies and people wait for review.
|
||||
@@ -31,11 +32,21 @@ func reviewTab(v string) string {
|
||||
}
|
||||
|
||||
func (s *Server) prospectsPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderProspects(w, r, reviewTab(r.URL.Query().Get("status")), "")
|
||||
sig, _ := strconv.ParseInt(r.URL.Query().Get("signal"), 10, 64)
|
||||
s.renderProspects(w, r, reviewTab(r.URL.Query().Get("status")), sig, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab, errMsg string) {
|
||||
companies, loose, err := prospects.Review(s.DB, tab, 200)
|
||||
// reviewURL is the review screen for a tab and a signal filter.
|
||||
func reviewURL(tab string, signalID int64) string {
|
||||
u := "/prospects?status=" + tab
|
||||
if signalID != 0 {
|
||||
u += "&signal=" + strconv.FormatInt(signalID, 10)
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab string, signalID int64, errMsg string) {
|
||||
companies, loose, err := prospects.Review(s.DB, tab, signalID, 200)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
@@ -72,14 +83,53 @@ func (s *Server) renderProspects(w http.ResponseWriter, r *http.Request, tab, er
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
list, err := signals.List(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
names := map[int64]string{}
|
||||
for _, sg := range list {
|
||||
names[sg.ID] = sg.Name
|
||||
}
|
||||
// Each prospect's funnel so far.
|
||||
var subjects []string
|
||||
for _, c := range companies {
|
||||
subjects = append(subjects, prospects.Subject("company", c.ID))
|
||||
for _, p := range c.Contacts {
|
||||
subjects = append(subjects, prospects.Subject("contact", p.ID))
|
||||
}
|
||||
}
|
||||
for _, p := range loose {
|
||||
subjects = append(subjects, prospects.Subject("contact", p.ID))
|
||||
}
|
||||
evs, err := signals.SubjectEvents(s.DB, subjects...)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
events := map[string][]signals.Event{}
|
||||
for _, e := range evs {
|
||||
if e.Stage != signals.StageFound {
|
||||
events[e.Subject] = append(events[e.Subject], e)
|
||||
}
|
||||
}
|
||||
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,
|
||||
"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"),
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -96,9 +146,15 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
tab := reviewTab(r.PostFormValue("tab"))
|
||||
filter, _ := strconv.ParseInt(r.PostFormValue("filter"), 10, 64)
|
||||
now := time.Now()
|
||||
var msg string
|
||||
switch kind + "/" + action {
|
||||
case "company/signal", "contact/signal":
|
||||
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
|
||||
err, msg = prospects.SetSignal(s.DB, kind, id, sig), "saved"
|
||||
case "company/outcome", "contact/outcome":
|
||||
err, msg = s.prospectOutcome(w, r, kind, id, tab), "outcome"
|
||||
case "company/accept":
|
||||
err, msg = ignore(prospects.AcceptCompany(s.DB, id, now)), "accepted"
|
||||
case "company/accept-all":
|
||||
@@ -140,10 +196,10 @@ func (s *Server) prospectAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.renderProspects(w, r, tab, "Couldn't do that: "+err.Error())
|
||||
s.renderProspects(w, r, tab, filter, "Couldn't do that: "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/prospects?status="+tab, msg)
|
||||
redirect(w, r, reviewURL(tab, filter), msg)
|
||||
}
|
||||
|
||||
// ignore drops a result and keeps the error.
|
||||
@@ -152,6 +208,7 @@ func ignore[T any](_ T, err error) error { return err }
|
||||
// --- Adding by hand ---
|
||||
|
||||
type prospectFormData struct {
|
||||
Signals []signals.Signal
|
||||
Company prospects.Company
|
||||
Contact prospects.Contact
|
||||
CompanyID int64 // adding a person at a company already in review
|
||||
@@ -161,6 +218,8 @@ type prospectFormData struct {
|
||||
|
||||
func (s *Server) prospectForm(w http.ResponseWriter, r *http.Request) {
|
||||
d := prospectFormData{}
|
||||
d.Signals, _ = signals.List(s.DB)
|
||||
d.Company.SignalID, _ = strconv.ParseInt(r.URL.Query().Get("signal"), 10, 64)
|
||||
if id, err := strconv.ParseInt(r.URL.Query().Get("company"), 10, 64); err == nil {
|
||||
c, err := prospects.GetCompany(s.DB, id)
|
||||
if err != nil {
|
||||
@@ -192,6 +251,9 @@ func (s *Server) prospectAdd(w http.ResponseWriter, r *http.Request) {
|
||||
},
|
||||
}
|
||||
d.CompanyID, _ = strconv.ParseInt(f("company_id"), 10, 64)
|
||||
d.Signals, _ = signals.List(s.DB)
|
||||
d.Company.SignalID, _ = strconv.ParseInt(f("signal"), 10, 64)
|
||||
d.Contact.SignalID = d.Company.SignalID
|
||||
if d.CompanyID != 0 {
|
||||
c, err := prospects.GetCompany(s.DB, d.CompanyID)
|
||||
if err != nil {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// prospectBadge is a prospect's status as search shows it.
|
||||
@@ -47,6 +48,8 @@ var settingsPages = []struct {
|
||||
"ai provider model anthropic claude openai ollama lm studio api key hermes effort"},
|
||||
{hit{"Core & Hermes", "Settings · the Federated Core, its services and the Hermes bridge", "/settings/core", ""},
|
||||
"core hermes federated mcp hub bridge espocrm nextcloud plausible gitea"},
|
||||
{hit{"Lead sources", "Settings · origami.chat and explee.com API keys", "/settings/sources", ""},
|
||||
"lead sources origami explee api key import campaigns prospecting outreach"},
|
||||
}
|
||||
|
||||
func (s *Server) searchPage(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -175,6 +178,15 @@ func (s *Server) search(q string) ([]hitGroup, error) {
|
||||
prospectHits = append(prospectHits, hit{Title: p.Name(), Detail: detail, Link: "/prospects?status=" + p.Status, Badge: prospectBadge(p.Status)})
|
||||
}
|
||||
|
||||
sigs, err := signals.Search(s.DB, words, searchLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, sg := range sigs {
|
||||
prospectHits = append([]hit{{Title: sg.Name, Detail: "Buying signal · " + sg.Hypothesis,
|
||||
Link: "/signals/" + strconv.FormatInt(sg.ID, 10), Badge: sg.Status}}, prospectHits...)
|
||||
}
|
||||
|
||||
var settings []hit
|
||||
if p, err := profile.Load(s.DB); err == nil && p.IsSet() {
|
||||
for _, pr := range p.Products {
|
||||
|
||||
+39
-1
@@ -10,6 +10,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -21,6 +22,7 @@ import (
|
||||
"supermarket/internal/legacy"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
//go:embed templates/*.html
|
||||
@@ -133,6 +135,18 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("GET /prospects/suppressed", s.suppressedPage)
|
||||
mux.HandleFunc("POST /prospects/suppressed", s.suppressedAction)
|
||||
mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", s.prospectAction)
|
||||
mux.HandleFunc("GET /signals", s.signalsPage)
|
||||
mux.HandleFunc("GET /signals/new", s.signalPage)
|
||||
mux.HandleFunc("POST /signals/new", s.signalSave)
|
||||
mux.HandleFunc("POST /signals/campaigns", s.signalCampaign)
|
||||
mux.HandleFunc("POST /lead-sources/{source}/import", s.importSource)
|
||||
mux.HandleFunc("GET /signals/{id}", s.signalPage)
|
||||
mux.HandleFunc("POST /signals/{id}", s.signalSave)
|
||||
mux.HandleFunc("POST /signals/{id}/delete", s.signalDelete)
|
||||
mux.HandleFunc("POST /funnel/{id}/delete", s.funnelDelete)
|
||||
mux.HandleFunc("GET /settings/sources", s.sourcesPage)
|
||||
mux.HandleFunc("POST /settings/sources", s.sourcesSave)
|
||||
mux.HandleFunc("POST /settings/sources/test/{source}", s.sourcesTest)
|
||||
mux.HandleFunc("GET /crm", s.crmPage)
|
||||
mux.HandleFunc("GET /crm/reach", s.crmReach)
|
||||
mux.HandleFunc("POST /crm/{action}", s.crmAction)
|
||||
@@ -232,6 +246,10 @@ func (s *Server) loadTemplates() error {
|
||||
return m, nil
|
||||
},
|
||||
"xreserve": twitter.URLReserve,
|
||||
// money shows cents as dollars: $1,234 or $12.50.
|
||||
"money": money,
|
||||
"stage": signals.StageLabel,
|
||||
"channel": signals.ChannelLabel,
|
||||
"truncate": func(n int, s string) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
@@ -298,7 +316,7 @@ type module struct {
|
||||
|
||||
var modules = []module{
|
||||
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
|
||||
{"prospects", "Prospects", "Phase 2", "Find companies and people who fit your targets, and add the ones you approve to EspoCRM through Hermes.", "/prospects"},
|
||||
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
|
||||
{"seo", "SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories.", ""},
|
||||
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
|
||||
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
|
||||
@@ -355,6 +373,7 @@ var flashes = map[string]string{
|
||||
"suppressed": "Added to the suppression list.",
|
||||
"unsuppressed": "Taken off the suppression list.",
|
||||
"prospect-added": "Added. Review it below.",
|
||||
"outcome": "Outcome recorded.",
|
||||
"rules-refreshed": "Rules refreshed.",
|
||||
"imported": "Imported.",
|
||||
"oauth-expired": "That sign-in took too long or was already used. Try again.",
|
||||
@@ -384,6 +403,25 @@ func (s *Server) serverError(w http.ResponseWriter, err error) {
|
||||
http.Error(w, "Something went wrong: "+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
func money(cents int64) string {
|
||||
neg := cents < 0
|
||||
if neg {
|
||||
cents = -cents
|
||||
}
|
||||
whole := strconv.FormatInt(cents/100, 10)
|
||||
for i := len(whole) - 3; i > 0; i -= 3 {
|
||||
whole = whole[:i] + "," + whole[i:]
|
||||
}
|
||||
out := "$" + whole
|
||||
if c := cents % 100; c != 0 {
|
||||
out += fmt.Sprintf(".%02d", c)
|
||||
}
|
||||
if neg {
|
||||
out = "-" + out
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ago(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return "never"
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
const testToken = "0123456789abcdef0123456789abcdef"
|
||||
@@ -99,7 +100,8 @@ func TestEveryPageRenders(t *testing.T) {
|
||||
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/content/scheduled", "/content/published",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed"} {
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed",
|
||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String())
|
||||
@@ -599,3 +601,89 @@ func TestProspectsReview(t *testing.T) {
|
||||
t.Errorf("missing prospect: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Signals: define one, tag a prospect, record outcomes, and see them on
|
||||
// the scorecard.
|
||||
func TestSignalsFunnel(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
rec := postForm(h, "/signals/new", url.Values{"name": {"Leaving Microsoft 365"}, "status": {"testing"},
|
||||
"hypothesis": {"Price rise makes them switch"}, "spot": {"m365 alternative"}})
|
||||
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/signals/1") {
|
||||
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := postForm(h, "/signals/new", url.Values{"name": {""}}); !strings.Contains(rec.Body.String(), "needs a name") {
|
||||
t.Error("a nameless signal was accepted")
|
||||
}
|
||||
postForm(h, "/prospects/new", url.Values{"company_name": {"Acme"}, "website": {"acme.example"}, "first_name": {"Pat"},
|
||||
"last_name": {"Lee"}, "email": {"pat@acme.example"}, "signal": {"1"}})
|
||||
body := do(h, http.MethodGet, "/prospects?signal=1", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "Pat Lee") || !strings.Contains(body, `<option value="1" selected>Leaving Microsoft 365</option>`) {
|
||||
t.Error("the prospect isn't shown with its signal")
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/prospects?signal=99", nil, nil).Body.String(); strings.Contains(body, "Pat Lee") {
|
||||
t.Error("the signal filter doesn't filter")
|
||||
}
|
||||
for _, f := range []url.Values{
|
||||
{"stage": {"contacted"}, "channel": {"email"}, "date": {"2026-11-20"}},
|
||||
{"stage": {"replied"}, "channel": {"email"}, "note": {"Interested, call next week"}},
|
||||
{"stage": {"paid"}, "channel": {"email"}, "amount": {"$1,070.50"}},
|
||||
} {
|
||||
f.Set("tab", "new")
|
||||
f.Set("filter", "1")
|
||||
if rec := postForm(h, "/prospects/contact/1/outcome", f); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/prospects?status=new&signal=1&msg=outcome" {
|
||||
t.Fatalf("outcome: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body.String())
|
||||
}
|
||||
}
|
||||
if rec := postForm(h, "/prospects/contact/1/outcome", url.Values{"stage": {"paid"}, "channel": {"email"}, "amount": {"lots"}}); !strings.Contains(rec.Body.String(), "an amount") {
|
||||
t.Errorf("a bad amount was accepted: %d", rec.Code)
|
||||
}
|
||||
body = do(h, http.MethodGet, "/signals", nil, nil).Body.String()
|
||||
for _, want := range []string{"Leaving Microsoft 365", "$1,070.50", `<span class="rate">100%</span>`} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("scorecard lacks %q", want)
|
||||
}
|
||||
}
|
||||
body = do(h, http.MethodGet, "/signals/1", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "Interested, call next week") || !strings.Contains(body, "Its prospects (1 new)") {
|
||||
t.Error("the signal's page")
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/prospects", nil, nil).Body.String(); !strings.Contains(body, "Interested, call next week") {
|
||||
t.Error("the prospect's steps aren't shown")
|
||||
}
|
||||
|
||||
// Moving the company to no signal moves its person and their steps.
|
||||
postForm(h, "/prospects/company/1/signal", url.Values{"signal": {"0"}})
|
||||
if rows, _ := signals.Scorecard(s.DB, signals.Filter{}); rows[0].Total() != 0 || rows[1].Signal != nil || rows[1].Counts["paid"] != 1 {
|
||||
t.Errorf("after untagging: %+v", rows)
|
||||
}
|
||||
|
||||
// An outside campaign, assigned to the signal.
|
||||
signals.SaveCampaign(s.DB, signals.Campaign{Source: "explee", ID: "7", Name: "M365 movers", SpendCents: 990, SyncedAt: time.Now()})
|
||||
if body := do(h, http.MethodGet, "/signals", nil, nil).Body.String(); !strings.Contains(body, "M365 movers") {
|
||||
t.Error("campaign not listed")
|
||||
}
|
||||
postForm(h, "/signals/campaigns", url.Values{"source": {"explee"}, "id": {"7"}, "signal": {"1"}})
|
||||
if cs, _ := signals.Campaigns(s.DB); cs[0].SignalID != 1 {
|
||||
t.Errorf("assign: %+v", cs)
|
||||
}
|
||||
if rec := postForm(h, "/lead-sources/explee/import", nil); !strings.Contains(rec.Body.String(), "API key first") {
|
||||
t.Errorf("import without a key: %s", rec.Body.String())
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/search?q=microsoft", nil, nil).Body.String(); !strings.Contains(body, "/signals/1") {
|
||||
t.Error("search doesn't find the signal")
|
||||
}
|
||||
|
||||
// Lead source keys.
|
||||
postForm(h, "/settings/sources", url.Values{secrets.ExpleeAPIKey: {"ex-key"}, "origami_project": {"proj"}})
|
||||
if s.Secrets.Get(secrets.ExpleeAPIKey) != "ex-key" || s.origamiProject() != "proj" {
|
||||
t.Error("lead source settings not saved")
|
||||
}
|
||||
if rec := postForm(h, "/settings/sources/test/origami", nil); !strings.Contains(rec.Body.String(), "Save the key first") {
|
||||
t.Errorf("test without a key: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
postForm(h, "/signals/1/delete", nil)
|
||||
if list, _ := signals.List(s.DB); len(list) != 0 {
|
||||
t.Error("delete")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -380,3 +380,41 @@ form.inline { display: inline-block; margin: 0 0 0.75rem; }
|
||||
.prospect .why { margin: 0.6rem 0 0.3rem; }
|
||||
.prospect .people { margin: 0.9rem 0 0.5rem; }
|
||||
.prospect .warnings { margin: 0.5rem 0; }
|
||||
|
||||
/* Signals and the funnel */
|
||||
.filters { display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end; margin: 0 0 1rem; }
|
||||
.filters label { margin: 0; }
|
||||
.filters select { width: auto; min-width: 12rem; }
|
||||
.table-wrap { overflow-x: auto; margin-bottom: 0.75rem; }
|
||||
table.list th.num, table.list td.num { text-align: right; white-space: nowrap; }
|
||||
.scorecard td.num { font-variant-numeric: tabular-nums; }
|
||||
table.scorecard th, table.scorecard td { padding: 0.5rem 0.5rem; }
|
||||
table.scorecard th { font-size: 0.66rem; letter-spacing: 0.02em; }
|
||||
table.scorecard td:first-child { min-width: 11rem; }
|
||||
table.scorecard td:first-child .badge { margin-left: 0.25rem; }
|
||||
.rate { display: block; font-size: 0.72rem; color: hsl(var(--muted-foreground)); }
|
||||
.stat { display: inline-block; margin-right: 0.6rem; white-space: nowrap; }
|
||||
.badge.idea { background: hsl(var(--muted)); color: hsl(var(--muted-foreground)); }
|
||||
.badge.testing { background: hsl(var(--accent)); color: hsl(var(--accent-foreground)); }
|
||||
.badge.proven { background: hsl(var(--ok-bg)); color: hsl(var(--ok)); }
|
||||
.badge.retired { background: hsl(var(--muted)); color: hsl(var(--muted-foreground)); text-decoration: line-through; }
|
||||
.funnel { display: grid; grid-template-columns: repeat(auto-fit, minmax(88px, 1fr)); gap: 0.4rem; margin: 0.5rem 0 1rem; }
|
||||
.funnel .step { border: 1px solid hsl(var(--border)); border-radius: var(--radius); padding: 0.55rem 0.7rem; display: flex; flex-direction: column; gap: 0.1rem; }
|
||||
.funnel .step .label { font-size: 0.75rem; color: hsl(var(--muted-foreground)); text-transform: uppercase; letter-spacing: 0.04em; }
|
||||
.funnel .step strong { font-size: 1.35rem; font-variant-numeric: tabular-nums; }
|
||||
.signal-tag { margin: 0.35rem 0 0; }
|
||||
.signal-tag label { display: inline-flex; align-items: center; gap: 0.45rem; margin: 0; font-weight: normal; }
|
||||
.signal-tag select { width: auto; padding-top: 0.15rem; padding-bottom: 0.15rem; font-size: 0.82rem; }
|
||||
.steps-done { list-style: none; padding: 0; margin: 0.45rem 0 0; font-size: 0.82rem; color: hsl(var(--muted-foreground)); }
|
||||
.steps-done li { padding: 0.12rem 0; }
|
||||
.steps-done form.inline { display: inline; margin: 0; }
|
||||
.outcome { margin: 0.4rem 0 0; }
|
||||
.outcome summary { cursor: pointer; color: hsl(var(--primary)); }
|
||||
.row.wrap { flex-wrap: wrap; align-items: flex-end; margin-top: 0.5rem; }
|
||||
.row.wrap label { margin: 0; }
|
||||
.row.wrap select, .row.wrap input { width: auto; }
|
||||
.row.wrap .grow { flex: 1; min-width: 10rem; }
|
||||
.row.wrap .grow input { width: 100%; }
|
||||
button.link { background: none; border: 0; box-shadow: none; padding: 0; color: hsl(var(--primary)); text-decoration: underline; cursor: pointer; font-weight: normal; }
|
||||
.danger-zone { margin-top: 2rem; }
|
||||
pre.sample { max-height: 24rem; overflow: auto; font-size: 0.78rem; }
|
||||
|
||||
@@ -65,6 +65,15 @@
|
||||
}
|
||||
});
|
||||
|
||||
// A select with data-autosubmit sends its form when it changes (inline
|
||||
// handlers aren't allowed by the page's Content-Security-Policy).
|
||||
document.addEventListener("change", function (e) {
|
||||
var el = e.target;
|
||||
if (el.hasAttribute && el.hasAttribute("data-autosubmit") && el.form) {
|
||||
if (el.form.requestSubmit) el.form.requestSubmit(); else el.form.submit();
|
||||
}
|
||||
});
|
||||
|
||||
// Ask before submitting a form with data-confirm. A form with data-busy
|
||||
// shows that text on the button that submitted it, and can't be sent twice,
|
||||
// while a slow request (fetching, writing, publishing) runs. With
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
{{end}}
|
||||
{{if eq .ID "prospects"}}
|
||||
<div class="subnav">
|
||||
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
|
||||
<a href="/prospects" {{if eq $nav "prospects/review"}}aria-current="page"{{end}}>Review{{with $.NewProspects}} <span class="count-badge" title="{{.}} waiting for review">{{.}}</span>{{end}}</a>
|
||||
<a href="/prospects/suppressed" {{if eq $nav "prospects/suppressed"}}aria-current="page"{{end}}>Suppression list</a>
|
||||
<a href="/crm" {{if eq $nav "prospects/crm"}}aria-current="page"{{end}}>CRM queue</a>
|
||||
@@ -81,7 +82,7 @@
|
||||
{{define "settings-start"}}
|
||||
<div class="page-head">
|
||||
<h1>Settings</h1>
|
||||
<p class="lede">Your company, the accounts Supermarket posts with, the AI it writes with, and your Federated Core.</p>
|
||||
<p class="lede">Your company, the accounts Supermarket posts with, the prospecting tools it reads, the AI it writes with, and your Federated Core.</p>
|
||||
</div>
|
||||
<div class="settings">
|
||||
<nav class="settings-nav" aria-label="Settings sections">
|
||||
@@ -90,6 +91,7 @@
|
||||
<div class="nav-label">Connections</div>
|
||||
<a href="/settings/accounts" {{if eq .Nav "settings/accounts"}}aria-current="page"{{end}}>{{template "icon" "accounts"}}Social accounts</a>
|
||||
<a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core & Hermes</a>
|
||||
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
|
||||
<div class="nav-label">AI</div>
|
||||
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
||||
</nav>
|
||||
|
||||
@@ -25,6 +25,15 @@
|
||||
<label>Phone <input name="phone" value="{{.Contact.Phone}}"></label>
|
||||
<label>LinkedIn profile <input name="linkedin" value="{{.Contact.LinkedIn}}" placeholder="https://www.linkedin.com/in/…"></label>
|
||||
</div>
|
||||
{{if .Signals}}{{$cur := .Company.SignalID}}
|
||||
<label>Buying signal
|
||||
<select name="signal">
|
||||
<option value="0">none</option>
|
||||
{{range .Signals}}<option value="{{.ID}}" {{if eq .ID $cur}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
<span class="help">The signal you found them through{{if $.Data.For}}. Leave it at none to use the company's{{end}}.</span>
|
||||
</label>
|
||||
{{end}}
|
||||
<label>Where you found them <input name="source_detail" value="{{.Contact.SourceDetail}}" placeholder="A link, an event, a referral…">
|
||||
<span class="help">Kept with the prospect and written into the CRM record, so you can always say where a contact came from.</span></label>
|
||||
<div class="actions">
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
{{define "content"}}{{with .Data}}{{$tab := .Tab}}{{$matches := .Matches}}
|
||||
{{define "content"}}{{with .Data}}{{$tab := .Tab}}{{$matches := .Matches}}{{$d := .}}
|
||||
<div class="heading">
|
||||
<h1>Review prospects</h1>
|
||||
<div class="buttons">
|
||||
<a class="button" href="/prospects/new">Add a prospect</a>
|
||||
<a class="button" href="/prospects/new{{if .Signal}}?signal={{.Signal}}{{end}}">Add a prospect</a>
|
||||
</div>
|
||||
</div>
|
||||
<p class="lede">Companies and people who may fit your targets. Nothing goes to your CRM until you accept it: accepting a company adds an Account, accepting a person adds a Lead, through <a href="/crm">the CRM queue</a>. Each one keeps where and when it was found.</p>
|
||||
|
||||
{{if .Signals}}
|
||||
<form method="get" action="/prospects" class="filters">
|
||||
<input type="hidden" name="status" value="{{$tab}}">
|
||||
<label class="small">Signal
|
||||
<select name="signal" data-autosubmit>
|
||||
<option value="0">All signals</option>
|
||||
{{range .Signals}}<option value="{{.ID}}" {{if eq .ID $d.Signal}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<noscript><button type="submit" class="secondary small">Show</button></noscript>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
<nav class="tabs">
|
||||
{{range .Statuses}}<a href="/prospects?status={{.}}" {{if eq $tab .}}aria-current="page"{{end}}>{{if eq . "new"}}New{{else if eq . "accepted"}}Accepted{{else}}Set aside{{end}}{{with index $.Data.Counts .}} <span class="muted">{{.}}</span>{{end}}</a>{{end}}
|
||||
{{range .Statuses}}<a href="/prospects?status={{.}}{{if $d.Signal}}&signal={{$d.Signal}}{{end}}" {{if eq $tab .}}aria-current="page"{{end}}>{{if eq . "new"}}New{{else if eq . "accepted"}}Accepted{{else}}Set aside{{end}}{{with index $.Data.Counts .}} <span class="muted">{{.}}</span>{{end}}</a>{{end}}
|
||||
</nav>
|
||||
|
||||
{{if and (eq $tab "new") (or .Companies .Loose)}}
|
||||
@@ -29,25 +42,26 @@
|
||||
{{if eq .Status $tab}}
|
||||
<div class="row-actions">
|
||||
{{if eq $tab "new"}}
|
||||
{{if .Contacts}}<form method="post" action="/prospects/company/{{.ID}}/accept-all"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="small">Accept with {{len .Contacts}} {{if eq (len .Contacts) 1}}person{{else}}people{{end}}</button></form>{{end}}
|
||||
<form method="post" action="/prospects/company/{{.ID}}/accept"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="small {{if .Contacts}}secondary{{end}}">Accept {{if .Contacts}}company only{{else}}company{{end}}</button></form>
|
||||
<form method="post" action="/prospects/company/{{.ID}}/reject"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Set aside</button></form>
|
||||
{{if .Domain}}<form method="post" action="/prospects/company/{{.ID}}/suppress" data-confirm="Never add anyone at {{.Domain}}? This puts the domain on your suppression list."><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Suppress {{.Domain}}</button></form>{{end}}
|
||||
{{if .Contacts}}<form method="post" action="/prospects/company/{{.ID}}/accept-all"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="small">Accept with {{len .Contacts}} {{if eq (len .Contacts) 1}}person{{else}}people{{end}}</button></form>{{end}}
|
||||
<form method="post" action="/prospects/company/{{.ID}}/accept"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="small {{if .Contacts}}secondary{{end}}">Accept {{if .Contacts}}company only{{else}}company{{end}}</button></form>
|
||||
<form method="post" action="/prospects/company/{{.ID}}/reject"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Set aside</button></form>
|
||||
{{if .Domain}}<form method="post" action="/prospects/company/{{.ID}}/suppress" data-confirm="Never add anyone at {{.Domain}}? This puts the domain on your suppression list."><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Suppress {{.Domain}}</button></form>{{end}}
|
||||
{{else if eq $tab "accepted"}}
|
||||
{{template "crm-state" dict "CRM" .CRM "Kind" "company" "ID" .ID "Tab" $tab}}
|
||||
{{template "crm-state" dict "CRM" .CRM "Kind" "company" "ID" .ID "Tab" $tab "Filter" $d.Signal}}
|
||||
{{else}}
|
||||
<form method="post" action="/prospects/company/{{.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||
<form method="post" action="/prospects/company/{{.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
</div>
|
||||
{{with .Why}}<p class="why">{{.}}</p>{{end}}
|
||||
<p class="meta">{{template "provenance" .}}</p>
|
||||
{{template "signal-tag" dict "Kind" "company" "ID" .ID "SignalID" .SignalID "D" $d}}
|
||||
{{with index $matches (printf "company:%d" .ID)}}{{template "crm-matches" .}}{{end}}
|
||||
|
||||
{{if .Contacts}}
|
||||
<ul class="items people">
|
||||
{{range .Contacts}}{{template "contact" dict "P" . "Tab" $tab "Matches" $matches}}{{end}}
|
||||
{{range .Contacts}}{{template "contact" dict "P" . "Tab" $tab "Matches" $matches "D" $d}}{{end}}
|
||||
</ul>
|
||||
{{end}}
|
||||
{{if eq $tab "new"}}<p class="small"><a href="/prospects/new?company={{.ID}}">Add a person at {{.Name}}</a></p>{{end}}
|
||||
@@ -58,7 +72,7 @@
|
||||
<section class="card prospect">
|
||||
<h2>People without a company</h2>
|
||||
<ul class="items people">
|
||||
{{range .Loose}}{{template "contact" dict "P" . "Tab" $tab "Matches" $matches}}{{end}}
|
||||
{{range .Loose}}{{template "contact" dict "P" . "Tab" $tab "Matches" $matches "D" $d}}{{end}}
|
||||
</ul>
|
||||
</section>
|
||||
{{end}}
|
||||
@@ -72,7 +86,7 @@
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
|
||||
{{define "contact"}}{{$p := .P}}{{$tab := .Tab}}
|
||||
{{define "contact"}}{{$p := .P}}{{$tab := .Tab}}{{$d := .D}}
|
||||
<li class="item">
|
||||
<div class="prospect-head">
|
||||
<div>
|
||||
@@ -83,18 +97,20 @@
|
||||
{{with $p.LinkedIn}} · <a href="{{.}}" target="_blank" rel="noopener noreferrer">LinkedIn</a>{{end}}
|
||||
</div>
|
||||
<div class="meta">{{template "provenance" $p}}</div>
|
||||
{{if not $p.CompanyID}}{{template "signal-tag" dict "Kind" "contact" "ID" $p.ID "SignalID" $p.SignalID "D" $d}}{{end}}
|
||||
{{with index .Matches (printf "contact:%d" $p.ID)}}{{template "crm-matches" .}}{{end}}
|
||||
{{template "outcomes" dict "Kind" "contact" "ID" $p.ID "Tab" $tab "D" $d}}
|
||||
</div>
|
||||
{{if eq $p.Status $tab}}
|
||||
<div class="row-actions">
|
||||
{{if eq $tab "new"}}
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/accept"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="small">Accept</button></form>
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/reject"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Set aside</button></form>
|
||||
{{if $p.Email}}<form method="post" action="/prospects/contact/{{$p.ID}}/suppress" data-confirm="Never add {{$p.Email}}? This puts the address on your suppression list."><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Suppress</button></form>{{end}}
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/accept"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="small">Accept</button></form>
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/reject"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Set aside</button></form>
|
||||
{{if $p.Email}}<form method="post" action="/prospects/contact/{{$p.ID}}/suppress" data-confirm="Never add {{$p.Email}}? This puts the address on your suppression list."><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Suppress</button></form>{{end}}
|
||||
{{else if eq $tab "accepted"}}
|
||||
{{template "crm-state" dict "CRM" $p.CRM "Kind" "contact" "ID" $p.ID "Tab" $tab}}
|
||||
{{template "crm-state" dict "CRM" $p.CRM "Kind" "contact" "ID" $p.ID "Tab" $tab "Filter" $d.Signal}}
|
||||
{{else}}
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||
<form method="post" action="/prospects/contact/{{$p.ID}}/reconsider"><input type="hidden" name="tab" value="{{$tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}"><button type="submit" class="secondary small">Reconsider</button></form>
|
||||
{{end}}
|
||||
</div>
|
||||
{{end}}
|
||||
@@ -114,8 +130,44 @@
|
||||
{{if eq .CRM.Status "done"}}<span class="badge published">{{if eq .CRM.Outcome "existing"}}already in the CRM{{else}}in the CRM{{end}}</span>
|
||||
{{else if eq .CRM.Status "failed"}}<span class="badge failed">failed</span> <a class="small" href="/crm">CRM queue</a>
|
||||
{{else if eq .CRM.Status "cancelled"}}<span class="badge">cancelled</span>
|
||||
<form method="post" action="/prospects/{{.Kind}}/{{.ID}}/accept"><input type="hidden" name="tab" value="{{.Tab}}"><button type="submit" class="secondary small">Queue again</button></form>
|
||||
<form method="post" action="/prospects/{{.Kind}}/{{.ID}}/accept"><input type="hidden" name="tab" value="{{.Tab}}"><input type="hidden" name="filter" value="{{.Filter}}"><button type="submit" class="secondary small">Queue again</button></form>
|
||||
{{else if eq .CRM.Status "claimed"}}<span class="badge scheduled">with Hermes</span>
|
||||
{{else if .CRM.Status}}<span class="badge draft">waiting for Hermes</span>
|
||||
{{else}}<span class="badge">accepted</span>{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "signal-tag"}}{{$d := .D}}{{$cur := .SignalID}}
|
||||
{{if $d.Signals}}
|
||||
<form method="post" action="/prospects/{{.Kind}}/{{.ID}}/signal" class="signal-tag">
|
||||
<input type="hidden" name="tab" value="{{$d.Tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}">
|
||||
<label class="small">Signal
|
||||
<select name="signal" data-autosubmit>
|
||||
<option value="0">none</option>
|
||||
{{range $d.Signals}}<option value="{{.ID}}" {{if eq .ID $cur}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
</label>
|
||||
<noscript><button type="submit" class="secondary small">Save</button></noscript>
|
||||
</form>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
{{define "outcomes"}}{{$d := .D}}{{$subject := printf "%s:%d" .Kind .ID}}
|
||||
{{with index $d.Events $subject}}
|
||||
<ol class="steps-done">
|
||||
{{range .}}<li><span class="badge {{if eq .Stage "paid"}}published{{else}}draft{{end}}">{{stage .Stage}}</span> {{channel .Channel}} · {{ago .At}}{{if .ValueCents}} · {{money .ValueCents}}{{end}}{{with .Note}} · {{truncate 100 .}}{{end}}
|
||||
{{if eq .Source "manual"}}<form method="post" action="/funnel/{{.ID}}/delete" class="inline" data-confirm="Remove this step?"><input type="hidden" name="back" value="{{$d.Back}}"><input type="hidden" name="tab" value="{{$d.Tab}}"><button type="submit" class="link small">remove</button></form>{{end}}</li>{{end}}
|
||||
</ol>
|
||||
{{end}}
|
||||
<details class="outcome">
|
||||
<summary class="small">Record an outcome</summary>
|
||||
<form method="post" action="/prospects/{{.Kind}}/{{.ID}}/outcome" class="row wrap">
|
||||
<input type="hidden" name="tab" value="{{.Tab}}"><input type="hidden" name="filter" value="{{$d.Signal}}">
|
||||
<label class="small">Step <select name="stage">{{range $d.Stages}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select></label>
|
||||
<label class="small">Channel <select name="channel">{{range $d.Channels}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select></label>
|
||||
<label class="small">Date <input type="date" name="date" value="{{$d.Today}}"></label>
|
||||
<label class="small">Amount <input name="amount" inputmode="decimal" placeholder="for Paid, e.g. 70" size="8"></label>
|
||||
<label class="small grow">Note <input name="note" placeholder="optional"></label>
|
||||
<button type="submit" class="secondary small">Record</button>
|
||||
</form>
|
||||
</details>
|
||||
{{end}}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
{{define "content"}}{{with .Data}}{{$s := .S}}
|
||||
<div class="heading">
|
||||
<h1>{{if $s.ID}}{{$s.Name}} <span class="badge {{$s.Status}}">{{$s.Status}}</span>{{else}}New signal{{end}}</h1>
|
||||
{{if $s.ID}}<div class="buttons">
|
||||
<a class="button secondary" href="/prospects?status=new&signal={{$s.ID}}">Its prospects{{if .Prospects}} ({{.Prospects}} new){{end}}</a>
|
||||
<a class="button secondary" href="/prospects/new?signal={{$s.ID}}">Add a prospect for it</a>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
<p class="lede">A guess about why a company buys now, written so it can be tested: what you'll see, and what you expect them to do.</p>
|
||||
|
||||
{{if $s.ID}}
|
||||
{{with .Total}}
|
||||
<section class="card">
|
||||
<h2>Funnel</h2>
|
||||
<div class="funnel">
|
||||
{{range .Cells}}<div class="step"><span class="label">{{stage .Stage}}</span><strong>{{.Count}}</strong>{{with .Rate}}<span class="rate">{{.}} of contacted</span>{{end}}</div>{{end}}
|
||||
</div>
|
||||
<p class="small">{{if .RevenueCents}}Revenue <strong>{{money .RevenueCents}}</strong>. {{end}}{{if .SpendCents}}Spend in outside tools <strong>{{money .SpendCents}}</strong>.{{end}}</p>
|
||||
{{if $.Data.ByChannel}}
|
||||
<table class="list scorecard">
|
||||
<thead><tr><th>Channel</th>{{range $.Data.Stages}}<th class="num">{{.Label}}</th>{{end}}</tr></thead>
|
||||
<tbody>{{range $.Data.ByChannel}}<tr><td>{{channel .Channel}}</td>{{range .Row.Cells}}<td class="num">{{if .Count}}{{.Count}}{{with .Rate}}<span class="rate">{{.}}</span>{{end}}{{else}}<span class="muted">·</span>{{end}}</td>{{end}}</tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{else}}<p class="help">Nothing recorded for it yet: tag prospects with it, give it an origami.chat or explee.com campaign, or record outcomes in Review.</p>{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
{{end}}
|
||||
|
||||
<form method="post" action="{{if $s.ID}}/signals/{{$s.ID}}{{else}}/signals/new{{end}}" class="card">
|
||||
<div class="cols">
|
||||
<label>Name <input name="name" value="{{$s.Name}}" required placeholder="Leaving Microsoft 365"></label>
|
||||
<label>Status
|
||||
<select name="status">{{range .Statuses}}<option value="{{.}}" {{if eq . $s.Status}}selected{{end}}>{{.}}</option>{{end}}</select>
|
||||
<span class="help">Idea, testing, proven or retired. Retired signals stay on the scorecard for comparison.</span>
|
||||
</label>
|
||||
</div>
|
||||
<label>Hypothesis <textarea name="hypothesis" rows="2" placeholder="Teams complaining about the Microsoft 365 price rise switch within a quarter.">{{$s.Hypothesis}}</textarea></label>
|
||||
<label>How to spot it <textarea name="spot" rows="4" placeholder="One per line: search queries, keywords, origami.chat or explee.com criteria">{{$s.Spot}}</textarea>
|
||||
<span class="help">Discovery (next) runs these as searches, so write them the way you'd search for the companies.</span></label>
|
||||
<label>Angle <textarea name="angle" rows="3" placeholder="The pain, and what we promise about it">{{$s.Angle}}</textarea>
|
||||
<span class="help">What emails, LinkedIn messages and content for this signal should say.</span></label>
|
||||
<label>Campaign tag <input name="slug" value="{{$s.Slug}}" placeholder="made from the name">
|
||||
<span class="help">Used as <code>utm_campaign</code> on links for this signal, so visits and sign-ups are counted against it. Change it before using it, not after.</span></label>
|
||||
<div class="actions">
|
||||
<button type="submit">Save</button>
|
||||
<a href="/signals">Back to signals</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{{if $s.ID}}
|
||||
{{if .Campaigns}}
|
||||
<h2>Campaigns testing it</h2>
|
||||
<ul class="items">{{range .Campaigns}}<li class="item"><strong>{{.Name}}</strong> <span class="muted small">{{if eq .Source "origami"}}origami.chat{{else}}explee.com{{end}}{{with .Status}} · {{.}}{{end}}</span>
|
||||
<div class="small">{{range $k, $v := .Stats}}{{if $v}}<span class="stat">{{$k}}: <strong>{{$v}}</strong></span> {{end}}{{end}}</div></li>{{end}}</ul>
|
||||
{{end}}
|
||||
|
||||
{{if .Events}}
|
||||
<h2>Latest steps</h2>
|
||||
<table class="list">
|
||||
<thead><tr><th>When</th><th>Step</th><th>Channel</th><th>Who</th><th>Note</th></tr></thead>
|
||||
<tbody>{{range .Events}}<tr><td>{{ago .At}}</td><td>{{stage .Stage}}{{if .ValueCents}} · {{money .ValueCents}}{{end}}{{if gt .Count 1}} · {{.Count}}{{end}}</td><td>{{channel .Channel}}</td><td class="small">{{or .Email .Subject}}</td><td class="small">{{truncate 120 .Note}}</td></tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
|
||||
<form method="post" action="/signals/{{$s.ID}}/delete" data-confirm="Delete “{{$s.Name}}”? Its prospects, campaigns and results stay, without a signal." class="danger-zone">
|
||||
<button type="submit" class="secondary small">Delete this signal</button>
|
||||
</form>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,81 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading">
|
||||
<h1>Signals</h1>
|
||||
<div class="buttons"><a class="button" href="/signals/new">New signal</a></div>
|
||||
</div>
|
||||
<p class="lede">A buying signal is a guess about why a company buys now. Each one is tested through what's done for it, directly (email, LinkedIn) and indirectly (posts, pages), and in origami.chat and explee.com. Every step anyone takes through the funnel is counted here, so you can see which signals turn into replies, bookings, sign-ups and payments.</p>
|
||||
|
||||
<form method="get" action="/signals" class="filters">
|
||||
<label class="small">Period
|
||||
<select name="period" data-autosubmit>{{range .Periods}}<option value="{{.ID}}" {{if eq .ID $d.Period}}selected{{end}}>{{.Label}}</option>{{end}}</select>
|
||||
</label>
|
||||
<label class="small">Channel
|
||||
<select name="channel" data-autosubmit><option value="">All channels</option>{{range .Channels}}<option value="{{.ID}}" {{if eq .ID $d.Channel}}selected{{end}}>{{.Label}}</option>{{end}}</select>
|
||||
</label>
|
||||
<noscript><button type="submit" class="secondary small">Show</button></noscript>
|
||||
</form>
|
||||
|
||||
{{if .Rows}}
|
||||
<div class="table-wrap">
|
||||
<table class="list scorecard">
|
||||
<thead><tr><th>Signal</th>{{range .Stages}}<th class="num">{{.Label}}</th>{{end}}<th class="num">Revenue</th><th class="num">Spend</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Rows}}
|
||||
<tr>
|
||||
<td>{{with .Signal}}<a href="/signals/{{.ID}}">{{.Name}}</a> <span class="badge {{.Status}}">{{.Status}}</span>{{else}}<span class="muted">No signal</span>{{end}}</td>
|
||||
{{range .Cells}}<td class="num">{{if .Count}}{{.Count}}{{with .Rate}}<span class="rate">{{.}}</span>{{end}}{{else}}<span class="muted">·</span>{{end}}</td>{{end}}
|
||||
<td class="num">{{if .RevenueCents}}{{money .RevenueCents}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td class="num">{{if .SpendCents}}{{money .SpendCents}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="help">People count once per stage, however many times they replied. Percentages are of those contacted. Visits are counted in total, not per person. Spend is what origami.chat and explee.com report for each signal's campaigns, all time. A signal moves to <em>proven</em> when you say so.</p>
|
||||
{{else}}
|
||||
<section class="card empty"><p>No signals yet. <a href="/signals/new">Write down the first one</a>: for example, “Teams complaining about the Microsoft 365 price rise switch within a quarter.”</p></section>
|
||||
{{end}}
|
||||
|
||||
<h2 id="campaigns">Campaigns in origami.chat and explee.com</h2>
|
||||
<p class="lede">Supermarket reads your campaigns, who they contacted, who replied, who was interested and who unsubscribed, every 6 hours. Give each campaign the signal it tests; its results count towards that signal. Interested people and people who replied show up in <a href="/prospects">Review</a>, and anyone who unsubscribed goes on the <a href="/prospects/suppressed">suppression list</a>.</p>
|
||||
|
||||
<div class="grid">
|
||||
{{range .Sources}}
|
||||
<section class="card">
|
||||
<h3>{{.Name}}</h3>
|
||||
{{if .Set}}
|
||||
{{with .Last}}<p class="small">{{if .Error}}<span class="warn-text">Last import failed {{ago .At}}: {{.Error}}</span>{{else}}Imported {{ago .At}}: {{.Campaigns}} campaigns, {{.Events}} new steps, {{.Prospects}} new people to review, {{.Suppressed}} unsubscribed.{{end}}</p>
|
||||
{{if .Warnings}}<details class="small"><summary>{{len .Warnings}} warnings</summary><ul>{{range .Warnings}}<li>{{.}}</li>{{end}}</ul></details>{{end}}
|
||||
{{else}}<p class="small">Not imported yet.</p>{{end}}
|
||||
<form method="post" action="/lead-sources/{{.ID}}/import" data-busy="Importing…"><button type="submit" class="secondary small">Import now</button></form>
|
||||
{{else}}<p class="small">Not connected. Save its API key under <a href="/settings/sources">Settings → Lead sources</a>.</p>{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
{{if .Campaigns}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Campaign</th><th>Numbers</th><th class="num">Spend</th><th>Signal</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Campaigns}}
|
||||
<tr>
|
||||
<td><strong>{{.Name}}</strong><br><span class="muted small">{{if eq .Source "origami"}}origami.chat{{else}}explee.com{{end}}{{with .Status}} · {{.}}{{end}} · read {{ago .SyncedAt}}</span></td>
|
||||
<td class="small">{{range $k, $v := .Stats}}{{if $v}}<span class="stat">{{$k}}: <strong>{{$v}}</strong></span> {{end}}{{end}}</td>
|
||||
<td class="num">{{if .SpendCents}}{{money .SpendCents}}{{end}}</td>
|
||||
<td>
|
||||
<form method="post" action="/signals/campaigns" class="row">
|
||||
<input type="hidden" name="source" value="{{.Source}}"><input type="hidden" name="id" value="{{.ID}}">
|
||||
{{$cur := .SignalID}}
|
||||
<select name="signal" data-autosubmit aria-label="Signal for {{.Name}}">
|
||||
<option value="0">No signal yet</option>
|
||||
{{range $d.Signals}}<option value="{{.ID}}" {{if eq .ID $cur}}selected{{end}}>{{.Name}}</option>{{end}}
|
||||
</select>
|
||||
<noscript><button type="submit" class="secondary small">Save</button></noscript>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,31 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
|
||||
<h2>Lead sources</h2>
|
||||
<p class="lede">The prospecting tools you test buying signals in. Supermarket only reads from them: campaigns and their numbers, who was contacted, who replied, who was interested and who unsubscribed. It never starts, changes or sends anything there. Results appear on <a href="/signals">Signals</a>.</p>
|
||||
|
||||
<form method="post" action="/settings/sources" autocomplete="off">
|
||||
{{range .Sources}}
|
||||
<section class="card">
|
||||
<h3>{{.Name}}</h3>
|
||||
{{template "key-field" (dict "F" .Key "Set" .Set)}}
|
||||
{{if eq .ID "origami"}}
|
||||
<label>Project <span class="muted small">(optional)</span> <input name="origami_project" value="{{$.Data.Project}}" placeholder="a project ID, to read only that project">
|
||||
<span class="help">If your organization has projects, the ID of the one to read. Leave empty to read the whole organization.</span></label>
|
||||
{{end}}
|
||||
{{if .Set}}
|
||||
<button type="button" class="secondary small" hx-post="/settings/sources/test/{{.ID}}" hx-target="#test-{{.ID}}" hx-indicator="#testing-{{.ID}}">Test</button>
|
||||
<span id="testing-{{.ID}}" class="htmx-indicator">Checking…</span>
|
||||
<div id="test-{{.ID}}"></div>
|
||||
{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
<div class="actions"><button type="submit">Save</button></div>
|
||||
</form>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
|
||||
{{define "test-result"}}
|
||||
{{with .Error}}<p class="error">{{.}}</p>{{end}}
|
||||
{{with .OK}}<p class="ok">{{.}}</p>{{end}}
|
||||
{{with .Sample}}<details><summary>What the API sends</summary>
|
||||
<p class="help">origami.chat doesn't document its responses, so Supermarket looks fields up by the names its docs use. If an import misses replies or contacts, this shows the real names.</p>
|
||||
<pre class="sample">{{.}}</pre></details>{{end}}
|
||||
{{end}}
|
||||
Reference in New Issue
Block a user