Phase 2 part 7: the end of the funnel

Posts can be written for a buying signal: the prompt gets its hypothesis
and angle, and links carry its campaign tag. Plausible (Stats API v2) is
read once a day for visitors on tagged links, recorded per signal as
Visited. Stripe (restricted key) is read every hour: $0 checkouts are
Signed up, paid invoices and one-time payments are Paid with their value,
tied to a signal by the checkout's utm_campaign metadata or the payer's
email. The Core's Cal.com has no API, so booking emails from Cal.com in
the outreach mailbox count as Booked. New Settings → Website & sales;
the signal page lists its posts and tagged links. Schema 11.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 06:42:03 -07:00
co-authored by Claude Opus 5.5
parent 90d73cf907
commit d23d5e2a87
32 changed files with 1775 additions and 26 deletions
+25 -1
View File
@@ -626,7 +626,31 @@ data. Each becomes an adapter behind a `leadsource` interface.
7. **Indirect and the end of the funnel**: content drafts tagged with a 7. **Indirect and the end of the funnel**: content drafts tagged with a
signal (UTM per signal), Plausible results per signal, Cal.com bookings, signal (UTM per signal), Plausible results per signal, Cal.com bookings,
and Stripe sign-ups and payments (pulled forward from Phase 4's Stripe and Stripe sign-ups and payments (pulled forward from Phase 4's Stripe
sync). sync). **Built 2026-11-22** (schema 11):
- **Content.** Drafts can be written for a signal (`drafts.signal_id`).
The prompt gets the signal's hypothesis and angle, and the UTM
campaign becomes the signal's slug. The signal page lists its posts
and the websites tagged with its campaign.
- **Plausible.** `internal/api/plausible` (Stats API v2) and
`internal/tracking`. Once a day it reads the completed days' visitors,
filtered to the signals' campaigns, by day, source, medium and
content. These become aggregate Visited events, with the channel from
source and medium. Sites come from the profile.
- **Stripe.** `internal/api/stripe`, with a restricted key. It reads
completed Checkout Sessions and paid invoices every hour. A $0
checkout is Signed up. Paid invoices, and one-time payments without
an invoice, are Paid with their value. `stripe_customers` keeps each
customer's signal: from checkout metadata `utm_campaign` (or
`signal`), or else from the email matching a prospect person or
company domain.
- **Cal.com.** The Core's Cal.com has no API: /api/v1 and /api/v2 both
return 404 (checked 2026-11-22). The user chose to read booking
notices from the outreach mailbox instead: emails from the
configured Cal.com sender count as Booked for the first address
that isn't ours. Cancellations, reschedules, requests and reminders
are skipped.
- **Still to do.** The cart has to save the UTM tags in the Checkout
Session's metadata. Settings → Website & sales says how.
8. **Later, with Phase 5 (sites)**: Hugo pages per signal, created, 8. **Later, with Phase 5 (sites)**: Hugo pages per signal, created,
duplicated or deleted from the scorecard, through Gitea PRs. duplicated or deleted from the scorecard, through Gitea PRs.
+2
View File
@@ -104,6 +104,8 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th
**Outreach (Prospects → Outreach, and Settings → Email).** On Review, *Write an email* or *Write a LinkedIn message* on a person has the AI draft one from their buying signal's hypothesis and angle, what's known about them and their company, and anything that happened before (an earlier reply, or a message you sent). *Draft* on the Outreach page does the same for up to 5 accepted people nobody has written to yet. Read and edit every draft. An email you *queue* goes out through your Core's mail server (mail.<your domain>, set up under Settings → Email): one at a time, at least a few minutes apart, within your sending hours and daily limit (20 by default), with your signature and an opt-out line under it, links to your sites tagged with the signal's campaign, and a copy in your Sent folder. Nothing goes to a suppressed address, an address that bounces, or someone emailed in the last two weeks. LinkedIn can't be automated: copy the message, open their profile, send it there and *Mark as sent*. Every 10 minutes Supermarket reads the inbox, read-only, for replies (matched to the email they answer, or by sender), bounces (the address is marked as bouncing) and requests to stop (the address goes on the suppression list); out-of-office replies are ignored. Sent messages count as Contacted and replies as Replied on the signal's scorecard. *Check the settings* signs in to both servers and looks up your domain's SPF, DKIM and DMARC records. **Outreach (Prospects → Outreach, and Settings → Email).** On Review, *Write an email* or *Write a LinkedIn message* on a person has the AI draft one from their buying signal's hypothesis and angle, what's known about them and their company, and anything that happened before (an earlier reply, or a message you sent). *Draft* on the Outreach page does the same for up to 5 accepted people nobody has written to yet. Read and edit every draft. An email you *queue* goes out through your Core's mail server (mail.<your domain>, set up under Settings → Email): one at a time, at least a few minutes apart, within your sending hours and daily limit (20 by default), with your signature and an opt-out line under it, links to your sites tagged with the signal's campaign, and a copy in your Sent folder. Nothing goes to a suppressed address, an address that bounces, or someone emailed in the last two weeks. LinkedIn can't be automated: copy the message, open their profile, send it there and *Mark as sent*. Every 10 minutes Supermarket reads the inbox, read-only, for replies (matched to the email they answer, or by sender), bounces (the address is marked as bouncing) and requests to stop (the address goes on the suppression list); out-of-office replies are ignored. Sent messages count as Contacted and replies as Replied on the signal's scorecard. *Check the settings* signs in to both servers and looks up your domain's SPF, DKIM and DMARC records.
**The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked.
**Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued. **Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued.
**The CRM queue (Prospects → CRM queue).** What Supermarket wants in EspoCRM waits in a queue, with the exact fields and how to recognise a record that's already there. `supermarket hermes` adds a Hermes scheduled job, `supermarket-crm`, that runs every 15 minutes: it calls Supermarket's `crm_pending_actions` tool, creates each record through the hub's EspoCRM tools unless a matching one exists, and reports each result with `crm_report_result`. Every 6 hours (or when you press *Sync on the next run*) it also copies your Leads, Accounts and Contacts to Supermarket with `crm_ingest`, so Supermarket can spot people and companies you already have. Before each run, the job runs `~/.hermes/scripts/supermarket-crm-check.sh`, which prints `crm-state` from the data folder; while that hasn't changed, Hermes skips the run and uses no AI. The page shows the command to run the job now, and *Send a test Lead* checks the whole path. Failed actions can be retried or cancelled; nothing is written to your CRM that isn't in the queue. **The CRM queue (Prospects → CRM queue).** What Supermarket wants in EspoCRM waits in a queue, with the exact fields and how to recognise a record that's already there. `supermarket hermes` adds a Hermes scheduled job, `supermarket-crm`, that runs every 15 minutes: it calls Supermarket's `crm_pending_actions` tool, creates each record through the hub's EspoCRM tools unless a matching one exists, and reports each result with `crm_report_result`. Every 6 hours (or when you press *Sync on the next run*) it also copies your Leads, Accounts and Contacts to Supermarket with `crm_ingest`, so Supermarket can spot people and companies you already have. Before each run, the job runs `~/.hermes/scripts/supermarket-crm-check.sh`, which prints `crm-state` from the data folder; while that hasn't changed, Hermes skips the run and uses no AI. The page shows the command to run the job now, and *Send a test Lead* checks the whole path. Failed actions can be retried or cancelled; nothing is written to your CRM that isn't in the queue.
+26
View File
@@ -248,6 +248,32 @@ Throughout, also notice:
- [ ] If EspoCRM can't be reached, the hint says whether the problem is - [ ] If EspoCRM can't be reached, the hint says whether the problem is
on the Core's side or Supermarket's. on the Core's side or Supermarket's.
### Website & sales (the end of the funnel)
- [ ] On Content, *For a buying signal* lists your signals. Posts written
for one speak to its situation, and when published their links carry
`utm_campaign=` the signal's tag.
- [ ] A signal's page lists the posts written for it, and your websites'
addresses tagged with its campaign; *Copy* copies one.
- [ ] Under Settings → Website & sales, Plausible's address is your Core's,
and the sites listed are your websites' domains.
- [ ] With a Plausible Stats API key saved, *Test* shows each site's
visitors in the last 30 days, and *Import now* says how many visitors
came on tagged links.
- [ ] Open a tagged link yourself; the next day (or after *Import now* the
day after), the signal shows a Visited step for that channel.
- [ ] With a restricted Stripe key saved, *Test* says it can read checkouts
and invoices, and whether it's live or test mode. *Sync now* lists
sign-ups and payments, and the customers table fills in.
- [ ] A payment from a prospect's email shows as Paid, with the amount, on
that prospect's signal, and the revenue on the scorecard.
- [ ] **(real)** A purchase through the shopping cart from a tagged link
counts for that signal (once the cart passes the tags to Stripe).
- [ ] With Cal.com's sending address saved under Settings → Email, a
booking made through your Cal.com link shows as Booked for the
person who booked (after the next inbox read). A cancellation
doesn't count.
## 7. Search ## 7. Search
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect - [ ] Searching for an inventory entry, a fetched item, a post, a prospect
+1
View File
@@ -159,6 +159,7 @@ func run(log *slog.Logger) error {
go srv.RunImports(ctx) go srv.RunImports(ctx)
go srv.RunDiscovery(ctx) go srv.RunDiscovery(ctx)
go srv.RunOutreach(ctx) go srv.RunOutreach(ctx)
go srv.RunTracking(ctx)
// A sync falls due, and a claim times out, without anything being // A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute. // written: refresh the state file each minute.
go func() { go func() {
+108
View File
@@ -0,0 +1,108 @@
// Package plausible reads visit numbers from Plausible's Stats API v2
// (https://plausible.io/docs/stats-api), on plausible.io or a self-hosted
// Plausible such as the one on a Federated Core.
package plausible
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// ErrUnauthorized means the key was refused.
var ErrUnauthorized = errors.New("Plausible refused the API key")
// Client calls one Plausible with one key.
type Client struct {
base, key string
http *http.Client
}
// New takes Plausible's address (e.g. https://plausible.example.com) and a
// Stats API key.
func New(base, key string) *Client {
return &Client{base: strings.TrimRight(base, "/"), key: key, http: &http.Client{Timeout: time.Minute}}
}
// Query is a Stats API v2 query.
type Query struct {
SiteID string `json:"site_id"`
Metrics []string `json:"metrics"`
DateRange any `json:"date_range"` // "7d", or ["2026-11-01", "2026-11-21"]
Dimensions []string `json:"dimensions,omitempty"`
Filters [][]any `json:"filters,omitempty"`
Pagination *Pagination `json:"pagination,omitempty"`
}
// Pagination limits the rows.
type Pagination struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
}
// Row is one result: the dimensions' values, then the metrics'.
type Row struct {
Metrics []float64 `json:"metrics"`
Dimensions []string `json:"dimensions"`
}
// Run sends a query.
func (c *Client) Run(ctx context.Context, q Query) ([]Row, error) {
body, err := json.Marshal(q)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.base+"/api/v2/query", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.key)
req.Header.Set("Content-Type", "application/json")
res, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, 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 {
var e struct {
Error string `json:"error"`
}
if json.Unmarshal(raw, &e) == nil && e.Error != "" {
return nil, fmt.Errorf("Plausible: %s", e.Error)
}
return nil, fmt.Errorf("Plausible: HTTP %d: %s", res.StatusCode, strings.TrimSpace(string(raw[:min(len(raw), 300)])))
}
var out struct {
Results []Row `json:"results"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("Plausible: %w", err)
}
return out.Results, nil
}
// Visitors is a site's visitors over the last 30 days: a cheap check that
// the key can read the site.
func (c *Client) Visitors(ctx context.Context, site string) (int, error) {
rows, err := c.Run(ctx, Query{SiteID: site, Metrics: []string{"visitors"}, DateRange: "30d"})
if err != nil {
return 0, err
}
if len(rows) == 0 || len(rows[0].Metrics) == 0 {
return 0, nil
}
return int(rows[0].Metrics[0]), nil
}
+167
View File
@@ -0,0 +1,167 @@
// Package stripe reads checkouts and paid invoices from Stripe's API
// (https://docs.stripe.com/api) with a restricted, read-only key. It never
// creates or changes anything in Stripe.
package stripe
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const apiBase = "https://api.stripe.com"
// ErrUnauthorized means the key was refused.
var ErrUnauthorized = errors.New("Stripe 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: time.Minute}}
}
// WithBase points the client at another server (for tests).
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
return c
}
// Live reports whether the key is for live data, not test mode.
func (c *Client) Live() bool { return strings.Contains(c.key, "_live_") }
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("Authorization", "Bearer "+c.key)
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 32<<20))
if err != nil {
return err
}
if res.StatusCode == http.StatusUnauthorized {
return ErrUnauthorized
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" {
return fmt.Errorf("Stripe %s: %s", path, e.Error.Message)
}
return fmt.Errorf("Stripe %s: HTTP %d", path, res.StatusCode)
}
return json.Unmarshal(raw, out)
}
// list reads every page of a list endpoint, oldest first.
func list[T interface{ id() string }](ctx context.Context, c *Client, path string, q url.Values, max int) ([]T, error) {
var all []T
q.Set("limit", "100")
for {
var page struct {
Data []T `json:"data"`
HasMore bool `json:"has_more"`
}
if err := c.get(ctx, path, q, &page); err != nil {
return nil, err
}
all = append(all, page.Data...)
if !page.HasMore || len(page.Data) == 0 || len(all) >= max {
break
}
q.Set("starting_after", page.Data[len(page.Data)-1].id())
}
// Stripe lists newest first.
for i, j := 0, len(all)-1; i < j; i, j = i+1, j-1 {
all[i], all[j] = all[j], all[i]
}
return all, nil
}
// Session is a completed Checkout Session: someone bought, subscribed or
// started a trial.
type Session struct {
ID string `json:"id"`
Created int64 `json:"created"`
Status string `json:"status"` // complete, open, expired
Mode string `json:"mode"` // payment, subscription, setup
PaymentStatus string `json:"payment_status"` // paid, unpaid, no_payment_required
AmountTotal int64 `json:"amount_total"`
Currency string `json:"currency"`
Customer string `json:"customer"`
Invoice string `json:"invoice"`
CustomerDetails struct {
Email string `json:"email"`
Name string `json:"name"`
} `json:"customer_details"`
Metadata map[string]string `json:"metadata"`
}
func (s Session) id() string { return s.ID }
// Sessions lists the completed Checkout Sessions created since a time.
func (c *Client) Sessions(ctx context.Context, since time.Time) ([]Session, error) {
q := url.Values{"status": {"complete"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
return list[Session](ctx, c, "/v1/checkout/sessions", q, 5000)
}
// Invoice is a paid invoice: a subscription's first or later payment.
type Invoice struct {
ID string `json:"id"`
Created int64 `json:"created"`
Customer string `json:"customer"`
CustomerEmail string `json:"customer_email"`
CustomerName string `json:"customer_name"`
AmountPaid int64 `json:"amount_paid"`
Currency string `json:"currency"`
BillingReason string `json:"billing_reason"` // subscription_create, subscription_cycle, manual…
Transitions struct {
PaidAt int64 `json:"paid_at"`
} `json:"status_transitions"`
}
func (i Invoice) id() string { return i.ID }
// PaidInvoices lists the paid invoices created since a time.
func (c *Client) PaidInvoices(ctx context.Context, since time.Time) ([]Invoice, error) {
q := url.Values{"status": {"paid"}, "created[gte]": {strconv.FormatInt(since.Unix(), 10)}}
return list[Invoice](ctx, c, "/v1/invoices", q, 5000)
}
// Check reads one session and one invoice, so a key missing either
// permission says which.
func (c *Client) Check(ctx context.Context) error {
var page struct {
Data []json.RawMessage `json:"data"`
}
if err := c.get(ctx, "/v1/checkout/sessions", url.Values{"limit": {"1"}}, &page); err != nil {
return fmt.Errorf("reading checkouts: %w", err)
}
if err := c.get(ctx, "/v1/invoices", url.Values{"limit": {"1"}}, &page); err != nil {
return fmt.Errorf("reading invoices: %w", err)
}
return nil
}
+31
View File
@@ -14,6 +14,7 @@ import (
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/models" "supermarket/internal/models"
"supermarket/internal/profile" "supermarket/internal/profile"
"supermarket/internal/signals"
"supermarket/internal/utm" "supermarket/internal/utm"
) )
@@ -335,3 +336,33 @@ func TestScheduleAndDue(t *testing.T) {
t.Errorf("unscheduled: %+v", got) t.Errorf("unscheduled: %+v", got)
} }
} }
func TestDraftsForSignal(t *testing.T) {
d := openDB(t)
sig := &signals.Signal{Name: "Leaving M365", Slug: "leaving-m365", Angle: "A flat price"}
if err := signals.Save(d, sig); err != nil {
t.Fatal(err)
}
if _, err := CreateDrafts(d, []Draft{{InventoryName: "Rival", Kind: "competitor", Channel: ChannelX, Content: "Hi", SignalID: sig.ID},
{InventoryName: "Rival", Kind: "competitor", Channel: ChannelLinkedIn, Content: "Plain"}}); err != nil {
t.Fatal(err)
}
list, err := ForSignal(d, sig.ID, 10)
if err != nil || len(list) != 1 || list[0].SignalSlug != "leaving-m365" {
t.Fatalf("for signal: %+v %v", list, err)
}
if p := list[0].UTM(); p.Campaign != "leaving-m365" || p.Medium != "social" {
t.Errorf("utm: %+v", p)
}
all, _ := ListDrafts(d, 10, StatusDraft)
for _, dr := range all {
if dr.SignalID == 0 && dr.UTM().Campaign != "competitor" {
t.Errorf("plain draft's campaign: %+v", dr.UTM())
}
}
prompt := userPrompt(Request{Profile: &profile.Profile{Name: "Us"}, Entry: &inventory.Entry{Name: "Rival", Relationship: "competitor"},
Channels: []string{ChannelX}, Signal: sig}, "")
if !strings.Contains(prompt, "Leaving M365") || !strings.Contains(prompt, "A flat price") {
t.Errorf("prompt lacks the signal: %s", prompt)
}
}
+24 -5
View File
@@ -78,6 +78,8 @@ type Draft struct {
UpdatedAt time.Time UpdatedAt time.Time
PublishedAt time.Time PublishedAt time.Time
PublishAt time.Time // when a scheduled draft goes out PublishAt time.Time // when a scheduled draft goes out
SignalID int64 // the buying signal it was written for; 0: none
SignalSlug string // that signal's campaign tag
} }
// Length is the draft's length as its channel counts it, including the // Length is the draft's length as its channel counts it, including the
@@ -167,9 +169,13 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
return "", fmt.Errorf("unknown channel %q", dr.Channel) return "", fmt.Errorf("unknown channel %q", dr.Channel)
} }
ids, _ := json.Marshal(nonNil(dr.ItemIDs)) ids, _ := json.Marshal(nonNil(dr.ItemIDs))
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids) var sig any
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel, if dr.SignalID != 0 {
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil { sig = dr.SignalID
}
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig); err != nil {
return "", err return "", err
} }
for _, id := range dr.ItemIDs { for _, id := range dr.ItemIDs {
@@ -193,7 +199,8 @@ func nonNil(s []string) []string {
} }
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error, const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target` post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target,
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), '')`
func scanDrafts(rows *sql.Rows) ([]Draft, error) { func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close() defer rows.Close()
@@ -202,7 +209,8 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
var dr Draft var dr Draft
var ids, created, updated, published, publishAt string var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content, if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target); err != nil { &dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target,
&dr.SignalID, &dr.SignalSlug); err != nil {
return nil, err return nil, err
} }
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs) _ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
@@ -301,6 +309,17 @@ func RecoverInterrupted(d *db.DB) (int, error) {
return int(n), nil return int(n), nil
} }
// ForSignal lists the posts written for a signal, newest first: the
// published ones, then the rest that aren't discarded.
func ForSignal(d *db.DB, signalID int64, limit int) ([]Draft, error) {
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE signal_id = ? AND status != ?
ORDER BY published_at IS NULL, published_at DESC, id DESC LIMIT ?`, signalID, StatusDiscarded, limit)
if err != nil {
return nil, err
}
return scanDrafts(rows)
}
// CountDrafts is how many drafts wait for review. // CountDrafts is how many drafts wait for review.
func CountDrafts(d *db.DB) (int, error) { func CountDrafts(d *db.DB) (int, error) {
var n int var n int
+23 -1
View File
@@ -12,6 +12,7 @@ import (
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/profile" "supermarket/internal/profile"
"supermarket/internal/signals"
) )
// Request is what a set of drafts is written from. // Request is what a set of drafts is written from.
@@ -24,6 +25,15 @@ type Request struct {
// if its rules couldn't be read). // if its rules couldn't be read).
Subreddit string Subreddit string
SubredditInfo *reddit.Subreddit SubredditInfo *reddit.Subreddit
// Signal, if set, is the buying signal the posts are written for.
Signal *signals.Signal
}
func (r *Request) signalID() int64 {
if r.Signal == nil {
return 0
}
return r.Signal.ID
} }
// SourceURL is the link the drafts carry: the first item's. // SourceURL is the link the drafts carry: the first item's.
@@ -122,7 +132,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
if r := []rune(title); len(r) > RedditTitleLimit { if r := []rune(title); len(r) > RedditTitleLimit {
title = string(r[:RedditTitleLimit-1]) + "…" title = string(r[:RedditTitleLimit-1]) + "…"
} }
drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, SignalID: req.signalID(),
Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body), Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body),
SourceURL: src, ItemIDs: ids, Status: StatusDraft}) SourceURL: src, ItemIDs: ids, Status: StatusDraft})
continue continue
@@ -144,6 +154,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
InventoryName: name, InventoryName: name,
Kind: req.Entry.Relationship, Kind: req.Entry.Relationship,
Channel: ch, Channel: ch,
SignalID: req.signalID(),
Content: text, Content: text,
SourceURL: src, SourceURL: src,
ItemIDs: ids, ItemIDs: ids,
@@ -264,6 +275,17 @@ func userPrompt(req Request, src string) string {
fmt.Fprintf(&b, "%s\n</item>\n", strings.TrimSpace(it.Body)) fmt.Fprintf(&b, "%s\n</item>\n", strings.TrimSpace(it.Body))
} }
if sig := req.Signal; sig != nil {
fmt.Fprintf(&b, "\nWrite it for readers in this situation (a buying signal we're testing): %s.\n", sig.Name)
if sig.Hypothesis != "" {
fmt.Fprintf(&b, "Why they may buy now: %s\n", oneLine(sig.Hypothesis))
}
if sig.Angle != "" {
fmt.Fprintf(&b, "The angle (their pain, and what we promise): %s\n", oneLine(sig.Angle))
}
b.WriteString("Connect the source material to that situation where it honestly fits; don't force it.\n")
}
b.WriteString("\nWrite one post for each channel below. Reply with JSON whose keys are the channel IDs.\n") b.WriteString("\nWrite one post for each channel below. Reply with JSON whose keys are the channel IDs.\n")
for _, ch := range req.Channels { for _, ch := range req.Channels {
limit := limitFor(ch, src) limit := limitFor(ch, src)
+6 -1
View File
@@ -86,7 +86,12 @@ func (d *Draft) UTM() utm.Params {
if slug := utm.Slug(d.InventoryName); slug != "" { if slug := utm.Slug(d.InventoryName); slug != "" {
content = slug + "-" + fmt.Sprint(d.ID) content = slug + "-" + fmt.Sprint(d.ID)
} }
return utm.Params{Source: d.Channel, Medium: "social", Campaign: d.Kind, Content: content} campaign := d.Kind
if d.SignalSlug != "" {
// Written for a buying signal: its visits count for the signal.
campaign = d.SignalSlug
}
return utm.Params{Source: d.Channel, Medium: "social", Campaign: campaign, Content: content}
} }
// MarkPosted records a draft the user posted by hand (on a network // MarkPosted records a draft the user posted by hand (on a network
+20
View File
@@ -340,6 +340,26 @@ CREATE INDEX outreach_by_status ON outreach (status, id);
CREATE INDEX outreach_by_contact ON outreach (contact_id); CREATE INDEX outreach_by_contact ON outreach (contact_id);
CREATE INDEX outreach_by_to ON outreach (to_addr); CREATE INDEX outreach_by_to ON outreach (to_addr);
CREATE UNIQUE INDEX outreach_message_id ON outreach (message_id) WHERE message_id != ''; CREATE UNIQUE INDEX outreach_message_id ON outreach (message_id) WHERE message_id != '';
`,
// 11: the end of the funnel. Posts written for a buying signal; Stripe
// customers with the campaign they came from; where each import stopped
// is kept in settings.
`
ALTER TABLE drafts ADD COLUMN signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL;
CREATE INDEX drafts_by_signal ON drafts (signal_id) WHERE signal_id IS NOT NULL;
CREATE TABLE stripe_customers (
id TEXT PRIMARY KEY, -- cus_…
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
name TEXT NOT NULL DEFAULT '',
signal_id INTEGER REFERENCES signals (id) ON DELETE SET NULL,
subject TEXT NOT NULL DEFAULT '', -- contact:12 when they're a prospect
channel TEXT NOT NULL DEFAULT '',
utm_campaign TEXT NOT NULL DEFAULT '',
utm_source TEXT NOT NULL DEFAULT '',
utm_medium TEXT NOT NULL DEFAULT '',
first_seen TEXT NOT NULL
);
`, `,
} }
+103 -6
View File
@@ -21,6 +21,7 @@ import (
"supermarket/internal/db" "supermarket/internal/db"
"supermarket/internal/prospects" "supermarket/internal/prospects"
"supermarket/internal/signals"
) )
// imapClient connects and signs in to the mailbox. // imapClient connects and signs in to the mailbox.
@@ -109,6 +110,7 @@ type Check struct {
Stops int `json:"stops"` Stops int `json:"stops"`
Bounces int `json:"bounces"` Bounces int `json:"bounces"`
AutoReplies int `json:"auto_replies"` AutoReplies int `json:"auto_replies"`
Bookings int `json:"bookings"`
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
} }
@@ -170,8 +172,19 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
if err != nil { if err != nil {
return err return err
} }
if !first.Valid { var since time.Time
// Nothing sent yet: start from here, without reading older mail. if first.Valid {
since, _ = time.Parse(timeFormat, first.String)
since = since.AddDate(0, 0, -1)
}
if s.BookingFrom != "" {
if b := now.AddDate(0, 0, -bookingDays); since.IsZero() || b.Before(since) {
since = b
}
}
if since.IsZero() {
// Nothing sent yet and no bookings to look for: start from here,
// without reading older mail.
return d.PutJSON(stateKey, inboxState{UIDValidity: mbox.UidValidity, LastUID: mbox.UidNext - 1}) return d.PutJSON(stateKey, inboxState{UIDValidity: mbox.UidValidity, LastUID: mbox.UidNext - 1})
} }
criteria := imap.NewSearchCriteria() criteria := imap.NewSearchCriteria()
@@ -179,8 +192,7 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
criteria.Uid = new(imap.SeqSet) criteria.Uid = new(imap.SeqSet)
criteria.Uid.AddRange(state.LastUID+1, 0) criteria.Uid.AddRange(state.LastUID+1, 0)
} else { } else {
since, _ := time.Parse(timeFormat, first.String) criteria.Since = since
criteria.Since = since.AddDate(0, 0, -1)
} }
uids, err := c.UidSearch(criteria) uids, err := c.UidSearch(criteria)
if err != nil { if err != nil {
@@ -202,7 +214,7 @@ func checkReplies(ctx context.Context, d *db.DB, s Settings, password string, no
} }
for start := 0; start < len(fresh); start += 100 { for start := 0; start < len(fresh); start += 100 {
batch := fresh[start:min(start+100, len(fresh))] batch := fresh[start:min(start+100, len(fresh))]
if err := readBatch(c, d, batch, res); err != nil { if err := readBatch(c, d, s, batch, res); err != nil {
return err return err
} }
last = max(last, batch[len(batch)-1]) last = max(last, batch[len(batch)-1])
@@ -244,6 +256,9 @@ var fullSection = &imap.BodySectionName{Peek: true}
// found is a message that answers, or bounces, one of ours. // found is a message that answers, or bounces, one of ours.
type found struct { type found struct {
uid uint32 uid uint32
booking bool
subject string
skip []string // addresses that aren't the attendee: ours, Cal.com's
msg *Message msg *Message
bounce bool bounce bool
id string // its Message-ID id string // its Message-ID
@@ -252,7 +267,7 @@ type found struct {
// readBatch looks at the headers of some new messages, then reads the ones // readBatch looks at the headers of some new messages, then reads the ones
// that concern outreach. // that concern outreach.
func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error { func readBatch(c *client.Client, d *db.DB, s Settings, uids []uint32, res *Check) error {
set := new(imap.SeqSet) set := new(imap.SeqSet)
set.AddNum(uids...) set.AddNum(uids...)
ch := make(chan *imap.Message, len(uids)) ch := make(chan *imap.Message, len(uids))
@@ -275,6 +290,17 @@ func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error {
if len(m.Envelope.From) > 0 { if len(m.Envelope.From) > 0 {
fromAddr = strings.ToLower(m.Envelope.From[0].Address()) fromAddr = strings.ToLower(m.Envelope.From[0].Address())
} }
if s.BookingFrom != "" && fromAddr == strings.ToLower(s.BookingFrom) {
skip := []string{fromAddr, strings.ToLower(s.FromAddress), strings.ToLower(s.Username)}
for _, a := range m.Envelope.To {
skip = append(skip, strings.ToLower(a.Address()))
}
if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, booking: true, subject: m.Envelope.Subject, skip: skip,
id: m.Envelope.MessageId, date: m.Envelope.Date})
}
continue
}
if isBounce(fromAddr, h.Get("Content-Type")) { if isBounce(fromAddr, h.Get("Content-Type")) {
if m.Size < 5<<20 { if m.Size < 5<<20 {
todo = append(todo, found{uid: m.Uid, bounce: true, id: m.Envelope.MessageId, date: m.Envelope.Date}) todo = append(todo, found{uid: m.Uid, bounce: true, id: m.Envelope.MessageId, date: m.Envelope.Date})
@@ -301,6 +327,12 @@ func readBatch(c *client.Client, d *db.DB, uids []uint32, res *Check) error {
if err != nil { if err != nil {
return err return err
} }
if f.booking {
if err := booked(d, f, raw, res); err != nil {
return err
}
continue
}
if f.bounce { if f.bounce {
if err := bounced(d, raw, res); err != nil { if err := bounced(d, raw, res); err != nil {
return err return err
@@ -517,3 +549,68 @@ func WantsStop(reply string) bool {
first, _, _ := strings.Cut(reply, "\n") first, _, _ := strings.Cut(reply, "\n")
return stopAlone.MatchString(strings.TrimSpace(first)) || stopPhrases.MatchString(reply) return stopAlone.MatchString(strings.TrimSpace(first)) || stopPhrases.MatchString(reply)
} }
// bookingDays is how far back bookings are looked for the first time.
const bookingDays = 30
var (
emailRe = regexp.MustCompile(`[A-Za-z0-9._%+'-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`)
notNewBooking = regexp.MustCompile(`(?i)cancel|reschedul|declined|rejected|reminder|request`)
)
// booked records a Cal.com booking notice as a Booked step for the person
// who booked: the first address in it that isn't ours or Cal.com's. Notices
// of cancellations, reschedules and reminders are skipped.
func booked(d *db.DB, f found, raw []byte, res *Check) error {
if notNewBooking.MatchString(f.subject) {
return nil
}
text := plainText(raw)
attendee := ""
for _, a := range emailRe.FindAllString(text, -1) {
a = strings.ToLower(strings.Trim(a, ".'"))
local, _, _ := strings.Cut(a, "@")
if local == "noreply" || local == "no-reply" || local == "notifications" || contains(f.skip, a) {
continue
}
attendee = a
break
}
if attendee == "" {
return nil
}
at := f.date
if at.IsZero() {
at = time.Now()
}
ev := signals.Event{Stage: signals.StageBooked, Channel: "website", Email: attendee, Source: signals.SourceSupermarket,
ExternalID: "booking:" + f.id, Note: truncate(strings.TrimSpace(f.subject), 200), At: at}
if f.id == "" {
ev.ExternalID = "booking:" + attendee + ":" + at.UTC().Format("2006-01-02T15")
}
var id, sig int64
if err := d.QueryRow(`SELECT p.id, coalesce(p.signal_id, c.signal_id, 0) FROM prospect_contacts p
LEFT JOIN prospect_companies c ON c.id = p.company_id WHERE p.email = ? LIMIT 1`, attendee).Scan(&id, &sig); err == nil {
ev.Subject, ev.SignalID = prospects.Subject("contact", id), sig
var ch string
if d.QueryRow(`SELECT channel FROM outreach WHERE contact_id = ? AND status = 'sent' ORDER BY sent_at DESC LIMIT 1`, id).Scan(&ch) == nil {
ev.Channel = ch
}
} else {
ev.Subject = "booking:" + attendee
}
added, err := signals.Record(d, ev)
if added {
res.Bookings++
}
return err
}
func contains(list []string, v string) bool {
for _, x := range list {
if x == v {
return true
}
}
return false
}
+40
View File
@@ -534,3 +534,43 @@ func TestSettings(t *testing.T) {
t.Errorf("dns: %+v", c) t.Errorf("dns: %+v", c)
} }
} }
func TestBookings(t *testing.T) {
d := openDB(t)
s := imapServer(t)
s.BookingFrom = "calcom@example.com"
ctx := context.Background()
ann := person(t, d, "Ann", "ann@acme.example")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: Pat Lee <pat@example.com>\nSubject: New event: 30 min between Pat Lee and Ann Doe\n"+
"Message-ID: <b1@cal>\nContent-Type: text/plain\n\nWhat: 30 min\nWho: Pat Lee - Organizer pat@example.com\nAnn Doe ann@acme.example\n")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: pat@example.com\nSubject: Event cancelled: 30 min with Ann Doe\n"+
"Message-ID: <b2@cal>\n\nCancelled. ann@acme.example\n")
deliver(t, s, "From: Cal.com <calcom@example.com>\nTo: pat@example.com\nSubject: New event: Intro between Pat Lee and Zed\n"+
"Message-ID: <b3@cal>\nContent-Type: text/html\n\n<p>Who: <a href=\"mailto:noreply@cal.example\">x</a> zed@else.example</p>\n")
res, err := CheckReplies(ctx, d, s, "password", now)
if err != nil {
t.Fatal(err)
}
if res.Bookings != 2 {
t.Fatalf("check: %+v", res)
}
evs, _ := signals.SubjectEvents(d, prospects.Subject("contact", ann))
var booked *signals.Event
for i := range evs {
if evs[i].Stage == signals.StageBooked {
booked = &evs[i]
}
}
if booked == nil || booked.SignalID == 0 || booked.Email != "ann@acme.example" || !strings.Contains(booked.Note, "30 min") {
t.Errorf("ann's booking: %+v", evs)
}
if zed, _ := signals.SubjectEvents(d, "booking:zed@else.example"); len(zed) != 1 || zed[0].SignalID != 0 {
t.Errorf("zed's booking: %+v", zed)
}
// Read again: nothing new.
if res, _ := CheckReplies(ctx, d, s, "password", now); res.Bookings != 0 {
t.Errorf("again: %+v", res)
}
}
+7 -2
View File
@@ -36,6 +36,9 @@ type Settings struct {
SchedulingLink string `json:"scheduling_link"` // offered as the next step, if set SchedulingLink string `json:"scheduling_link"` // offered as the next step, if set
SaveToSent bool `json:"save_to_sent"` // put a copy in the mailbox's Sent folder SaveToSent bool `json:"save_to_sent"` // put a copy in the mailbox's Sent folder
ReadReplies bool `json:"read_replies"` ReadReplies bool `json:"read_replies"`
// BookingFrom is the address Cal.com sends booking notices from; its
// emails in the inbox count as bookings.
BookingFrom string `json:"booking_from"`
// Insecure allows a mail server without TLS. Only tests set it. // Insecure allows a mail server without TLS. Only tests set it.
Insecure bool `json:"-"` Insecure bool `json:"-"`
@@ -94,13 +97,15 @@ func Save(d *db.DB, s Settings) error {
// Check finds settings that can't work. // Check finds settings that can't work.
func (s *Settings) Check() error { func (s *Settings) Check() error {
for _, f := range []*string{&s.SMTPHost, &s.IMAPHost, &s.Username, &s.FromName, &s.FromAddress, &s.SchedulingLink} { for _, f := range []*string{&s.SMTPHost, &s.IMAPHost, &s.Username, &s.FromName, &s.FromAddress, &s.SchedulingLink, &s.BookingFrom} {
*f = strings.TrimSpace(*f) *f = strings.TrimSpace(*f)
} }
s.FromAddress = strings.ToLower(s.FromAddress) s.FromAddress, s.BookingFrom = strings.ToLower(s.FromAddress), strings.ToLower(s.BookingFrom)
switch { switch {
case s.FromAddress != "" && !strings.Contains(s.FromAddress, "@"): case s.FromAddress != "" && !strings.Contains(s.FromAddress, "@"):
return errors.New("the From address isn't an email address") return errors.New("the From address isn't an email address")
case s.BookingFrom != "" && !strings.Contains(s.BookingFrom, "@"):
return errors.New("Cal.com's sending address isn't an email address")
case s.SMTPPort < 1 || s.SMTPPort > 65535 || s.IMAPPort < 1 || s.IMAPPort > 65535: case s.SMTPPort < 1 || s.SMTPPort > 65535 || s.IMAPPort < 1 || s.IMAPPort > 65535:
return errors.New("a port must be between 1 and 65535") return errors.New("a port must be between 1 and 65535")
case s.DailyLimit < 1 || s.DailyLimit > 200: case s.DailyLimit < 1 || s.DailyLimit > 200:
+3
View File
@@ -39,6 +39,9 @@ const (
MailPassword = "mail.password" // the outreach mailbox on the Core MailPassword = "mail.password" // the outreach mailbox on the Core
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
RedditClientID = "reddit.client_id" RedditClientID = "reddit.client_id"
RedditClientSecret = "reddit.client_secret" RedditClientSecret = "reddit.client_secret"
RedditAccessToken = "reddit.access_token" RedditAccessToken = "reddit.access_token"
+285
View File
@@ -0,0 +1,285 @@
package tracking
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/api/stripe"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
// Customer is a Stripe customer and where they came from.
type Customer struct {
ID string
Email string
Name string
SignalID int64
Subject string // contact:12 or company:3 when they're a prospect; else stripe:<id>
Channel string
Campaign string
}
// stripeState is where the last sync stopped.
type stripeState struct {
Sessions int64 `json:"sessions"` // created time of the newest session read
Invoices int64 `json:"invoices"`
}
const stripeStateKey = "tracking:stripe-state"
// firstStripeDays is how far back the first sync reads.
const firstStripeDays = 90
// SyncStripe reads new completed checkouts and paid invoices. A checkout
// with nothing to pay (a trial or a free plan) counts as Signed up; money
// paid counts as Paid, with its amount. Each customer is tied to a signal by
// the utm_campaign the shopping cart saved in the checkout's metadata, or
// else by their email: a prospect's, or one at a prospect company's domain.
func SyncStripe(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time) (*Result, error) {
res := &Result{At: now}
var st stripeState
if _, err := d.GetJSON(stripeStateKey, &st); err != nil {
return save(d, SourceStripe, res, err)
}
first := now.AddDate(0, 0, -firstStripeDays).Unix()
if st.Sessions == 0 {
st.Sessions = first
}
if st.Invoices == 0 {
st.Invoices = first
}
tags, err := slugs(d)
if err != nil {
return save(d, SourceStripe, res, err)
}
sessions, err := c.Sessions(ctx, time.Unix(st.Sessions, 0))
if err != nil {
return save(d, SourceStripe, res, err)
}
var signups, payments int
var revenue int64
for _, s := range sessions {
key := s.Customer
if key == "" {
key = "guest:" + s.ID
}
cust, err := customer(d, tags, key, s.CustomerDetails.Email, s.CustomerDetails.Name, s.Metadata, time.Unix(s.Created, 0))
if err != nil {
return save(d, SourceStripe, res, err)
}
at := time.Unix(s.Created, 0)
switch {
case s.AmountTotal == 0 && s.Mode != "setup":
added, err := record(d, cust, signals.StageSignedUp, "cs:"+s.ID, 0, s.Currency, "Checkout: "+planNote(s), at)
if err != nil {
return save(d, SourceStripe, res, err)
}
if added {
signups++
}
case s.Mode == "payment" && s.PaymentStatus == "paid" && s.Invoice == "":
// A one-time payment without an invoice; the others are
// counted from their invoices.
added, err := record(d, cust, signals.StagePaid, "cs:"+s.ID, s.AmountTotal, s.Currency, "One-time payment", at)
if err != nil {
return save(d, SourceStripe, res, err)
}
if added {
payments++
revenue += s.AmountTotal
}
}
st.Sessions = max(st.Sessions, s.Created)
}
invoices, err := c.PaidInvoices(ctx, time.Unix(st.Invoices, 0))
if err != nil {
return save(d, SourceStripe, res, err)
}
for _, inv := range invoices {
st.Invoices = max(st.Invoices, inv.Created)
if inv.AmountPaid <= 0 {
continue
}
key := inv.Customer
if key == "" {
key = "guest:" + inv.ID
}
cust, err := customer(d, tags, key, inv.CustomerEmail, inv.CustomerName, nil, time.Unix(inv.Created, 0))
if err != nil {
return save(d, SourceStripe, res, err)
}
at := time.Unix(inv.Transitions.PaidAt, 0)
if inv.Transitions.PaidAt == 0 {
at = time.Unix(inv.Created, 0)
}
note := "Invoice"
switch inv.BillingReason {
case "subscription_create":
note = "First subscription payment"
case "subscription_cycle":
note = "Subscription renewal"
case "subscription_update":
note = "Subscription change"
}
added, err := record(d, cust, signals.StagePaid, "in:"+inv.ID, inv.AmountPaid, inv.Currency, note, at)
if err != nil {
return save(d, SourceStripe, res, err)
}
if added {
payments++
revenue += inv.AmountPaid
}
}
if err := d.PutJSON(stripeStateKey, st); err != nil {
return save(d, SourceStripe, res, err)
}
res.Added = signups + payments
res.Detail = fmt.Sprintf("%s and %s (%s).", plural(signups, "sign-up"), plural(payments, "payment"), money(revenue))
return save(d, SourceStripe, res, nil)
}
func planNote(s stripe.Session) string {
if s.Mode == "subscription" {
return "a trial or free plan"
}
return "nothing to pay"
}
func money(cents int64) string {
return fmt.Sprintf("%d.%02d", cents/100, cents%100)
}
// record adds one Stripe step to the funnel.
func record(d *db.DB, c *Customer, stage, id string, cents int64, currency, note string, at time.Time) (bool, error) {
if currency != "" {
note += " (" + strings.ToUpper(currency) + ")"
}
return signals.Record(d, signals.Event{
SignalID: c.SignalID, Stage: stage, Channel: c.Channel, Subject: c.Subject, Email: c.Email,
Source: SourceStripe, ExternalID: id, ValueCents: cents, Note: note, At: at,
})
}
// customer returns the stored customer, adding or completing it from what
// the checkout or invoice says.
func customer(d *db.DB, tags map[string]int64, id, email, name string, meta map[string]string, now time.Time) (*Customer, error) {
c := &Customer{ID: id}
var sig sql.NullInt64
err := d.QueryRow(`SELECT email, name, signal_id, subject, channel, utm_campaign FROM stripe_customers WHERE id = ?`, id).
Scan(&c.Email, &c.Name, &sig, &c.Subject, &c.Channel, &c.Campaign)
known := err == nil
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
c.SignalID = sig.Int64
if c.Email == "" {
c.Email = strings.ToLower(strings.TrimSpace(email))
}
if c.Name == "" {
c.Name = strings.TrimSpace(name)
}
var source, medium string
if meta != nil {
campaign := strings.ToLower(strings.TrimSpace(meta["utm_campaign"]))
if campaign == "" {
campaign = strings.ToLower(strings.TrimSpace(meta["signal"]))
}
source, medium = meta["utm_source"], meta["utm_medium"]
if s, ok := tags[campaign]; ok && c.SignalID == 0 {
c.SignalID, c.Campaign = s, campaign
c.Channel = Channel(source, medium)
}
}
if c.Subject == "" || strings.HasPrefix(c.Subject, "stripe:") {
if subj, s, ch := matchProspect(d, c.Email); subj != "" {
c.Subject = subj
if c.SignalID == 0 {
c.SignalID = s
}
if c.Channel == "" {
c.Channel = ch
}
}
}
if c.Subject == "" {
c.Subject = "stripe:" + id
}
if c.Channel == "" {
c.Channel = "website"
}
if known {
_, err = d.Exec(`UPDATE stripe_customers SET email = ?, name = ?, signal_id = ?, subject = ?, channel = ?, utm_campaign = ?,
utm_source = CASE WHEN utm_source = '' THEN ? ELSE utm_source END,
utm_medium = CASE WHEN utm_medium = '' THEN ? ELSE utm_medium END WHERE id = ?`,
c.Email, c.Name, nullID(c.SignalID), c.Subject, c.Channel, c.Campaign, source, medium, id)
} else {
_, err = d.Exec(`INSERT INTO stripe_customers (id, email, name, signal_id, subject, channel, utm_campaign, utm_source, utm_medium, first_seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, c.Email, c.Name, nullID(c.SignalID), c.Subject, c.Channel, c.Campaign,
source, medium, now.UTC().Format(time.RFC3339))
}
return c, err
}
func nullID(id int64) any {
if id == 0 {
return nil
}
return id
}
// matchProspect finds the prospect a payer is: a person with that email,
// or else a company at its domain. It returns their funnel subject, signal,
// and the channel Supermarket last wrote to them on.
func matchProspect(d *db.DB, email string) (subject string, signalID int64, channel string) {
if email == "" {
return "", 0, ""
}
var id, sig int64
err := d.QueryRow(`SELECT p.id, coalesce(p.signal_id, c.signal_id, 0) FROM prospect_contacts p
LEFT JOIN prospect_companies c ON c.id = p.company_id WHERE p.email = ? LIMIT 1`, email).Scan(&id, &sig)
if err == nil {
_ = d.QueryRow(`SELECT channel FROM outreach WHERE contact_id = ? AND status = 'sent' ORDER BY sent_at DESC LIMIT 1`, id).Scan(&channel)
return prospects.Subject("contact", id), sig, channel
}
if dom := crm.EmailDomain(email); dom != "" {
if err := d.QueryRow(`SELECT id, coalesce(signal_id, 0) FROM prospect_companies WHERE domain = ? LIMIT 1`, dom).Scan(&id, &sig); err == nil {
return prospects.Subject("company", id), sig, ""
}
}
return "", 0, ""
}
// Customers lists the Stripe customers seen, newest first.
func Customers(d *db.DB, limit int) ([]Customer, error) {
rows, err := d.Query(`SELECT id, email, name, coalesce(signal_id, 0), subject, channel, utm_campaign
FROM stripe_customers ORDER BY first_seen DESC LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Customer
for rows.Next() {
var c Customer
if err := rows.Scan(&c.ID, &c.Email, &c.Name, &c.SignalID, &c.Subject, &c.Channel, &c.Campaign); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
func plural(n int, word string) string {
if n == 1 {
return "1 " + word
}
return fmt.Sprintf("%d %ss", n, word)
}
+234
View File
@@ -0,0 +1,234 @@
// Package tracking brings the end of the funnel in: visits to the
// company's websites from Plausible, counted per buying signal by the
// campaign tag on the link that brought them; and sign-ups and payments
// from Stripe, tied to a signal by the campaign the shopping cart saved
// with the checkout, or else by who paid. Both only read.
package tracking
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"supermarket/internal/api/plausible"
"supermarket/internal/db"
"supermarket/internal/profile"
"supermarket/internal/signals"
)
// Event sources.
const (
SourcePlausible = "plausible"
SourceStripe = "stripe"
)
// Result is what one import did.
type Result struct {
At time.Time `json:"at"`
Added int `json:"added"` // funnel steps recorded
Detail string `json:"detail,omitempty"`
Error string `json:"error,omitempty"`
Through string `json:"through,omitempty"` // Plausible: the last day read
}
func resultKey(source string) string { return "tracking:last:" + source }
// Last is an import's last result, 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
}
func save(d *db.DB, source string, r *Result, err error) (*Result, error) {
if err != nil {
r.Error = err.Error()
}
if perr := d.PutJSON(resultKey(source), r); perr != nil && err == nil {
err = perr
}
return r, err
}
// Channel is the funnel channel for a link's UTM source and medium: the
// direct channels by name, social posts, or the website.
func Channel(source, medium string) string {
source, medium = strings.ToLower(source), strings.ToLower(medium)
switch {
case medium == "outreach" && (source == "email" || source == "linkedin"):
return source
case medium == "email" || source == "email" || source == "newsletter":
return "email"
case medium == "social" || source == "x" || source == "twitter" || source == "linkedin" || source == "reddit" ||
source == "facebook" || source == "mastodon" || source == "bluesky":
return "social"
case source == "blog" || medium == "blog":
return "blog"
}
return "website"
}
// slugs maps each signal's campaign tag to its ID.
func slugs(d *db.DB) (map[string]int64, error) {
list, err := signals.List(d)
if err != nil {
return nil, err
}
out := map[string]int64{}
for _, s := range list {
out[strings.ToLower(s.Slug)] = s.ID
}
return out, nil
}
// Sites are the Plausible site IDs of the company's websites: each one's
// Plausible site if set, else its domain.
func Sites(p *profile.Profile) []string {
var out []string
seen := map[string]bool{}
for _, w := range p.Websites {
site := plausibleSite(w.PlausibleSite)
if site == "" {
if u, err := url.Parse(strings.TrimSpace(w.URL)); err == nil {
site = strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
}
}
if site != "" && !seen[site] {
seen[site] = true
out = append(out, site)
}
}
return out
}
// firstDays is how far back the first Plausible import reads.
const firstDays = 30
const dayFormat = "2006-01-02"
func plausibleStateKey(site string) string { return "tracking:plausible-through:" + site }
// ImportPlausible reads, for each site, the visitors per day that came on a
// link tagged with a signal's campaign, by source, medium and content, for
// the whole days since the last import (today is read tomorrow, when it's
// complete). Visits are counted per signal, never per person.
func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites []string, now time.Time) (*Result, error) {
res := &Result{At: now}
if len(sites) == 0 {
return save(d, SourcePlausible, res, errors.New("no websites in the profile to read"))
}
tags, err := slugs(d)
if err != nil {
return save(d, SourcePlausible, res, err)
}
if len(tags) == 0 {
res.Detail = "No signals yet, so no campaigns to look for."
return save(d, SourcePlausible, res, nil)
}
var campaigns []any
for slug := range tags {
campaigns = append(campaigns, slug)
}
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
visits := 0
for _, site := range sites {
var through string
if _, err := d.GetJSON(plausibleStateKey(site), &through); err != nil {
return save(d, SourcePlausible, res, err)
}
from := now.Local().AddDate(0, 0, -firstDays).Format(dayFormat)
if through != "" {
t, _ := time.ParseInLocation(dayFormat, through, time.Local)
from = t.AddDate(0, 0, 1).Format(dayFormat)
}
if from > yesterday {
continue
}
rows, err := c.Run(ctx, plausible.Query{
SiteID: site,
Metrics: []string{"visitors"},
DateRange: []string{from, yesterday},
Dimensions: []string{"time:day", "visit:utm_campaign", "visit:utm_source", "visit:utm_medium", "visit:utm_content"},
Filters: [][]any{{"is", "visit:utm_campaign", campaigns}},
Pagination: &plausible.Pagination{Limit: 10000},
})
if err != nil {
return save(d, SourcePlausible, res, fmt.Errorf("%s: %w", site, err))
}
for _, r := range rows {
if len(r.Dimensions) < 5 || len(r.Metrics) < 1 || r.Metrics[0] < 1 {
continue
}
day, campaign, source, medium, content := r.Dimensions[0], r.Dimensions[1], r.Dimensions[2], r.Dimensions[3], r.Dimensions[4]
sig, ok := tags[strings.ToLower(campaign)]
if !ok {
continue
}
at, err := time.ParseInLocation(dayFormat, day[:min(len(day), 10)], time.Local)
if err != nil {
continue
}
n := int(r.Metrics[0])
note := strings.Trim(none(source)+" / "+none(medium), " /")
if c := none(content); c != "" {
note += " · " + c
}
added, err := signals.Record(d, signals.Event{
SignalID: sig, Stage: signals.StageVisited, Channel: Channel(none(source), none(medium)),
Source: SourcePlausible, Count: n, Note: site + ": " + note, At: at.Add(12 * time.Hour),
ExternalID: strings.Join([]string{site, day, campaign, source, medium, content}, "|"),
})
if err != nil {
return save(d, SourcePlausible, res, err)
}
if added {
res.Added++
visits += n
}
}
if err := d.PutJSON(plausibleStateKey(site), yesterday); err != nil {
return save(d, SourcePlausible, res, err)
}
}
res.Through = yesterday
res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal.", visits)
return save(d, SourcePlausible, res, nil)
}
// none is "" for Plausible's empty values.
func none(v string) string {
if v == "(none)" || v == "(not set)" {
return ""
}
return v
}
// plausibleSite is a site ID from what the profile holds, which may be the
// dashboard's address instead (https://plausible.example.com/example.com)
// or the Plausible server itself; that last one gives "", so the
// website's domain is used.
func plausibleSite(v string) string {
v = strings.TrimSpace(strings.ToLower(v))
if strings.Contains(v, "://") {
u, err := url.Parse(v)
if err != nil {
return ""
}
path := strings.Trim(u.Path, "/")
if path == "" {
return ""
}
parts := strings.Split(path, "/")
v = parts[len(parts)-1]
}
if strings.HasPrefix(v, "plausible.") {
return ""
}
return v
}
+200
View File
@@ -0,0 +1,200 @@
package tracking
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/plausible"
"supermarket/internal/api/stripe"
"supermarket/internal/db"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/signals"
)
var now = time.Date(2026, 11, 22, 9, 0, 0, 0, time.Local)
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 signal(t *testing.T, d *db.DB, name, slug string) int64 {
s := &signals.Signal{Name: name, Slug: slug}
if err := signals.Save(d, s); err != nil {
t.Fatal(err)
}
return s.ID
}
func TestChannel(t *testing.T) {
for in, want := range map[[2]string]string{
{"email", "outreach"}: "email", {"linkedin", "outreach"}: "linkedin", {"linkedin", "social"}: "social",
{"x", ""}: "social", {"newsletter", ""}: "email", {"", ""}: "website", {"blog", ""}: "blog",
} {
if got := Channel(in[0], in[1]); got != want {
t.Errorf("%v: %q, want %q", in, got, want)
}
}
}
func TestSites(t *testing.T) {
p := &profile.Profile{Websites: []profile.Website{{URL: "https://www.federated.computer/", PlausibleSite: "plausible.federated.computer"},
{URL: "https://shop.example", PlausibleSite: "shop-stats"}, {URL: "https://federated.computer"},
{URL: "https://blog.example", PlausibleSite: "https://plausible.example.com/blog.example"}}}
if got := strings.Join(Sites(p), ","); got != "federated.computer,shop-stats,blog.example" {
t.Errorf("sites: %s", got)
}
}
func TestImportPlausible(t *testing.T) {
d := openDB(t)
m365 := signal(t, d, "Leaving M365", "leaving-m365")
var got []plausible.Query
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer k" || r.URL.Path != "/api/v2/query" {
w.WriteHeader(http.StatusUnauthorized)
return
}
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
got = append(got, q)
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-20", "leaving-m365", "email", "outreach", "outreach-3"}, "metrics": []float64{2}},
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social", "(none)"}, "metrics": []float64{5}},
map[string]any{"dimensions": []string{"2026-11-21", "old-campaign", "x", "social", "(none)"}, "metrics": []float64{9}},
}})
}))
defer srv.Close()
c := plausible.New(srv.URL, "k")
res, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now)
if err != nil {
t.Fatal(err)
}
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") {
t.Fatalf("result: %+v", res)
}
q := got[0]
dr, _ := json.Marshal(q.DateRange)
if q.SiteID != "federated.computer" || string(dr) != `["2026-10-23","2026-11-21"]` || len(q.Filters) != 1 {
t.Errorf("query: %+v %s", q, dr)
}
evs, _ := signals.RecentEvents(d, m365, 10)
if len(evs) != 2 || evs[0].Stage != signals.StageVisited || evs[0].Channel != "social" || evs[0].Count != 5 ||
evs[1].Channel != "email" || !strings.Contains(evs[1].Note, "outreach-3") {
t.Errorf("events: %+v", evs)
}
// The next day reads only the new day; running again the same day reads nothing.
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 1 {
t.Errorf("same day: %d queries, %v", len(got), err)
}
res, _ = ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now.AddDate(0, 0, 1))
dr, _ = json.Marshal(got[1].DateRange)
if string(dr) != `["2026-11-22","2026-11-22"]` || res.Added != 0 {
t.Errorf("next day: %s %+v", dr, res)
}
if last, _ := Last(d, SourcePlausible); last == nil || last.Through != "2026-11-22" {
t.Errorf("last: %+v", last)
}
if _, err := ImportPlausible(context.Background(), d, plausible.New(srv.URL, "bad"), []string{"x.example"}, now); err == nil {
t.Error("a bad key worked")
}
}
func TestSyncStripe(t *testing.T) {
d := openDB(t)
m365 := signal(t, d, "Leaving M365", "leaving-m365")
faith := signal(t, d, "Faith", "faith")
co, _, _ := prospects.AddCompany(d, prospects.Company{Name: "Church", Website: "church.example", Source: prospects.SourceManual, SignalID: faith}, now)
ann, _, _ := prospects.AddContact(d, prospects.Contact{FirstName: "Ann", Email: "ann@acme.example", Source: prospects.SourceManual, SignalID: m365}, now)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer rk_live_x" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Query().Get("status") == "" {
t.Errorf("unfiltered list: %s", r.URL)
}
switch r.URL.Path {
case "/v1/checkout/sessions":
if r.URL.Query().Get("starting_after") == "" {
json.NewEncoder(w).Encode(map[string]any{"has_more": true, "data": []any{
// A trial from a tagged link.
map[string]any{"id": "cs_2", "created": now.Unix() - 100, "status": "complete", "mode": "subscription", "amount_total": 0,
"currency": "usd", "customer": "cus_new", "customer_details": map[string]any{"email": "new@else.example", "name": "New Co"},
"metadata": map[string]any{"utm_campaign": "leaving-m365", "utm_source": "linkedin", "utm_medium": "social"}},
}})
return
}
json.NewEncoder(w).Encode(map[string]any{"has_more": false, "data": []any{
// A one-time payment by a prospect, no tags.
map[string]any{"id": "cs_1", "created": now.Unix() - 200, "status": "complete", "mode": "payment", "payment_status": "paid",
"amount_total": 7000, "currency": "usd", "customer": "cus_ann", "customer_details": map[string]any{"email": "ann@acme.example"}},
}})
case "/v1/invoices":
json.NewEncoder(w).Encode(map[string]any{"has_more": false, "data": []any{
map[string]any{"id": "in_1", "created": now.Unix() - 50, "customer": "cus_new", "amount_paid": 4900, "currency": "usd",
"billing_reason": "subscription_cycle", "status_transitions": map[string]any{"paid_at": now.Unix() - 40}},
map[string]any{"id": "in_2", "created": now.Unix() - 30, "customer": "cus_pastor", "customer_email": "pastor@church.example",
"amount_paid": 12000, "currency": "usd", "billing_reason": "subscription_create"},
map[string]any{"id": "in_3", "created": now.Unix() - 20, "customer": "cus_x", "amount_paid": 0},
}})
}
}))
defer srv.Close()
c := stripe.New("rk_live_x").WithBase(srv.URL)
res, err := SyncStripe(context.Background(), d, c, now)
if err != nil {
t.Fatal(err)
}
if res.Added != 4 || res.Detail != "1 sign-up and 3 payments (239.00)." {
t.Fatalf("result: %+v", res)
}
m, _ := signals.RecentEvents(d, m365, 10)
stages := map[string]signals.Event{}
for _, e := range m {
stages[e.Stage+":"+e.ExternalID] = e
}
if e := stages["signed_up:cs:cs_2"]; e.Channel != "social" || e.Subject != "stripe:cus_new" {
t.Errorf("trial: %+v", e)
}
if e := stages["paid:in:in_1"]; e.ValueCents != 4900 || e.Channel != "social" || e.Note != "Subscription renewal (USD)" {
t.Errorf("renewal: %+v", e)
}
if e := stages["paid:cs:cs_1"]; e.ValueCents != 7000 || e.Subject != prospects.Subject("contact", ann) || e.Channel != "website" {
t.Errorf("one-time: %+v", e)
}
f, _ := signals.RecentEvents(d, faith, 10)
var paid *signals.Event
for i := range f {
if f[i].Stage == signals.StagePaid {
paid = &f[i]
}
}
if len(f) != 2 || paid == nil || paid.ValueCents != 12000 || paid.Subject != prospects.Subject("company", co) {
t.Errorf("by domain: %+v", f)
}
// Running again adds nothing.
if res, _ := SyncStripe(context.Background(), d, c, now); res.Added != 0 {
t.Errorf("again: %+v", res)
}
// The invoice with nothing paid makes no customer.
if cs, _ := Customers(d, 10); len(cs) != 3 {
t.Errorf("customers: %+v", cs)
}
if err := stripe.New("bad").WithBase(srv.URL).Check(context.Background()); err == nil {
t.Error("a bad key worked")
}
}
+22 -1
View File
@@ -13,10 +13,12 @@ import (
"supermarket/internal/api/reddit" "supermarket/internal/api/reddit"
"supermarket/internal/api/sitemap" "supermarket/internal/api/sitemap"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/db"
"supermarket/internal/fetcher" "supermarket/internal/fetcher"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/models" "supermarket/internal/models"
"supermarket/internal/profile" "supermarket/internal/profile"
"supermarket/internal/signals"
) )
// maxPerItem caps "one post per item", which makes one AI call per item. // maxPerItem caps "one post per item", which makes one AI call per item.
@@ -85,6 +87,7 @@ type entryPage struct {
Channels []channelChoice Channels []channelChoice
ProfileSet bool ProfileSet bool
Subreddits []string // suggestions: the entry's, then the profile's Subreddits []string // suggestions: the entry's, then the profile's
Signals []signals.Signal
// After a fetch // After a fetch
Fetched bool Fetched bool
NewItems int NewItems int
@@ -168,7 +171,7 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
base, name = "/content/own", ifElse(p.Name != "", p.Name, "Your company") base, name = "/content/own", ifElse(p.Name != "", p.Name, "Your company")
} }
return &entryPage{Own: content.IsOwn(e), Base: base, Name: name, Products: products, Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed, return &entryPage{Own: content.IsOwn(e), Base: base, Name: name, Products: products, Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet(), Signals: activeSignals(s.DB)}, nil
} }
func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) { func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) {
@@ -312,6 +315,11 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
} }
} }
req := content.Request{Profile: p, Entry: e} req := content.Request{Profile: p, Entry: e}
if id, _ := strconv.ParseInt(r.PostForm.Get("signal"), 10, 64); id != 0 {
if req.Signal, err = signals.Get(s.DB, id); err != nil {
return errors.New("that signal no longer exists")
}
}
for _, ch := range ordered { for _, ch := range ordered {
if ch == content.ChannelReddit { if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit")) req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit"))
@@ -353,3 +361,16 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
} }
return nil return nil
} }
// activeSignals are the signals content can be written for: all but the
// retired ones.
func activeSignals(d *db.DB) []signals.Signal {
list, _ := signals.List(d)
var out []signals.Signal
for _, sg := range list {
if sg.Status != "retired" {
out = append(out, sg)
}
}
return out
}
+1
View File
@@ -88,6 +88,7 @@ func (s *Server) emailSave(w http.ResponseWriter, r *http.Request) {
DailyLimit: num("daily_limit"), GapMinutes: num("gap_minutes"), StartHour: num("start_hour"), EndHour: num("end_hour"), DailyLimit: num("daily_limit"), GapMinutes: num("gap_minutes"), StartHour: num("start_hour"), EndHour: num("end_hour"),
Weekends: f("weekends") == "on", Footer: strings.TrimSpace(strings.ReplaceAll(f("footer"), "\r\n", "\n")), Weekends: f("weekends") == "on", Footer: strings.TrimSpace(strings.ReplaceAll(f("footer"), "\r\n", "\n")),
SchedulingLink: f("scheduling_link"), SaveToSent: f("save_to_sent") == "on", ReadReplies: f("read_replies") == "on", SchedulingLink: f("scheduling_link"), SaveToSent: f("save_to_sent") == "on", ReadReplies: f("read_replies") == "on",
BookingFrom: f("booking_from"),
} }
if err := outreach.Save(s.DB, set); err != nil { if err := outreach.Save(s.DB, set); err != nil {
s.renderEmail(w, r, set, err.Error()) s.renderEmail(w, r, set, err.Error())
+4
View File
@@ -158,6 +158,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/email", s.emailSave) mux.HandleFunc("POST /settings/email", s.emailSave)
mux.HandleFunc("POST /settings/email/test", s.emailTest) mux.HandleFunc("POST /settings/email/test", s.emailTest)
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest) mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
mux.HandleFunc("GET /settings/tracking", s.trackingPage)
mux.HandleFunc("POST /settings/tracking", s.trackingSave)
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
mux.HandleFunc("POST /settings/tracking/run/{source}", s.trackingRun)
mux.HandleFunc("GET /outreach", s.outreachPage) mux.HandleFunc("GET /outreach", s.outreachPage)
mux.HandleFunc("POST /outreach/draft", s.outreachDraft) mux.HandleFunc("POST /outreach/draft", s.outreachDraft)
mux.HandleFunc("POST /outreach/draft-many", s.outreachDraftMany) mux.HandleFunc("POST /outreach/draft-many", s.outreachDraftMany)
+1 -1
View File
@@ -100,7 +100,7 @@ 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", "/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", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published", "/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil) rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK { if rec.Code != http.StatusOK {
+29
View File
@@ -6,6 +6,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -13,6 +14,7 @@ import (
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/explee" "supermarket/internal/api/explee"
"supermarket/internal/api/origami" "supermarket/internal/api/origami"
"supermarket/internal/content"
"supermarket/internal/discovery" "supermarket/internal/discovery"
"supermarket/internal/leadsource" "supermarket/internal/leadsource"
"supermarket/internal/profile" "supermarket/internal/profile"
@@ -87,6 +89,9 @@ type signalData struct {
Events []signals.Event Events []signals.Event
Prospects int // new prospects tagged with it Prospects int // new prospects tagged with it
Posts []content.Draft // written for it
Links []string // the websites, tagged with its campaign
Runs []discovery.Run Runs []discovery.Run
Running bool Running bool
Research string // why Claude can't search, or "" Research string // why Claude can't search, or ""
@@ -172,6 +177,17 @@ func (s *Server) renderSignal(w http.ResponseWriter, r *http.Request, sig *signa
return return
} }
d.Prospects = len(cs) + len(ps) d.Prospects = len(cs) + len(ps)
if d.Posts, err = content.ForSignal(s.DB, sig.ID, 20); err != nil {
s.serverError(w, err)
return
}
if p, _ := profile.Load(s.DB); p != nil {
for _, ws := range p.Websites {
if u := tagLink(ws.URL, sig.Slug); u != "" {
d.Links = append(d.Links, u)
}
}
}
if d.Runs, err = discovery.Runs(s.DB, sig.ID, 8); err != nil { if d.Runs, err = discovery.Runs(s.DB, sig.ID, 8); err != nil {
s.serverError(w, err) s.serverError(w, err)
return return
@@ -638,3 +654,16 @@ func (s *Server) RunDiscovery(ctx context.Context) {
} }
} }
} }
// tagLink is a website's address with a signal's campaign tag, for
// landing pages, the shopping cart and links placed by hand.
func tagLink(site, slug string) string {
u, err := url.Parse(strings.TrimSpace(site))
if err != nil || u.Host == "" {
return ""
}
q := u.Query()
q.Set("utm_campaign", slug)
u.RawQuery = q.Encode()
return u.String()
}
@@ -86,6 +86,12 @@
<span class="help">One subreddit per post. Its rules are read and followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span> <span class="help">One subreddit per post. Its rules are read and followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span>
</label> </label>
</fieldset> </fieldset>
{{if .Signals}}
<label>For a buying signal <span class="muted small">(optional)</span>
<select name="signal"><option value="0">none: plain news for your audience</option>{{range .Signals}}<option value="{{.ID}}">{{.Name}}</option>{{end}}</select>
<span class="help">The posts speak to people in that situation, and their links carry its campaign tag, so visits and sign-ups count for it on the scorecard.</span>
</label>
{{end}}
<fieldset class="choice"> <fieldset class="choice">
<legend>Posts</legend> <legend>Posts</legend>
<label class="check"><input type="radio" name="mode" value="one" checked> One post from all selected items</label> <label class="check"><input type="radio" name="mode" value="one" checked> One post from all selected items</label>
+2
View File
@@ -45,6 +45,8 @@
<label class="check"><input type="checkbox" name="weekends" {{if $s.Weekends}}checked{{end}}> Send on weekends too</label> <label class="check"><input type="checkbox" name="weekends" {{if $s.Weekends}}checked{{end}}> Send on weekends too</label>
<label>Scheduling link <span class="muted small">(optional)</span> <input name="scheduling_link" value="{{$s.SchedulingLink}}" placeholder="https://cal.example.com/you/30min"> <label>Scheduling link <span class="muted small">(optional)</span> <input name="scheduling_link" value="{{$s.SchedulingLink}}" placeholder="https://cal.example.com/you/30min">
<span class="help">Offered as the next step when a call fits. Booking through it counts as Booked once Cal.com is connected.</span></label> <span class="help">Offered as the next step when a call fits. Booking through it counts as Booked once Cal.com is connected.</span></label>
<label>Cal.com's sending address <span class="muted small">(optional)</span> <input name="booking_from" value="{{$s.BookingFrom}}" placeholder="the From address of Cal.com's booking emails">
<span class="help">Cal.com emails you about every booking. With its address here, each new booking email in this mailbox counts as Booked for the person who booked (cancellations and reschedules don't). Open one of those emails and copy its From address. Needs the inbox reading above.</span></label>
<label>Signature <textarea name="footer" rows="5">{{$s.Footer}}</textarea> <label>Signature <textarea name="footer" rows="5">{{$s.Footer}}</textarea>
<span class="help">Added under every email. Keep a way to opt out: a reply of “stop” puts the address on your suppression list.</span></label> <span class="help">Added under every email. Keep a way to opt out: a reply of “stop” puts the address on your suppression list.</span></label>
</section> </section>
+1
View File
@@ -94,6 +94,7 @@
<a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core &amp; Hermes</a> <a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core &amp; Hermes</a>
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a> <a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
<a href="/settings/email" {{if eq .Nav "settings/email"}}aria-current="page"{{end}}>{{template "icon" "email"}}Email</a> <a href="/settings/email" {{if eq .Nav "settings/email"}}aria-current="page"{{end}}>{{template "icon" "email"}}Email</a>
<a href="/settings/tracking" {{if eq .Nav "settings/tracking"}}aria-current="page"{{end}}>{{template "icon" "metrics"}}Website &amp; sales</a>
<div class="nav-label">AI</div> <div class="nav-label">AI</div>
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a> <a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
</nav> </nav>
+1 -1
View File
@@ -12,7 +12,7 @@
{{else if .NotReady}}<p class="warn-text">Sending is off: {{.NotReady}}.</p> {{else if .NotReady}}<p class="warn-text">Sending is off: {{.NotReady}}.</p>
{{else}} {{else}}
<p><strong>{{.SentToday}}</strong> of {{.S.DailyLimit}} emails sent today{{with .Counts.queued}}, <strong>{{.}}</strong> queued{{end}}. {{if .Window}}Paused: {{.Window}}.{{else}}Sending now, one every {{.S.GapMinutes}} minutes or more.{{end}}</p> <p><strong>{{.SentToday}}</strong> of {{.S.DailyLimit}} emails sent today{{with .Counts.queued}}, <strong>{{.}}</strong> queued{{end}}. {{if .Window}}Paused: {{.Window}}.{{else}}Sending now, one every {{.S.GapMinutes}} minutes or more.{{end}}</p>
{{with .LastCheck}}<p class="small muted">Inbox read {{ago .At}}{{if .Error}}: <span class="error-text">{{.Error}}</span>{{else}}: {{.Read}} new {{if eq .Read 1}}message{{else}}messages{{end}}{{if .Replies}}, {{.Replies}} {{if eq .Replies 1}}reply{{else}}replies{{end}}{{end}}{{if .Bounces}}, {{.Bounces}} bounced{{end}}{{if .Stops}}, {{.Stops}} asked to stop{{end}}{{if .AutoReplies}}, {{.AutoReplies}} automatic{{end}}.{{end}}</p>{{end}} {{with .LastCheck}}<p class="small muted">Inbox read {{ago .At}}{{if .Error}}: <span class="error-text">{{.Error}}</span>{{else}}: {{.Read}} new {{if eq .Read 1}}message{{else}}messages{{end}}{{if .Replies}}, {{.Replies}} {{if eq .Replies 1}}reply{{else}}replies{{end}}{{end}}{{if .Bounces}}, {{.Bounces}} bounced{{end}}{{if .Stops}}, {{.Stops}} asked to stop{{end}}{{if .AutoReplies}}, {{.AutoReplies}} automatic{{end}}{{if .Bookings}}, {{.Bookings}} {{if eq .Bookings 1}}booking{{else}}bookings{{end}}{{end}}.{{end}}</p>{{end}}
{{end}} {{end}}
</section> </section>
+2 -1
View File
@@ -79,7 +79,8 @@
<label>Address <input name="website_url" type="url" value="{{.URL}}" placeholder="https://"></label> <label>Address <input name="website_url" type="url" value="{{.URL}}" placeholder="https://"></label>
<label>Hugo repository on Gitea <input name="website_repo" value="{{.Repo}}" placeholder="https://gitea.example.com/org/site.git"></label> <label>Hugo repository on Gitea <input name="website_repo" value="{{.Repo}}" placeholder="https://gitea.example.com/org/site.git"></label>
<label>Branch that gets published <input name="website_branch" value="{{.Branch}}" placeholder="main"></label> <label>Branch that gets published <input name="website_branch" value="{{.Branch}}" placeholder="main"></label>
<label>Plausible site <input name="website_plausible" value="{{.PlausibleSite}}" placeholder="example.com"></label> <label>Plausible site <input name="website_plausible" value="{{.PlausibleSite}}" placeholder="example.com">
<span class="help">The site's name in Plausible, usually its domain. Leave it empty if that's the website's domain.</span></label>
<label>Google Search Console property <input name="website_gsc" value="{{.SearchConsoleProperty}}" placeholder="sc-domain:example.com"></label> <label>Google Search Console property <input name="website_gsc" value="{{.SearchConsoleProperty}}" placeholder="sc-domain:example.com"></label>
<label>Bing Webmaster site <input name="website_bing" value="{{.BingSite}}" placeholder="https://example.com/"></label> <label>Bing Webmaster site <input name="website_bing" value="{{.BingSite}}" placeholder="https://example.com/"></label>
</div> </div>
+11 -1
View File
@@ -60,7 +60,7 @@
</div> </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>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> <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> <span class="help">Finding companies 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> <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> <span class="help">What emails, LinkedIn messages and content for this signal should say.</span></label>
<div class="cols"> <div class="cols">
@@ -87,6 +87,16 @@
<div class="small">{{range $k, $v := .Stats}}{{if $v}}<span class="stat">{{$k}}: <strong>{{$v}}</strong></span> {{end}}{{end}}</div></li>{{end}}</ul> <div class="small">{{range $k, $v := .Stats}}{{if $v}}<span class="stat">{{$k}}: <strong>{{$v}}</strong></span> {{end}}{{end}}</div></li>{{end}}</ul>
{{end}} {{end}}
<h2>Content for it</h2>
{{if .Posts}}
<ul class="items">{{range .Posts}}<li class="item"><span class="badge {{if eq .Status "published"}}published{{else}}draft{{end}}">{{.Status}}</span> {{.Channel}} · {{truncate 140 .Content}}
<span class="muted small">{{if not .PublishedAt.IsZero}}published {{ago .PublishedAt}}{{with .PostURL}} · <a href="{{.}}" target="_blank" rel="noopener noreferrer">view</a>{{end}}{{else}}written {{ago .CreatedAt}}{{end}}</span></li>{{end}}</ul>
{{else}}<p class="help">No posts written for it yet. On <a href="/content">Content</a>, pick items and choose this signal under “For a buying signal”.</p>{{end}}
{{with .Links}}
<p class="small">Links tagged with it, for landing pages, the shopping cart, or a link you share by hand (add <code>utm_source</code> and <code>utm_medium</code> for where you put it). Visits on them count for this signal:</p>
<ul class="small">{{range $i, $u := .}}<li><code id="link-{{$i}}">{{$u}}</code> <button type="button" class="link small" data-copy="link-{{$i}}">Copy</button></li>{{end}}</ul>
{{end}}
{{if .Events}} {{if .Events}}
<h2>Latest steps</h2> <h2>Latest steps</h2>
<table class="list"> <table class="list">
+68
View File
@@ -0,0 +1,68 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Website &amp; sales</h2>
<p class="lede">The end of the funnel: who came to your websites from a link tagged with a buying signal, who booked a call, and who signed up or paid. Supermarket only reads these. Results appear on <a href="/signals">Signals</a>.</p>
<form method="post" action="/settings/tracking" autocomplete="off">
<section class="card" id="plausible">
<h3>Plausible: visits</h3>
<p class="small">Once a day, Supermarket reads yesterday's visitors who arrived on a link tagged with a signal's campaign (<code>utm_campaign</code>), by where the link was (source, medium and content). Visits are counted per signal, never per person.</p>
<label>Plausible's address <input name="plausible_url" value="{{.PlausibleURL}}" placeholder="https://plausible.example.com"></label>
{{template "key-field" (dict "F" .PlausibleKey "Set" .PlausibleSet)}}
<p class="help">Sites read: {{if .Sites}}{{range $i, $s := .Sites}}{{if $i}}, {{end}}<code>{{$s}}</code>{{end}}{{else}}none yet: add your websites (and their Plausible site, if it differs from the domain) to the <a href="/settings/profile">profile</a>{{end}}.</p>
{{if .PlausibleSet}}
<div class="row">
<button type="button" class="secondary small" hx-post="/settings/tracking/test/plausible" hx-target="#test-plausible" hx-indicator="#testing-plausible">Test</button>
<button type="submit" class="secondary small" formaction="/settings/tracking/run/plausible" formnovalidate>Import now</button>
<span id="testing-plausible" class="htmx-indicator">Checking…</span>
</div>
<div id="test-plausible"></div>
{{end}}
{{template "last-run" .LastPlausible}}
</section>
<section class="card" id="stripe">
<h3>Stripe: sign-ups and payments</h3>
<p class="small">Every hour, Supermarket reads new completed checkouts and paid invoices. A checkout with nothing to pay (a trial or a free plan) counts as <strong>Signed up</strong>; money paid counts as <strong>Paid</strong>, with the amount, renewals included. Each customer is tied to a signal by the campaign their checkout carries, or else by their email: a prospect's, or one at a prospect company's domain.</p>
{{template "key-field" (dict "F" .StripeKey "Set" .StripeSet)}}
<details class="small">
<summary>What the shopping cart needs to do</summary>
<p>When a visitor arrives with UTM tags on the link, the cart keeps them (in a cookie or the session) and passes them to Stripe when it creates the Checkout Session, as metadata:</p>
<pre class="sample">metadata[utm_campaign] = the signal's campaign tag
metadata[utm_source] = e.g. email, linkedin, x
metadata[utm_medium] = e.g. outreach, social
metadata[utm_content] = optional: which message or post</pre>
<p>Without them, a payment is still counted, and tied to a signal when the payer's email belongs to a prospect.</p>
</details>
{{if .StripeSet}}
<div class="row">
<button type="button" class="secondary small" hx-post="/settings/tracking/test/stripe" hx-target="#test-stripe" hx-indicator="#testing-stripe">Test</button>
<button type="submit" class="secondary small" formaction="/settings/tracking/run/stripe" formnovalidate>Sync now</button>
<span id="testing-stripe" class="htmx-indicator">Checking…</span>
</div>
<div id="test-stripe"></div>
{{end}}
{{template "last-run" .LastStripe}}
{{if .Customers}}
<table class="list">
<thead><tr><th>Customer</th><th>Came from</th><th>Prospect</th></tr></thead>
<tbody>{{range .Customers}}<tr><td>{{or .Name .Email}}{{if and .Name .Email}} <span class="muted small">{{.Email}}</span>{{end}}</td>
<td class="small">{{if .Campaign}}{{.Campaign}} · {{end}}{{channel .Channel}}</td>
<td class="small">{{if hasPrefix .Subject "stripe:"}}<span class="muted">no</span>{{else}}yes{{end}}</td></tr>{{end}}</tbody>
</table>
{{end}}
</section>
<section class="card" id="bookings">
<h3>Cal.com: bookings</h3>
<p class="small">Your Core's Cal.com has no API, so bookings are read from the emails Cal.com sends you about them, in the mailbox under <a href="/settings/email">Settings → Email</a>. Each new booking counts as <strong>Booked</strong> for the person who booked.</p>
{{if .BookingFrom}}<p class="ok small">Looking for booking emails from <code>{{.BookingFrom}}</code>.</p>
{{else}}<p class="warn-text small">Give Cal.com's sending address under <a href="/settings/email">Settings → Email</a> to start.</p>{{end}}
</section>
<div class="actions"><button type="submit">Save</button></div>
</form>
{{end}}{{template "settings-end"}}{{end}}
{{define "last-run"}}{{with .}}
<p class="small {{if .Error}}error-text{{else}}muted{{end}}">Last read {{ago .At}}: {{if .Error}}{{.Error}}{{else}}{{.Detail}}{{if .Through}} Through {{.Through}}.{{end}}{{end}}</p>
{{end}}{{end}}
+237
View File
@@ -0,0 +1,237 @@
package web
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/api/plausible"
"supermarket/internal/api/stripe"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/tracking"
)
var (
plausibleKey = secretField{"plausible", secrets.PlausibleAPIKey, "Stats API key",
"In Plausible, your account settings → API Keys → New API key, of the Stats API kind.", ""}
stripeKey = secretField{"stripe", secrets.StripeAPIKey, "Restricted key",
"In Stripe, Developers → API keys → Create restricted key, with Read access to Checkout Sessions and Invoices and nothing else. It starts rk_live_.", "https://dashboard.stripe.com/apikeys"}
)
const plausibleURLKey = "tracking:plausible-url"
// Test hooks: other servers for the APIs.
var (
stripeBase = ""
)
// plausibleURL is Plausible's address: the saved one, or the Core's.
func (s *Server) plausibleURL() string {
var u string
if _, err := s.DB.GetJSON(plausibleURLKey, &u); err == nil && u != "" {
return u
}
if s.Core != nil && s.Core.Domain != "" {
return "https://plausible." + s.Core.Domain
}
return "https://plausible.io"
}
func (s *Server) plausible() *plausible.Client {
key := s.Secrets.Get(secrets.PlausibleAPIKey)
if key == "" {
return nil
}
return plausible.New(s.plausibleURL(), key)
}
func (s *Server) stripe() *stripe.Client {
key := s.Secrets.Get(secrets.StripeAPIKey)
if key == "" {
return nil
}
c := stripe.New(key)
if stripeBase != "" {
c.WithBase(stripeBase)
}
return c
}
func (s *Server) sites() []string {
p, _ := profile.Load(s.DB)
if p == nil {
return nil
}
return tracking.Sites(p)
}
func (s *Server) trackingPage(w http.ResponseWriter, r *http.Request) {
s.renderTracking(w, r, "")
}
func (s *Server) renderTracking(w http.ResponseWriter, r *http.Request, errMsg string) {
lastP, _ := tracking.Last(s.DB, tracking.SourcePlausible)
lastS, _ := tracking.Last(s.DB, tracking.SourceStripe)
customers, _ := tracking.Customers(s.DB, 20)
set, _ := s.outreachSettings()
s.render(w, r, "tracking", page{Title: "Website & sales", Nav: "settings/tracking", Error: errMsg, Data: map[string]any{
"PlausibleURL": s.plausibleURL(),
"PlausibleKey": plausibleKey,
"PlausibleSet": s.Secrets.Has(secrets.PlausibleAPIKey),
"Sites": s.sites(),
"LastPlausible": lastP,
"StripeKey": stripeKey,
"StripeSet": s.Secrets.Has(secrets.StripeAPIKey),
"LastStripe": lastS,
"Customers": customers,
"BookingFrom": set.BookingFrom,
}})
}
func (s *Server) trackingSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
u := strings.TrimRight(strings.TrimSpace(r.PostFormValue("plausible_url")), "/")
if u != "" && !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
s.renderTracking(w, r, "Plausible's address must start with https://")
return
}
if err := s.DB.PutJSON(plausibleURLKey, u); err != nil {
s.serverError(w, err)
return
}
if err := s.saveSecrets(r, []secretField{plausibleKey, stripeKey}); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/tracking", "saved")
}
// trackingTest checks a key: Plausible's against each site, Stripe's
// against checkouts and invoices.
func (s *Server) trackingTest(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
data := map[string]any{}
switch r.PathValue("source") {
case tracking.SourcePlausible:
c := s.plausible()
if c == nil {
data["Error"] = "Save the key first."
break
}
sites := s.sites()
if len(sites) == 0 {
data["Error"] = "Add your websites to the profile first."
break
}
var ok, bad []string
for _, site := range sites {
n, err := c.Visitors(ctx, site)
if err != nil {
bad = append(bad, site+": "+err.Error())
} else {
ok = append(ok, site+": "+strconv.Itoa(n)+" visitors in the last 30 days")
}
}
if len(ok) > 0 {
data["OK"] = "The key works. " + strings.Join(ok, "; ") + "."
}
if len(bad) > 0 {
data["Error"] = strings.Join(bad, "; ")
}
case tracking.SourceStripe:
c := s.stripe()
if c == nil {
data["Error"] = "Save the key first."
break
}
if err := c.Check(ctx); err != nil {
data["Error"] = err.Error()
break
}
if c.Live() {
data["OK"] = "The key works: it can read checkouts and invoices (live data)."
} else {
data["OK"] = "The key works, but it's a test-mode key: it reads test data, not real customers."
}
default:
http.NotFound(w, r)
return
}
s.fragment(w, "sources", "test-result", data)
}
// trackingRun imports from one source now.
func (s *Server) trackingRun(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
if err := s.runTracking(ctx, r.PathValue("source")); err != nil {
s.renderTracking(w, r, err.Error())
return
}
redirect(w, r, "/settings/tracking", "imported")
}
func (s *Server) runTracking(ctx context.Context, source string) error {
now := time.Now()
switch source {
case tracking.SourcePlausible:
c := s.plausible()
if c == nil {
return errors.New("save the Plausible key first")
}
_, err := tracking.ImportPlausible(ctx, s.DB, c, s.sites(), now)
return err
case tracking.SourceStripe:
c := s.stripe()
if c == nil {
return errors.New("save the Stripe key first")
}
_, err := tracking.SyncStripe(ctx, s.DB, c, now)
return err
}
return errors.New("unknown source")
}
// RunTracking reads Plausible once a day (yesterday's visits) and Stripe
// every hour.
func (s *Server) RunTracking(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
tried := map[string]time.Time{}
for {
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
for _, src := range []string{tracking.SourcePlausible, tracking.SourceStripe} {
if (src == tracking.SourcePlausible && s.plausible() == nil) || (src == tracking.SourceStripe && s.stripe() == nil) {
continue
}
last, _ := tracking.Last(s.DB, src)
due := last == nil || time.Since(last.At) >= time.Hour
if src == tracking.SourcePlausible && last != nil && last.Error == "" && last.Through >= yesterday {
due = false
}
// After a failure, wait an hour before trying again.
if !due || time.Since(tried[src]) < time.Hour {
continue
}
tried[src] = time.Now()
rctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
if err := s.runTracking(rctx, src); err != nil {
s.Log.Warn("tracking: import failed", "source", src, "err", err)
}
cancel()
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
+80
View File
@@ -0,0 +1,80 @@
package web
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"supermarket/internal/core"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/signals"
)
func TestWebsiteAndSales(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v2/query":
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-20", "leaving-m365", "linkedin", "social", "(none)"}, "metrics": []float64{3}},
}})
case "/v1/checkout/sessions":
json.NewEncoder(w).Encode(map[string]any{"data": []any{
map[string]any{"id": "cs_1", "created": 1, "status": "complete", "mode": "subscription", "amount_total": 0,
"customer": "cus_1", "customer_details": map[string]any{"email": "a@b.example", "name": "Bea"},
"metadata": map[string]any{"utm_campaign": "leaving-m365"}},
}})
case "/v1/invoices":
json.NewEncoder(w).Encode(map[string]any{"data": []any{}})
}
}))
defer srv.Close()
stripeBase = srv.URL
defer func() { stripeBase = "" }()
s, h := newTestServer(t, &core.Core{Domain: "example.com", Email: "me@example.com"})
if err := profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}}); err != nil {
t.Fatal(err)
}
sig := &signals.Signal{Name: "Leaving M365", Slug: "leaving-m365"}
signals.Save(s.DB, sig)
body := do(h, http.MethodGet, "/settings/tracking", nil, nil).Body.String()
for _, want := range []string{`value="https://plausible.example.com"`, "<code>us.example</code>", "metadata[utm_campaign]", "Give Cal.com"} {
if !strings.Contains(body, want) {
t.Errorf("settings lack %q", want)
}
}
if rec := postForm(h, "/settings/tracking", url.Values{"plausible_url": {srv.URL}, secrets.PlausibleAPIKey: {"k"}, secrets.StripeAPIKey: {"rk_test_x"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body)
}
if body := postForm(h, "/settings/tracking/test/plausible", nil).Body.String(); !strings.Contains(body, "us.example: 3 visitors") {
t.Errorf("plausible test: %s", body)
}
if body := postForm(h, "/settings/tracking/test/stripe", nil).Body.String(); !strings.Contains(body, "test-mode key") {
t.Errorf("stripe test: %s", body)
}
for _, src := range []string{"plausible", "stripe"} {
if rec := postForm(h, "/settings/tracking/run/"+src, nil); rec.Code != http.StatusSeeOther {
t.Errorf("run %s: %d %s", src, rec.Code, rec.Body)
}
}
body = do(h, http.MethodGet, "/settings/tracking", nil, nil).Body.String()
for _, want := range []string{"3 visitors on links tagged with a signal", "1 sign-up and 0 payments", "Bea"} {
if !strings.Contains(body, want) {
t.Errorf("after the imports, settings lack %q", want)
}
}
body = do(h, http.MethodGet, "/signals/1", nil, nil).Body.String()
for _, want := range []string{"https://us.example?utm_campaign=leaving-m365", "Content for it", "Signed up", "Visited"} {
if !strings.Contains(body, want) {
t.Errorf("signal page lacks %q", want)
}
}
if body := do(h, http.MethodGet, "/content/own", nil, nil).Body.String(); !strings.Contains(body, "For a buying signal") && strings.Contains(body, "Write drafts") {
t.Error("the draft form doesn't offer the signals")
}
}