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:
+22
-1
@@ -13,10 +13,12 @@ import (
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/sitemap"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/fetcher"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/models"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// maxPerItem caps "one post per item", which makes one AI call per item.
|
||||
@@ -85,6 +87,7 @@ type entryPage struct {
|
||||
Channels []channelChoice
|
||||
ProfileSet bool
|
||||
Subreddits []string // suggestions: the entry's, then the profile's
|
||||
Signals []signals.Signal
|
||||
// After a fetch
|
||||
Fetched bool
|
||||
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")
|
||||
}
|
||||
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) {
|
||||
@@ -312,6 +315,11 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
|
||||
}
|
||||
}
|
||||
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 {
|
||||
if ch == content.ChannelReddit {
|
||||
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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -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"),
|
||||
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",
|
||||
BookingFrom: f("booking_from"),
|
||||
}
|
||||
if err := outreach.Save(s.DB, set); err != nil {
|
||||
s.renderEmail(w, r, set, err.Error())
|
||||
|
||||
@@ -158,6 +158,10 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("POST /settings/email", s.emailSave)
|
||||
mux.HandleFunc("POST /settings/email/test", s.emailTest)
|
||||
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("POST /outreach/draft", s.outreachDraft)
|
||||
mux.HandleFunc("POST /outreach/draft-many", s.outreachDraftMany)
|
||||
|
||||
@@ -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",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/content/scheduled", "/content/published",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/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"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"supermarket/internal/ai"
|
||||
"supermarket/internal/api/explee"
|
||||
"supermarket/internal/api/origami"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/discovery"
|
||||
"supermarket/internal/leadsource"
|
||||
"supermarket/internal/profile"
|
||||
@@ -87,6 +89,9 @@ type signalData struct {
|
||||
Events []signals.Event
|
||||
Prospects int // new prospects tagged with it
|
||||
|
||||
Posts []content.Draft // written for it
|
||||
Links []string // the websites, tagged with its campaign
|
||||
|
||||
Runs []discovery.Run
|
||||
Running bool
|
||||
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
|
||||
}
|
||||
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 {
|
||||
s.serverError(w, err)
|
||||
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>
|
||||
</label>
|
||||
</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">
|
||||
<legend>Posts</legend>
|
||||
<label class="check"><input type="radio" name="mode" value="one" checked> One post from all selected items</label>
|
||||
|
||||
@@ -45,6 +45,8 @@
|
||||
<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">
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -94,6 +94,7 @@
|
||||
<a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core & Hermes</a>
|
||||
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
|
||||
<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 & sales</a>
|
||||
<div class="nav-label">AI</div>
|
||||
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
||||
</nav>
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
{{else if .NotReady}}<p class="warn-text">Sending is off: {{.NotReady}}.</p>
|
||||
{{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>
|
||||
{{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}}
|
||||
</section>
|
||||
|
||||
|
||||
@@ -79,7 +79,8 @@
|
||||
<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>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>Bing Webmaster site <input name="website_bing" value="{{.BingSite}}" placeholder="https://example.com/"></label>
|
||||
</div>
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
</div>
|
||||
<label>Hypothesis <textarea name="hypothesis" rows="2" placeholder="Teams complaining about the Microsoft 365 price rise switch within a quarter.">{{$s.Hypothesis}}</textarea></label>
|
||||
<label>How to spot it <textarea name="spot" rows="4" placeholder="One per line: search queries, keywords, origami.chat or explee.com criteria">{{$s.Spot}}</textarea>
|
||||
<span class="help">Discovery (next) runs these as searches, so write them the way you'd search for the companies.</span></label>
|
||||
<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>
|
||||
<span class="help">What emails, LinkedIn messages and content for this signal should say.</span></label>
|
||||
<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>
|
||||
{{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}}
|
||||
<h2>Latest steps</h2>
|
||||
<table class="list">
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
|
||||
<h2>Website & 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}}
|
||||
@@ -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:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user