Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00e6deee00 | ||
|
|
152c14b580 | ||
|
|
23f765159f | ||
|
|
a9a1cb97ac | ||
|
|
6ba524295b | ||
|
|
5e799c7541 | ||
|
|
2c242d8c94 | ||
|
|
07c4491f48 |
@@ -407,7 +407,9 @@ Part 4, promoting our own products:
|
||||
invites feedback, and Posts warns that self-promotion is often
|
||||
restricted.
|
||||
|
||||
**Not yet tried for real (deferred on 2026-11-21 for the UI redesign below; run this checklist next).** Parts 1–4 are covered by tests with fake AI
|
||||
**Tried for real on 2026-11-21:** publishing to X and LinkedIn worked (LinkedIn needed the "Sign In with LinkedIn using OpenID Connect" product; X's callback must use 127.0.0.1). Reddit refuses new API apps without approval, so Reddit drafts are posted by hand. The full hand-testing checklist is now TEST.md; the steps below were the first one.
|
||||
|
||||
**Originally deferred on 2026-11-21 for the UI redesign below.** Parts 1–4 are covered by tests with fake AI
|
||||
and channel clients, and the rebuilt app runs (schema 3). But the
|
||||
installed app has no profile, AI key, inventory or social sign-ins yet, so no
|
||||
real fetch, generation or post has been made. Before relying on it:
|
||||
@@ -473,7 +475,11 @@ The plan for Phase 1, as first written:
|
||||
### Phase 2: Buying signals, prospects and the funnel
|
||||
|
||||
**Started 2026-11-21** on branch `phase2-prospects`, after Phase 0 and 1
|
||||
were merged into `main` and tagged `v0.1.0`.
|
||||
were merged into `main` and tagged `v0.1.0`. **Parts 1 to 7 built, and
|
||||
merged into `main` on 2026-11-22** (d23d5e2). Part 8 (Hugo pages per
|
||||
signal) waits for Phase 5. Not yet tried against the live services:
|
||||
discovery's web search, outreach's mailbox, Stripe and Plausible (no keys
|
||||
saved yet), and the CRM bridge, which waits on the Core's MCP hub.
|
||||
|
||||
**Reframed 2026-11-21 (the user's direction).** Phase 2 is built around
|
||||
**buying signals**: hypotheses about why a company buys now, which are
|
||||
@@ -660,7 +666,8 @@ tagged with the signal from its UTM campaign.
|
||||
### Phase 3: SEO, for all of the company's websites
|
||||
|
||||
**Started 2026-11-22** on branch `phase3-seo`, after Phase 2 was merged
|
||||
into `main`.
|
||||
into `main`. **All seven parts built, and merged into `main` on
|
||||
2026-11-22** (2302fb0).
|
||||
|
||||
**Decisions (the user, 2026-11-22).**
|
||||
- **chatseo.app:** borrow its ideas only, no subscription. It was reviewed
|
||||
@@ -993,6 +1000,197 @@ signals; this phase builds the full metrics on top of it.
|
||||
5. A dashboard with CSV export. It can also be published as a page on one of
|
||||
the company's sites.
|
||||
|
||||
**Started 2026-11-22** on branch `phase4-metrics`, after Phase 3 was merged
|
||||
into `main`. **Parts 1 to 6 built, and merged into `main` on 2026-11-22**
|
||||
(152c14b). Part 7 (pipeline influence) waits for the CRM bridge.
|
||||
|
||||
**Design decisions:**
|
||||
- **MRR comes from invoice line items, not subscriptions.** A subscription
|
||||
object only says how things stand today. An invoice line says what a
|
||||
customer was billed for which period: monthly value = the line's amount,
|
||||
after discounts, ÷ the months its period covers. Past months can then be
|
||||
rebuilt exactly, and trials ($0), pauses (no invoice) and cancellations
|
||||
(no next period) fall out naturally.
|
||||
- **Every number is computed in code** from the synced data, like Phase 3.
|
||||
No estimates; where data is missing, the dashboard says so.
|
||||
- **One currency.** Amounts in another currency are counted apart, never
|
||||
added.
|
||||
- **Gross margin is per product** (the user, 2026-11-22). The default is
|
||||
**60%**, and each Stripe product can have its own margin, set on
|
||||
Metrics. CLV weighs each customer's revenue by the margin of what they
|
||||
buy. Products come from the sync; if the key can't read Products, their
|
||||
names come from the invoice lines' descriptions.
|
||||
|
||||
**Parts, in order, a commit after each:**
|
||||
1. **The full Stripe sync.**
|
||||
- Read customers, invoices (with their lines), credit notes and refunds:
|
||||
a full backfill, then the Events API every hour.
|
||||
- Events are kept for 30 days, so an older watermark triggers a new
|
||||
backfill.
|
||||
- Use the same restricted, read-only key as Phase 2. The key also needs
|
||||
read access to Customers, Credit notes, Events and Charges (for
|
||||
refunds).
|
||||
- **Built 2026-11-22** (schema 18: `stripe_objects`,
|
||||
`stripe_invoice_lines`):
|
||||
- `metrics.Sync` backfills customers, invoices (drafts skipped),
|
||||
credit notes and refunds (with `expand[]=data.charge` for the
|
||||
customer).
|
||||
- It then applies the Events API for the followed types since the
|
||||
watermark. `charge.refunded` reads its refunds, and
|
||||
`customer.deleted` marks the customer deleted.
|
||||
- Invoice lines are re-read in full when `has_more`.
|
||||
`stripe.ParseLine` reads both the older line shape and the 2025
|
||||
one, and stores the amount after discounts.
|
||||
- It syncs every hour, on Metrics, with *Sync now* and *Read
|
||||
everything again*.
|
||||
- Per-product margins came in with it (schema 19 adds the lines'
|
||||
descriptions). Products are read on every sync; without Products
|
||||
access, the sync says so and names come from the line
|
||||
descriptions. `metrics.Products` lists each product's last 12
|
||||
months billed (paid and open invoices). Margins are a default plus
|
||||
per-product overrides, under Metrics → Gross margin by product.
|
||||
`WeightedMargin` gives the revenue-weighted margin.
|
||||
- On the live account, the first full sync read 857 customers,
|
||||
2,894 invoices, 21 credit notes, 346 refunds and 63 products, all
|
||||
in USD.
|
||||
2. **The MRR model and NRR.**
|
||||
- MRR per customer per month, from invoice lines.
|
||||
- Each month's movements: new, expansion, contraction, churn,
|
||||
reactivation.
|
||||
- NRR monthly and over the trailing 12 months, by signup cohort.
|
||||
- **Built 2026-11-22** (no schema change):
|
||||
- `metrics.Build` measures each customer's MRR at each month's last
|
||||
second (the current month: now). It sums the recurring lines of
|
||||
paid and open invoices in the main currency whose period covers
|
||||
that moment.
|
||||
- A normal line is divided by its interval (a year counts as 12
|
||||
months, a week as 52/12). A proration is spread over its actual
|
||||
part-period, so an upgrade counts from its day. Under a cent counts
|
||||
as nothing (trials).
|
||||
- Moves: new, expansion, contraction, churn, reactivation. Changes
|
||||
under $1 or 1% are noise from the proration arithmetic.
|
||||
- NRR for a month is what last month's customers pay now ÷ what they
|
||||
paid then. NRR over 12 months is what the customers of 12 months
|
||||
ago pay now ÷ what they paid then.
|
||||
- Cohorts are by the first paid month, with the retained share of
|
||||
starting MRR for up to 12 months.
|
||||
- **Start month.** When 20+ customers and most of the MRR appear as
|
||||
new in one month, the app suggests counting from it. That's what
|
||||
happened in January 2025 on the live account: billing came back to
|
||||
Stripe after a gap through most of 2024. Customers paying in the
|
||||
start month are the base, not new. You can choose "count
|
||||
everything" instead.
|
||||
- The pages are Metrics (MRR now, ARR, ARPA, NRR, a 24-month SVG
|
||||
chart, the month-by-month table, cohorts) and Metrics → a month
|
||||
(each customer's move).
|
||||
- On the live data, both large swings are real: in June 2026 a
|
||||
customer paying about $2,075 a month left, and in July 2026 prices
|
||||
rose across the plans.
|
||||
3. **Matching Stripe customers to EspoCRM Accounts** (from the cached CRM
|
||||
records), by stored ID, email or email domain, with a screen to fix
|
||||
wrong matches. Customers already tied to prospects (Phase 2) keep that
|
||||
tie.
|
||||
- **Built 2026-11-22** (schema 20: `crm_matches`, the user's choices
|
||||
only):
|
||||
- `metrics.Matches` matches every customer with a paid or open
|
||||
invoice, in this order:
|
||||
1. the user's choice;
|
||||
2. an Account Hermes created from here (a done `stripe-customer:`
|
||||
CRM action);
|
||||
3. a stored ID: `espocrm_id`, `espo_id`, `crm_id` or
|
||||
`espocrm_account_id` in the customer's metadata, or a
|
||||
`cus_…` in the Account's `stripeCustomerId`, `cStripeCustomerId`
|
||||
or a similar field;
|
||||
4. email, on the Account or one of its Contacts (via
|
||||
`accountId`);
|
||||
5. the email's domain, skipping free mail.
|
||||
- When several Accounts fit, the user chooses.
|
||||
- The page is Metrics → Customers and the CRM, with three tabs: to
|
||||
fix, paying now, all. Each customer can be matched to an Account
|
||||
(by name), marked "not in the CRM", put back to automatic, or
|
||||
queued as a new Account for Hermes (the website comes from the
|
||||
email's domain).
|
||||
- On the live account, 385 customers have billing. None can be
|
||||
matched until Hermes copies the CRM's Accounts, which waits on the
|
||||
Core's MCP hub.
|
||||
4. **The spend log and CAC.**
|
||||
- Spend by channel and month, entered by hand or imported from CSV.
|
||||
- Outside tools' spend comes in automatically (origami.chat and
|
||||
explee.com campaigns already report it).
|
||||
- CAC = spend ÷ new paying customers, per month and per channel, with
|
||||
the channel taken from the customer's first funnel touch.
|
||||
- **Built 2026-11-22** (schema 21: `spend`, `spend_seen`):
|
||||
- Spend is logged by month and channel: the funnel's channels plus
|
||||
"general" for overheads. It comes in by hand, or from a pasted CSV
|
||||
of month,channel,amount,note (all or nothing).
|
||||
- `SyncOutsideSpend` runs with the hourly metrics. It adds each
|
||||
origami.chat or explee.com campaign's spend since last seen to the
|
||||
current month. The first time, a campaign's whole lifetime spend
|
||||
goes into that month, with a note saying so. On the live account,
|
||||
that was explee.com's $344.51, in November 2026.
|
||||
- `BuildCAC`: each month's spend ÷ its new customers (from the MRR
|
||||
model), plus a trailing three-month figure. With no spend logged,
|
||||
CAC is unknown, never $0.
|
||||
- By channel, over 12 months: each new customer's channel is their
|
||||
first funnel event, matched by email; Stripe's own steps don't
|
||||
count, and customers with none are "unknown". Phase 2's
|
||||
`stripe_customers.channel` defaults to "website", so it isn't
|
||||
used. General spend counts toward monthly CAC, not toward any
|
||||
channel.
|
||||
- The page is Metrics → Spend and CAC.
|
||||
5. **CLV and cohorts.**
|
||||
- CLV = ARPA × gross margin ÷ monthly churn rate, with the margin
|
||||
weighted by each product's share of the revenue.
|
||||
- Each signup cohort's actual cumulative revenue, net of refunds and
|
||||
credit notes.
|
||||
- **Built 2026-11-22** (no schema change):
|
||||
- **`BuildCLV`** measures on the last complete month:
|
||||
- ARPA;
|
||||
- the margin, weighted by each product's 12-month billings;
|
||||
- customer churn, as customers lost ÷ customers at the start,
|
||||
summed over up to the last 12 complete months;
|
||||
- lifetime = 1 ÷ churn;
|
||||
- CLV = ARPA × margin × lifetime;
|
||||
- CAC = spend ÷ new customers over its own 12-month window (churn
|
||||
needs the month before, so its window starts a month later);
|
||||
- CLV:CAC.
|
||||
- **`RevenueByCohort`** uses money that actually came in: paid
|
||||
invoices' `amount_paid` at `paid_at`, minus refunds that
|
||||
succeeded, minus post-payment credit notes less any part refunded
|
||||
(pre-payment notes already lowered the amount paid). It's counted
|
||||
by the month it happened, cumulative per customer, for each first
|
||||
paid month, with a gross profit view.
|
||||
- Cells mark months not reached yet separately from the amount,
|
||||
because revenue can be negative when refunds exceed payments.
|
||||
- The page is Metrics → CLV and cohorts. On the live account, CLV
|
||||
is about $1,161 of gross profit per customer: $94 a month, 60%
|
||||
margin, 4.9% monthly churn, a 20.6-month lifetime. CAC waits for
|
||||
spend to be logged.
|
||||
6. **The dashboard.**
|
||||
- MRR over time with its movements, NRR, CAC, CLV and CLV:CAC.
|
||||
- CSV export of every table.
|
||||
- Optionally published as a page on one of the sites, through a pull
|
||||
request.
|
||||
- **Built 2026-11-22** (no schema change):
|
||||
- The MRR and NRR page has a second strip: churn, CLV, CAC and
|
||||
CLV:CAC.
|
||||
- `metrics.Export` writes eight tables as CSV, amounts in dollars:
|
||||
MRR month by month (every month), NRR by cohort and revenue by
|
||||
cohort (24 months), CAC by month and by channel, the spend log,
|
||||
products and margins, and customers with their MRR and CRM match.
|
||||
Each is downloaded at `/metrics/export/<name>.csv`, linked under
|
||||
its table.
|
||||
- **Metrics → Publish** builds an open metrics page in Markdown,
|
||||
with totals only: MRR and ARR, customers and ARPA, 12-month
|
||||
growth, NRR, churn, and a 12-month table, chosen part by part.
|
||||
- `seo.Applier.PublishPage` opens a pull request that adds or
|
||||
updates the page (`hugorepo.UpsertPage`), checked with a Hugo
|
||||
build. The options and the last pull request are kept. A test
|
||||
checks that no customer's name, email or ID can appear on the
|
||||
page.
|
||||
7. **Pipeline influence**, once the CRM bridge works: the value of open and
|
||||
won EspoCRM opportunities with at least one marketing touch, by channel.
|
||||
|
||||
### Phase 5: Sites and components
|
||||
1. **Component library**: a Hugo theme module with section partials (hero,
|
||||
features, cards, steps, pricing, stats, FAQ, comparison table, testimonial,
|
||||
@@ -1134,3 +1332,7 @@ Phases 1, 3, 5 and the Stripe half of 4 depend only on Phase 0.
|
||||
3. **Gitea**: which Gitea do sites live on (the Core's, at
|
||||
`gitea.<CORE_DOMAIN>`?), and should the app get its token from the user or
|
||||
from Gitea's OAuth?
|
||||
*2026-11-22:* resolved. Sites live on the Core's Gitea
|
||||
(gitea.federated.computer, with Federated_Computer/federated-website for
|
||||
the main site). The user gives the app an access token with the
|
||||
`write:repository` scope, under Settings → Search engines.
|
||||
|
||||
@@ -143,6 +143,27 @@ Edit the brief and answer those questions ("not tested" is a fine answer), then
|
||||
- **Google:** the sitemaps Search Console has, with their errors.
|
||||
- **Bing:** with a Bing Webmaster API key (Settings → Search engines), Bing's weekly clicks and impressions, its top searches, and its crawl issues.
|
||||
|
||||
**Metrics (Metrics).** With the Stripe key from Settings → Website & sales (give it read access to Customers, Invoices, Credit notes, Charges and Refunds, and Events too), Supermarket reads your whole Stripe history once, then the changes every hour. Under *Gross margin by product*, each product shows what it billed over the last 12 months; give each its margin (what you keep after the cost of delivering it), or leave it at the default, 60%. CLV uses them. Metrics shows:
|
||||
- MRR today, ARR, the number of paying customers, the average per customer, and NRR for the month and over 12 months;
|
||||
- a 24-month chart;
|
||||
- each month's movements (new, expansion, contraction, churn, reactivation), with a page per month listing each customer's move;
|
||||
- cohorts by the month customers first paid, with the share of their starting MRR they still pay.
|
||||
|
||||
MRR is built from the invoice lines (each recurring line's amount after discounts, spread over its billing period), so past months are exact. *Spend and CAC* (under Metrics): log what marketing and sales cost each month, by channel, by hand or by pasting a CSV (`month,channel,amount,note`). origami.chat and explee.com campaign spend comes in on its own. CAC is the month's spend over the customers who first paid that month, with a steadier three-month figure. Over the last 12 months it's also shown per channel, using each new customer's first step in the funnel (a reply, a visit, an outreach email), matched by email.
|
||||
|
||||
*CLV and cohorts* (under Metrics): customer lifetime value, as gross profit per customer. That's the average MRR per customer × the gross margin (weighted by product) ÷ the monthly churn rate averaged over 12 months. It's shown beside CAC as CLV:CAC (3:1 or better is healthy). Below it, each signup cohort's actual cumulative revenue per customer, month by month: what came in, less refunds and credits, with a gross profit view.
|
||||
|
||||
Every Metrics table has a *Download as CSV* link. *Publish* (under Metrics) builds an "open metrics" page for your website from the numbers you choose: MRR and ARR, customers, growth, NRR, churn, a monthly table. It shows totals only, never anything about any one customer. *Open a pull request* adds or updates the page on the site's Gitea repository; merging publishes it.
|
||||
|
||||
*Customers and the CRM* (under Metrics) matches each Stripe customer to its EspoCRM Account, in this order:
|
||||
- a stored ID, either side;
|
||||
- the email, on the Account or one of its Contacts;
|
||||
- the email's domain (free mail doesn't count).
|
||||
|
||||
Where several Accounts fit, you choose; you can fix any match, mark a customer as not in the CRM, or queue a paying customer to be added as an Account through Hermes. It needs Hermes to have copied the CRM's Accounts.
|
||||
|
||||
If your billing moved to Stripe partway through, set the month to count from, so the customers already paying then aren't counted as new; Metrics suggests one when it sees the jump. CAC and CLV come in the next parts.
|
||||
|
||||
**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.
|
||||
|
||||
@@ -399,19 +399,101 @@ Throughout, also notice:
|
||||
- [ ] With a Bing Webmaster API key saved, Bing's weekly numbers, searches
|
||||
and crawl issues appear.
|
||||
|
||||
## 8. Search
|
||||
## 8. Metrics
|
||||
|
||||
### Stripe sync
|
||||
|
||||
- [ ] With the Stripe key's read access widened (Customers, Invoices, Credit
|
||||
notes, Charges and Refunds, Events), Metrics → *Sync now* reads your
|
||||
whole history the first time and says so.
|
||||
- [ ] The counts of customers, invoices, credit notes and refunds match
|
||||
Stripe's dashboard (draft invoices aren't counted).
|
||||
- [ ] A later *Sync now* applies only the changes since the last one; a
|
||||
payment or refund made in Stripe shows up within the hour.
|
||||
- [ ] The currencies listed are the ones you bill in.
|
||||
- [ ] *Gross margin by product* lists your Stripe products by name, with
|
||||
what each billed over the last 12 months (compare one with Stripe's
|
||||
reports). Setting a margin and saving keeps it; an empty box shows
|
||||
the default.
|
||||
|
||||
### MRR, movements and NRR
|
||||
|
||||
- [ ] Metrics shows MRR today, close to Stripe's own MRR figure (Billing →
|
||||
Overview). Small differences come from how each counts prorations and
|
||||
open invoices.
|
||||
- [ ] The month-by-month table's net change adds up: new + expansion +
|
||||
reactivation − contraction − churn.
|
||||
- [ ] Open a month: each customer's move is listed with the MRR before
|
||||
and after; check two of them against the customer in Stripe.
|
||||
- [ ] If billing moved to Stripe partway through, the suggestion to count
|
||||
from that month appears; *Count from …* makes those customers the
|
||||
starting base, and the suggestion goes away.
|
||||
- [ ] Cohorts start at 100% in their first month.
|
||||
|
||||
### Spend and CAC
|
||||
|
||||
- [ ] Metrics → Spend and CAC: origami.chat and explee.com campaign spend
|
||||
appears in the log on its own (the first time, all of it in the
|
||||
current month, with a note).
|
||||
- [ ] *Add* logs an amount for a month and channel; a bad amount or month
|
||||
is refused.
|
||||
- [ ] Pasting CSV rows imports them; one bad row imports nothing and names
|
||||
the row.
|
||||
- [ ] CAC for a month is its spend over its new customers (as counted on
|
||||
MRR and NRR); months without spend say so instead of showing $0.
|
||||
- [ ] By channel: a customer who first replied to an outreach email counts
|
||||
under Email; customers with no step before paying count as unknown.
|
||||
|
||||
### CLV and cohorts
|
||||
|
||||
- [ ] Metrics → CLV and cohorts shows CLV with what it rests on: average
|
||||
per customer, gross margin (it changes when you set product
|
||||
margins), monthly churn and lifetime. Check: CLV = average × margin ×
|
||||
lifetime.
|
||||
- [ ] With spend logged, CAC over 12 months and CLV:CAC appear.
|
||||
- [ ] Revenue by cohort: pick one customer who started alone in a month and
|
||||
compare the row with what they paid in Stripe, less refunds. A
|
||||
cohort whose refunds exceed its payments shows a negative amount.
|
||||
- [ ] *Gross profit* shows the same table after margin.
|
||||
|
||||
### Downloads and publishing
|
||||
|
||||
- [ ] Each Metrics table's *Download as CSV* gives a file that opens in a
|
||||
spreadsheet, with the same numbers as the page.
|
||||
- [ ] The MRR and NRR page shows churn, CLV, CAC and CLV:CAC above the
|
||||
chart.
|
||||
- [ ] Metrics → Publish: choosing what to show and *Save and preview*
|
||||
changes the preview; no customer is named anywhere in it.
|
||||
- [ ] **(real)** *Open a pull request* adds the page (or updates it) on the
|
||||
site's repository, checked with a build; after merging, it's live at
|
||||
the address chosen.
|
||||
|
||||
### Customers and the CRM
|
||||
|
||||
- [ ] Before Hermes has copied the CRM, Metrics → Customers and the CRM says
|
||||
no Accounts are copied, and lists every customer with billing.
|
||||
- [ ] Once Accounts are copied (after the CRM bridge works), customers are
|
||||
matched by stored ID, email or domain; check a few against EspoCRM.
|
||||
Gmail-style addresses never match by domain.
|
||||
- [ ] Where several Accounts fit, they're listed; choosing one by name and
|
||||
*Match* keeps it, and *automatic* undoes it.
|
||||
- [ ] *not in the CRM* moves a customer out of the "to fix" list.
|
||||
- [ ] *add to the CRM* on a paying customer queues an Account on the CRM
|
||||
queue; once Hermes adds it, the customer shows as matched.
|
||||
|
||||
## 9. Search
|
||||
|
||||
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
|
||||
(company or person) or a signal finds it, with a link to where it is.
|
||||
|
||||
## 9. Agents (MCP)
|
||||
## 10. Agents (MCP)
|
||||
|
||||
- [ ] `supermarket token` prints a token.
|
||||
- [ ] Claude Code (`claude mcp list`) shows Supermarket connected, and can
|
||||
list prospects or the CRM queue through it.
|
||||
- [ ] Hermes uses the Supermarket and Core MCP tools in its CRM job.
|
||||
|
||||
## 10. Data and safety
|
||||
## 11. Data and safety
|
||||
|
||||
- [ ] `~/.local/share/supermarket/secrets.json` is readable only by you
|
||||
(`ls -l`), and no key is ever shown in the app after saving.
|
||||
|
||||
@@ -161,6 +161,7 @@ func run(log *slog.Logger) error {
|
||||
go srv.RunOutreach(ctx)
|
||||
go srv.RunTracking(ctx)
|
||||
go srv.RunSEO(ctx)
|
||||
go srv.RunMetrics(ctx)
|
||||
// A sync falls due, and a claim times out, without anything being
|
||||
// written: refresh the state file each minute.
|
||||
go func() {
|
||||
|
||||
@@ -165,3 +165,217 @@ func (c *Client) Check(ctx context.Context) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Raw is an object as Stripe sent it, with its ID and creation time read.
|
||||
type Raw struct {
|
||||
ID string
|
||||
Object string
|
||||
Created int64
|
||||
JSON json.RawMessage
|
||||
}
|
||||
|
||||
// ListRaw reads every page of a list endpoint, newest first as Stripe sends
|
||||
// them, keeping each object whole.
|
||||
func (c *Client) ListRaw(ctx context.Context, path string, q url.Values, max int) ([]Raw, error) {
|
||||
if q == nil {
|
||||
q = url.Values{}
|
||||
}
|
||||
q.Set("limit", "100")
|
||||
var all []Raw
|
||||
for {
|
||||
var page struct {
|
||||
Data []json.RawMessage `json:"data"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := c.get(ctx, path, q, &page); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range page.Data {
|
||||
var head struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
}
|
||||
if err := json.Unmarshal(d, &head); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, Raw{ID: head.ID, Object: head.Object, Created: head.Created, JSON: d})
|
||||
}
|
||||
if !page.HasMore || len(page.Data) == 0 || (max > 0 && len(all) >= max) {
|
||||
return all, nil
|
||||
}
|
||||
q.Set("starting_after", all[len(all)-1].ID)
|
||||
}
|
||||
}
|
||||
|
||||
// InvoiceLines reads all of an invoice's lines (for invoices whose embedded
|
||||
// list was cut short).
|
||||
func (c *Client) InvoiceLines(ctx context.Context, invoiceID string) ([]json.RawMessage, error) {
|
||||
raws, err := c.ListRaw(ctx, "/v1/invoices/"+url.PathEscape(invoiceID)+"/lines", nil, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]json.RawMessage, len(raws))
|
||||
for i, r := range raws {
|
||||
out[i] = r.JSON
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// EventTypes are the events the sync follows.
|
||||
var EventTypes = []string{
|
||||
"customer.created", "customer.updated", "customer.deleted",
|
||||
"invoice.created", "invoice.finalized", "invoice.updated", "invoice.paid", "invoice.voided", "invoice.marked_uncollectible",
|
||||
"credit_note.created", "credit_note.updated", "credit_note.voided",
|
||||
"refund.created", "refund.updated", "charge.refunded",
|
||||
}
|
||||
|
||||
// Event is one change, with the object as it was after it.
|
||||
type Event struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Created int64 `json:"created"`
|
||||
Data struct {
|
||||
Object json.RawMessage `json:"object"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// Events lists the events of the followed types after a time, oldest first.
|
||||
func (c *Client) Events(ctx context.Context, after time.Time) ([]Event, error) {
|
||||
q := url.Values{"created[gt]": {strconv.FormatInt(after.Unix(), 10)}}
|
||||
for _, t := range EventTypes {
|
||||
q.Add("types[]", t)
|
||||
}
|
||||
raws, err := c.ListRaw(ctx, "/v1/events", q, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Event, 0, len(raws))
|
||||
for i := len(raws) - 1; i >= 0; i-- {
|
||||
var e Event
|
||||
if err := json.Unmarshal(raws[i].JSON, &e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Line is an invoice line, read from either shape Stripe has used: the
|
||||
// older one (price, type, proration on the line) and the 2025 one (pricing,
|
||||
// parent).
|
||||
type Line struct {
|
||||
ID string
|
||||
Amount int64 // after discounts, before tax
|
||||
Currency string
|
||||
PeriodStart int64
|
||||
PeriodEnd int64
|
||||
Subscription string
|
||||
Price string
|
||||
Product string
|
||||
Interval string // day, week, month, year; "" for one-off
|
||||
IntervalCount int
|
||||
Quantity int64
|
||||
Proration bool
|
||||
Recurring bool
|
||||
Description string
|
||||
}
|
||||
|
||||
// ParseLine reads an invoice line.
|
||||
func ParseLine(raw json.RawMessage) (Line, error) {
|
||||
var l struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Amount int64 `json:"amount"`
|
||||
Currency string `json:"currency"`
|
||||
Period struct {
|
||||
Start int64 `json:"start"`
|
||||
End int64 `json:"end"`
|
||||
} `json:"period"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
Proration bool `json:"proration"`
|
||||
Type string `json:"type"`
|
||||
Subscription json.RawMessage `json:"subscription"`
|
||||
Price *struct {
|
||||
ID string `json:"id"`
|
||||
Product json.RawMessage `json:"product"`
|
||||
Recurring *struct {
|
||||
Interval string `json:"interval"`
|
||||
IntervalCount int `json:"interval_count"`
|
||||
} `json:"recurring"`
|
||||
} `json:"price"`
|
||||
Pricing *struct {
|
||||
PriceDetails *struct {
|
||||
Price json.RawMessage `json:"price"`
|
||||
Product string `json:"product"`
|
||||
} `json:"price_details"`
|
||||
} `json:"pricing"`
|
||||
Parent *struct {
|
||||
Type string `json:"type"`
|
||||
SubscriptionItemDetails *struct {
|
||||
Subscription string `json:"subscription"`
|
||||
Proration bool `json:"proration"`
|
||||
} `json:"subscription_item_details"`
|
||||
} `json:"parent"`
|
||||
DiscountAmounts []struct {
|
||||
Amount int64 `json:"amount"`
|
||||
} `json:"discount_amounts"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &l); err != nil {
|
||||
return Line{}, err
|
||||
}
|
||||
out := Line{ID: l.ID, Amount: l.Amount, Currency: l.Currency, PeriodStart: l.Period.Start, PeriodEnd: l.Period.End,
|
||||
Quantity: l.Quantity, Proration: l.Proration, Subscription: idOf(l.Subscription), Description: l.Description}
|
||||
for _, d := range l.DiscountAmounts {
|
||||
out.Amount -= d.Amount
|
||||
}
|
||||
if l.Price != nil {
|
||||
out.Price, out.Product = l.Price.ID, idOf(l.Price.Product)
|
||||
if l.Price.Recurring != nil {
|
||||
out.Interval, out.IntervalCount = l.Price.Recurring.Interval, l.Price.Recurring.IntervalCount
|
||||
}
|
||||
}
|
||||
if l.Pricing != nil && l.Pricing.PriceDetails != nil {
|
||||
out.Price = or(out.Price, idOf(l.Pricing.PriceDetails.Price))
|
||||
out.Product = or(out.Product, l.Pricing.PriceDetails.Product)
|
||||
}
|
||||
if l.Parent != nil && l.Parent.SubscriptionItemDetails != nil {
|
||||
out.Subscription = or(out.Subscription, l.Parent.SubscriptionItemDetails.Subscription)
|
||||
out.Proration = out.Proration || l.Parent.SubscriptionItemDetails.Proration
|
||||
}
|
||||
out.Recurring = l.Type == "subscription" || (l.Parent != nil && l.Parent.Type == "subscription_item_details") || out.Interval != ""
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func or(a, b string) string {
|
||||
if a != "" {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// idOf reads a field that is an ID string or an expanded object with an id.
|
||||
func idOf(raw json.RawMessage) string {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return ""
|
||||
}
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return s
|
||||
}
|
||||
var o struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &o)
|
||||
return o.ID
|
||||
}
|
||||
|
||||
// GetRaw reads one object.
|
||||
func (c *Client) GetRaw(ctx context.Context, path string, q url.Values) (json.RawMessage, error) {
|
||||
var out json.RawMessage
|
||||
err := c.get(ctx, path, q, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// IDOf reads a field that is an ID string or an expanded object with an id.
|
||||
func IDOf(raw json.RawMessage) string { return idOf(raw) }
|
||||
|
||||
@@ -612,3 +612,7 @@ func WriteState(d *db.DB, now time.Time) error {
|
||||
}
|
||||
return os.Rename(tmp, filepath.Clean(StateFile))
|
||||
}
|
||||
|
||||
// IsFreeMail reports whether a domain is a free email provider's, which
|
||||
// says nothing about the company.
|
||||
func IsFreeMail(domain string) bool { return freeMail[strings.ToLower(domain)] }
|
||||
|
||||
@@ -495,6 +495,78 @@ CREATE TABLE seo_briefs (
|
||||
live_at TEXT
|
||||
);
|
||||
CREATE INDEX seo_briefs_by_site ON seo_briefs (site, id);
|
||||
`,
|
||||
// 18: the full Stripe data for the metrics: every customer, invoice,
|
||||
// credit note and refund as Stripe sent it, and the invoice lines the
|
||||
// MRR model reads.
|
||||
`
|
||||
CREATE TABLE stripe_objects (
|
||||
kind TEXT NOT NULL, -- customer, invoice, credit_note, refund
|
||||
id TEXT NOT NULL,
|
||||
customer TEXT NOT NULL DEFAULT '',
|
||||
created INTEGER NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT '',
|
||||
currency TEXT NOT NULL DEFAULT '',
|
||||
amount INTEGER NOT NULL DEFAULT 0, -- invoice: total; credit note: total; refund: amount
|
||||
data TEXT NOT NULL,
|
||||
PRIMARY KEY (kind, id)
|
||||
);
|
||||
CREATE INDEX stripe_objects_by_customer ON stripe_objects (kind, customer);
|
||||
CREATE TABLE stripe_invoice_lines (
|
||||
invoice TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
customer TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT '', -- the invoice's
|
||||
currency TEXT NOT NULL DEFAULT '',
|
||||
amount INTEGER NOT NULL DEFAULT 0, -- after discounts, before tax
|
||||
period_start INTEGER NOT NULL DEFAULT 0,
|
||||
period_end INTEGER NOT NULL DEFAULT 0,
|
||||
subscription TEXT NOT NULL DEFAULT '',
|
||||
price TEXT NOT NULL DEFAULT '',
|
||||
product TEXT NOT NULL DEFAULT '',
|
||||
interval TEXT NOT NULL DEFAULT '',
|
||||
interval_count INTEGER NOT NULL DEFAULT 0,
|
||||
quantity INTEGER NOT NULL DEFAULT 0,
|
||||
proration INTEGER NOT NULL DEFAULT 0,
|
||||
recurring INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (invoice, id)
|
||||
);
|
||||
CREATE INDEX stripe_invoice_lines_by_customer ON stripe_invoice_lines (customer, period_start);
|
||||
`,
|
||||
// 19: invoice lines' descriptions, which name the product when the key
|
||||
// can't read Products.
|
||||
`
|
||||
ALTER TABLE stripe_invoice_lines ADD COLUMN description TEXT NOT NULL DEFAULT '';
|
||||
`,
|
||||
// 20: Stripe customers matched to EspoCRM Accounts by hand (the
|
||||
// automatic matches are worked out each time).
|
||||
`
|
||||
CREATE TABLE crm_matches (
|
||||
customer TEXT PRIMARY KEY, -- cus_…
|
||||
espo_id TEXT NOT NULL DEFAULT '', -- the Account; '' means "not in the CRM"
|
||||
set_at TEXT NOT NULL
|
||||
);
|
||||
`,
|
||||
// 21: the spend log, for CAC.
|
||||
`
|
||||
CREATE TABLE spend (
|
||||
id INTEGER PRIMARY KEY,
|
||||
month TEXT NOT NULL, -- YYYY-MM
|
||||
channel TEXT NOT NULL, -- a funnel channel, or general
|
||||
amount_cents INTEGER NOT NULL,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
source TEXT NOT NULL DEFAULT 'manual', -- manual, csv, origami, explee
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX spend_by_month ON spend (month);
|
||||
-- What each outside campaign had spent when last seen, so only the
|
||||
-- difference is added.
|
||||
CREATE TABLE spend_seen (
|
||||
source TEXT NOT NULL,
|
||||
campaign TEXT NOT NULL,
|
||||
spend_cents INTEGER NOT NULL,
|
||||
PRIMARY KEY (source, campaign)
|
||||
);
|
||||
`,
|
||||
}
|
||||
|
||||
|
||||
@@ -534,3 +534,20 @@ func BuiltFile(outDir, rel string) (string, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(outDir, rel))
|
||||
return string(raw), err
|
||||
}
|
||||
|
||||
// UpsertPage writes a content file, or, if it exists, replaces its body and
|
||||
// sets the given front matter fields.
|
||||
func (r *Repo) UpsertPage(rel string, fields []Field, body string) error {
|
||||
if !r.Exists(rel) {
|
||||
return r.NewPage(rel, fields, body)
|
||||
}
|
||||
if err := r.ReplaceBody(rel, body); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range fields {
|
||||
if err := r.SetFrontMatter(rel, f.Key, f.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// CLV is customer lifetime value, and what it rests on. Amounts are in
|
||||
// cents.
|
||||
type CLV struct {
|
||||
Month string // the last complete month it's measured on
|
||||
ARPA float64 // MRR per paying customer
|
||||
Margin float64 // percent, weighted by each product's revenue
|
||||
Churn float64 // percent of customers lost a month, averaged over 12 months
|
||||
ChurnMonths int // how many months the average covers
|
||||
Lifetime float64 // months: 1 ÷ churn
|
||||
Value float64 // ARPA × margin ÷ churn; -1 when churn is 0
|
||||
CAC float64 // over the same 12 months; -1 without spend or new customers
|
||||
Ratio float64 // CLV ÷ CAC; -1 when either is unknown
|
||||
}
|
||||
|
||||
// BuildCLV works CLV out from the MRR model, the margins and the spend log:
|
||||
// the last complete month's ARPA, the revenue-weighted margin of the last
|
||||
// 12 months, and the customer churn rate averaged over the last 12 complete
|
||||
// months (customers lost ÷ customers at the start).
|
||||
func BuildCLV(d *db.DB, m *Model, now time.Time) (*CLV, error) {
|
||||
months := m.Months
|
||||
if len(months) > 0 && months[len(months)-1].Partial {
|
||||
months = months[:len(months)-1]
|
||||
}
|
||||
if len(months) < 2 {
|
||||
return nil, nil
|
||||
}
|
||||
last := months[len(months)-1]
|
||||
c := &CLV{Month: last.Month, ARPA: last.ARPA(), Value: -1, CAC: -1, Ratio: -1}
|
||||
products, err := Products(d, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rev := map[string]int64{}
|
||||
for _, p := range products {
|
||||
rev[p.ID] = p.Revenue
|
||||
}
|
||||
c.Margin = WeightedMargin(LoadMargins(d), rev)
|
||||
var lost, base int
|
||||
// Churn needs the month before, so it starts a month later than CAC.
|
||||
for i := max(1, len(months)-12); i < len(months); i++ {
|
||||
base += months[i-1].Customers
|
||||
lost += months[i].ChurnCount
|
||||
c.ChurnMonths++
|
||||
}
|
||||
from, newCount := max(0, len(months)-12), 0
|
||||
for i := from; i < len(months); i++ {
|
||||
newCount += months[i].NewCount
|
||||
}
|
||||
if base > 0 {
|
||||
c.Churn = 100 * float64(lost) / float64(base)
|
||||
}
|
||||
if c.Churn > 0 {
|
||||
c.Lifetime = 100 / c.Churn
|
||||
c.Value = c.ARPA * c.Margin / 100 * c.Lifetime
|
||||
}
|
||||
var spend int64
|
||||
if err := d.QueryRow(`SELECT coalesce(sum(amount_cents), 0) FROM spend WHERE month BETWEEN ? AND ?`,
|
||||
months[from].Month, last.Month).Scan(&spend); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if spend > 0 && newCount > 0 {
|
||||
c.CAC = float64(spend) / float64(newCount)
|
||||
if c.Value > 0 {
|
||||
c.Ratio = c.Value / c.CAC
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// --- Revenue by cohort ---
|
||||
|
||||
// revenueEvent is money in (or out) for a customer at a time.
|
||||
type revenueEvent struct {
|
||||
customer string
|
||||
at int64
|
||||
cents int64
|
||||
}
|
||||
|
||||
// cashFlows are each customer's payments, net of refunds and of credit
|
||||
// notes that gave money back without a refund: paid invoices' amount paid
|
||||
// when paid, refunds that went through when made, and post-payment credit
|
||||
// notes (less any part refunded, which is counted as a refund) when issued.
|
||||
// Pre-payment credit notes already lowered the amount paid.
|
||||
func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) {
|
||||
var out []revenueEvent
|
||||
rows, err := d.Query(`SELECT customer, coalesce(json_extract(data, '$.status_transitions.paid_at'), created),
|
||||
coalesce(json_extract(data, '$.amount_paid'), 0) FROM stripe_objects
|
||||
WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != ''`, currency)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var e revenueEvent
|
||||
if err := rows.Scan(&e.customer, &e.at, &e.cents); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if e.cents != 0 {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
rows, err = d.Query(`SELECT customer, created, amount FROM stripe_objects
|
||||
WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != ''`, currency)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var e revenueEvent
|
||||
if err := rows.Scan(&e.customer, &e.at, &e.cents); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
e.cents = -e.cents
|
||||
out = append(out, e)
|
||||
}
|
||||
rows.Close()
|
||||
rows, err = d.Query(`SELECT customer, created, data FROM stripe_objects
|
||||
WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != ''`, currency)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var cust, raw string
|
||||
var at int64
|
||||
if err := rows.Scan(&cust, &at, &raw); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
var cn struct {
|
||||
Type string `json:"type"`
|
||||
PostPaymentAmount int64 `json:"post_payment_amount"`
|
||||
Refunds []struct {
|
||||
AmountRefunded int64 `json:"amount_refunded"`
|
||||
} `json:"refunds"`
|
||||
RefundAmount int64 `json:"refund_amount"` // older API versions
|
||||
Refund any `json:"refund"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &cn)
|
||||
credit := cn.PostPaymentAmount
|
||||
for _, r := range cn.Refunds {
|
||||
credit -= r.AmountRefunded
|
||||
}
|
||||
if cn.Refund != nil && len(cn.Refunds) == 0 {
|
||||
credit = 0 // an older note tied to a refund: counted there
|
||||
}
|
||||
if credit > 0 {
|
||||
out = append(out, revenueEvent{customer: cust, at: at, cents: -credit})
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Cell is one cohort month's figure; Known is false for months not
|
||||
// reached yet. (Revenue can be negative, when refunds exceed payments.)
|
||||
type Cell struct {
|
||||
V float64
|
||||
Known bool
|
||||
}
|
||||
|
||||
// CohortRevenue is what a signup cohort has paid: cumulative revenue per
|
||||
// customer, k months after their first paid month.
|
||||
type CohortRevenue struct {
|
||||
Month string
|
||||
Customers int
|
||||
PerCustomer []Cell // cents, cumulative, for months 0, 1, 2…
|
||||
Margin []Cell // the same, after gross margin
|
||||
}
|
||||
|
||||
// RevenueByCohort follows the last n signup cohorts for up to span months:
|
||||
// the money they paid, net of refunds and credits, cumulative and per
|
||||
// customer, with the margin-weighted gross profit beside it.
|
||||
func RevenueByCohort(d *db.DB, m *Model, n, span int, now time.Time) ([]CohortRevenue, error) {
|
||||
flows, err := cashFlows(d, m.Currency)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
products, err := Products(d, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rev := map[string]int64{}
|
||||
for _, p := range products {
|
||||
rev[p.ID] = p.Revenue
|
||||
}
|
||||
margin := WeightedMargin(LoadMargins(d), rev) / 100
|
||||
idx := map[string]int{}
|
||||
for i, mo := range m.Months {
|
||||
idx[mo.Month] = i
|
||||
}
|
||||
// Each customer's payments, by month index.
|
||||
paid := map[string]map[int]int64{}
|
||||
for _, f := range flows {
|
||||
mon := time.Unix(f.at, 0).UTC().Format("2006-01")
|
||||
i, ok := idx[mon]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if paid[f.customer] == nil {
|
||||
paid[f.customer] = map[int]int64{}
|
||||
}
|
||||
paid[f.customer][i] += f.cents
|
||||
}
|
||||
members := map[string][]string{}
|
||||
for c, first := range m.First {
|
||||
members[first] = append(members[first], c)
|
||||
}
|
||||
var out []CohortRevenue
|
||||
for i := len(m.Months) - 1; i >= 0 && len(out) < n; i-- {
|
||||
cs := members[m.Months[i].Month]
|
||||
if len(cs) == 0 {
|
||||
continue
|
||||
}
|
||||
co := CohortRevenue{Month: m.Months[i].Month, Customers: len(cs)}
|
||||
var cum float64
|
||||
for k := 0; k <= span; k++ {
|
||||
if i+k >= len(m.Months) {
|
||||
co.PerCustomer = append(co.PerCustomer, Cell{})
|
||||
co.Margin = append(co.Margin, Cell{})
|
||||
continue
|
||||
}
|
||||
for _, c := range cs {
|
||||
cum += float64(paid[c][i+k])
|
||||
}
|
||||
per := cum / float64(len(cs))
|
||||
co.PerCustomer = append(co.PerCustomer, Cell{per, true})
|
||||
co.Margin = append(co.Margin, Cell{per * margin, true})
|
||||
}
|
||||
out = append(out, co)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCLV(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC)
|
||||
// Ten customers at $100 from January; one leaves at the end of March,
|
||||
// one at the end of May. Products: all "prod_core", at a 50% margin.
|
||||
for i := 0; i < 10; i++ {
|
||||
to := "2026-08"
|
||||
switch i {
|
||||
case 0:
|
||||
to = "2026-03"
|
||||
case 1:
|
||||
to = "2026-05"
|
||||
}
|
||||
addLines(t, d, monthly(fmt.Sprintf("cus_%d", i), 10000, "2026-01", to)...)
|
||||
}
|
||||
d.Exec(`UPDATE stripe_invoice_lines SET product = 'prod_core'`)
|
||||
SaveMargins(d, Margins{Default: 60, ByProduct: map[string]float64{"prod_core": 50}})
|
||||
AddSpend(d, Spend{Month: "2026-01", Channel: "general", AmountCents: 300000}, now)
|
||||
m, _ := Build(d, now)
|
||||
c, err := BuildCLV(d, m, now)
|
||||
if err != nil || c == nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Complete months: Jan–Jun. Churn: 2 lost over 5 month-starts of
|
||||
// 10+10+9+9+8 customers = 2/46.
|
||||
if c.Month != "2026-06" || c.ARPA != 10000 || c.Margin != 50 || c.ChurnMonths != 5 || !near(c.Churn*46, 200) {
|
||||
t.Fatalf("clv: %+v", c)
|
||||
}
|
||||
// CLV = $100 × 50% × 23 months = $1,150; CAC = $3,000 ÷ 10 = $300.
|
||||
if !near(c.Value, 115000) || !near(c.CAC, 30000) || c.Ratio < 3.83 || c.Ratio > 3.84 {
|
||||
t.Errorf("value: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevenueByCohort(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 4, 15, 0, 0, 0, 0, time.UTC)
|
||||
addLines(t, d, monthly("cus_a", 10000, "2026-01", "2026-05")...)
|
||||
addLines(t, d, monthly("cus_b", 10000, "2026-01", "2026-05")...)
|
||||
at := func(s string) int64 { return day(s) }
|
||||
for _, inv := range []struct {
|
||||
id, cust string
|
||||
paid int64
|
||||
when string
|
||||
}{
|
||||
{"p1", "cus_a", 10000, "2026-01-10"}, {"p2", "cus_a", 10000, "2026-02-10"}, {"p3", "cus_b", 10000, "2026-01-10"},
|
||||
{"p4", "cus_b", 10000, "2026-02-10"}, {"p5", "cus_b", 10000, "2026-03-10"},
|
||||
} {
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, data) VALUES ('invoice', ?, ?, ?, 'paid', 'usd', ?)`,
|
||||
inv.id, inv.cust, at(inv.when), fmt.Sprintf(`{"amount_paid":%d,"status_transitions":{"paid_at":%d}}`, inv.paid, at(inv.when)))
|
||||
}
|
||||
// cus_b gets $40 back in February; a $20 post-payment credit in March,
|
||||
// $5 of it refunded (counted as a refund); and a pre-payment note,
|
||||
// which the amount paid already reflects.
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES
|
||||
('refund', 'r1', 'cus_b', ?, 'succeeded', 'usd', 4000, '{}'),
|
||||
('refund', 'r2', 'cus_b', ?, 'canceled', 'usd', 9999, '{}'),
|
||||
('credit_note', 'cn1', 'cus_b', ?, 'issued', 'usd', 2000, '{"type":"post_payment","post_payment_amount":2000,"refunds":[{"amount_refunded":500}]}'),
|
||||
('credit_note', 'cn2', 'cus_a', ?, 'issued', 'usd', 3000, '{"type":"pre_payment","pre_payment_amount":3000,"post_payment_amount":0}')`,
|
||||
at("2026-02-20"), at("2026-02-21"), at("2026-03-20"), at("2026-02-01"))
|
||||
m, _ := Build(d, now)
|
||||
cos, err := RevenueByCohort(d, m, 5, 4, now)
|
||||
if err != nil || len(cos) != 1 {
|
||||
t.Fatalf("cohorts: %+v %v", cos, err)
|
||||
}
|
||||
co := cos[0]
|
||||
// Two customers, cumulative: Jan $200 → $100 each; Feb +$200 −$40 =
|
||||
// $360 → $180; Mar +$100 −$15 = $445 → $222.50; Apr nothing → same.
|
||||
want := []float64{10000, 18000, 22250, 22250}
|
||||
for i, w := range want {
|
||||
if c := co.PerCustomer[i]; !c.Known || !near(c.V, w) {
|
||||
t.Errorf("month %d: %+v, want %.0f", i, c, w)
|
||||
}
|
||||
}
|
||||
if co.PerCustomer[4].Known {
|
||||
t.Error("a month not reached yet is known")
|
||||
}
|
||||
if !near(co.Margin[1].V, 18000*0.6) {
|
||||
t.Errorf("gross profit: %v", co.Margin[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNegativeCohortRevenueShows(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 3, 15, 0, 0, 0, 0, time.UTC)
|
||||
addLines(t, d, monthly("cus_r", 10000, "2026-01", "2026-02")...)
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, data) VALUES ('invoice', 'pr', 'cus_r', ?, 'paid', 'usd', '{"amount_paid":10000}')`, day("2026-01-10"))
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES ('refund', 'rr', 'cus_r', ?, 'succeeded', 'usd', 15000, '{}')`, day("2026-02-01"))
|
||||
m, _ := Build(d, now)
|
||||
cos, _ := RevenueByCohort(d, m, 5, 2, now)
|
||||
if len(cos) != 1 || !cos[0].PerCustomer[1].Known || cos[0].PerCustomer[1].V != -5000 {
|
||||
t.Errorf("negative revenue: %+v", cos)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// How a customer was matched to an Account.
|
||||
const (
|
||||
MatchStoredID = "stored ID"
|
||||
MatchEmail = "email"
|
||||
MatchDomain = "domain"
|
||||
MatchManual = "by you"
|
||||
MatchNotInCRM = "not in the CRM" // the user said so
|
||||
MatchNone = ""
|
||||
MatchAmbiguous = "several"
|
||||
)
|
||||
|
||||
// Account is an EspoCRM Account, as copied.
|
||||
type Account struct {
|
||||
ID, Name, Domain string
|
||||
}
|
||||
|
||||
// Match is a Stripe customer and the Account it belongs to.
|
||||
type Match struct {
|
||||
Customer Customer
|
||||
Account Account
|
||||
How string
|
||||
Candidates []Account // when several Accounts fit
|
||||
MRR float64 // now, in cents
|
||||
Prospect string // the Phase 2 prospect it's tied to (contact:12), if any
|
||||
}
|
||||
|
||||
var stripeIDFields = []string{"stripeCustomerId", "cStripeCustomerId", "stripeId", "cStripeId", "stripeCustomerID"}
|
||||
|
||||
// crmIndex is the copied CRM, indexed for matching.
|
||||
type crmIndex struct {
|
||||
accounts map[string]Account
|
||||
byStripe map[string]string // cus_… → Account
|
||||
byEmail map[string][]string // email → Accounts (theirs, or their Contacts')
|
||||
byDomain map[string][]string
|
||||
}
|
||||
|
||||
func loadCRM(d *db.DB) (*crmIndex, error) {
|
||||
ix := &crmIndex{accounts: map[string]Account{}, byStripe: map[string]string{}, byEmail: map[string][]string{}, byDomain: map[string][]string{}}
|
||||
rows, err := d.Query(`SELECT entity, espo_id, name, email, domain, data FROM crm_records WHERE entity IN ('Account', 'Contact')`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type contact struct{ email, account string }
|
||||
var contacts []contact
|
||||
for rows.Next() {
|
||||
var entity, id, name, email, domain, raw string
|
||||
if err := rows.Scan(&entity, &id, &name, &email, &domain, &raw); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal([]byte(raw), &data)
|
||||
if entity == "Contact" {
|
||||
if acc, _ := data["accountId"].(string); acc != "" && email != "" {
|
||||
contacts = append(contacts, contact{strings.ToLower(email), acc})
|
||||
}
|
||||
continue
|
||||
}
|
||||
ix.accounts[id] = Account{ID: id, Name: name, Domain: domain}
|
||||
for _, f := range stripeIDFields {
|
||||
if v, _ := data[f].(string); strings.HasPrefix(v, "cus_") {
|
||||
ix.byStripe[v] = id
|
||||
}
|
||||
}
|
||||
if email != "" {
|
||||
ix.byEmail[strings.ToLower(email)] = appendUnique(ix.byEmail[strings.ToLower(email)], id)
|
||||
}
|
||||
if domain != "" && !crm.IsFreeMail(domain) {
|
||||
ix.byDomain[domain] = appendUnique(ix.byDomain[domain], id)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for _, c := range contacts {
|
||||
if _, ok := ix.accounts[c.account]; ok {
|
||||
ix.byEmail[c.email] = appendUnique(ix.byEmail[c.email], c.account)
|
||||
}
|
||||
}
|
||||
return ix, rows.Err()
|
||||
}
|
||||
|
||||
func appendUnique(s []string, v string) []string {
|
||||
if slices.Contains(s, v) {
|
||||
return s
|
||||
}
|
||||
return append(s, v)
|
||||
}
|
||||
|
||||
// customerMeta reads the fields matching needs from a Stripe customer.
|
||||
type customerMeta struct {
|
||||
Customer
|
||||
EspoID string // from the customer's metadata
|
||||
}
|
||||
|
||||
func loadCustomers(d *db.DB) ([]customerMeta, error) {
|
||||
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ? AND status != 'deleted'`, KindCustomer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []customerMeta
|
||||
for rows.Next() {
|
||||
var id, raw string
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &c)
|
||||
m := customerMeta{Customer: Customer{ID: id, Name: c.Name, Email: strings.ToLower(c.Email)}}
|
||||
for _, k := range []string{"espocrm_id", "espo_id", "crm_id", "espocrm_account_id"} {
|
||||
if v := c.Metadata[k]; v != "" {
|
||||
m.EspoID = v
|
||||
break
|
||||
}
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// manual are the user's choices: customer → Account ("" for not in the CRM).
|
||||
func manual(d *db.DB) (map[string]string, error) {
|
||||
rows, err := d.Query(`SELECT customer, espo_id FROM crm_matches`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var c, a string
|
||||
if err := rows.Scan(&c, &a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[c] = a
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Matches matches every Stripe customer with billing to an Account: the
|
||||
// user's choice first, then a stored ID (either side), then email (an
|
||||
// Account's or one of its Contacts'), then the email's domain (not free
|
||||
// mail). Paying customers come first, by MRR.
|
||||
func Matches(d *db.DB, model *Model) ([]Match, error) {
|
||||
ix, err := loadCRM(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
custs, err := loadCustomers(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
man, err := manual(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
billed := map[string]bool{}
|
||||
rows, err := d.Query(`SELECT DISTINCT customer FROM stripe_objects WHERE kind = 'invoice' AND status IN ('paid', 'open')`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var c string
|
||||
rows.Scan(&c)
|
||||
billed[c] = true
|
||||
}
|
||||
rows.Close()
|
||||
prospects := map[string]string{}
|
||||
rows, err = d.Query(`SELECT id, subject FROM stripe_customers WHERE subject NOT LIKE 'stripe:%'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var c, s string
|
||||
rows.Scan(&c, &s)
|
||||
prospects[c] = s
|
||||
}
|
||||
rows.Close()
|
||||
// Accounts Hermes created (or found) for customers queued from here.
|
||||
added := map[string]Account{}
|
||||
rows, err = d.Query(`SELECT substr(key, 17), espo_id, json_extract(fields, '$.name') FROM crm_actions
|
||||
WHERE key LIKE 'stripe-customer:%' AND status = 'done' AND espo_id != ''`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var c, id string
|
||||
var name *string
|
||||
rows.Scan(&c, &id, &name)
|
||||
a := ix.accounts[id]
|
||||
if a.ID == "" {
|
||||
a = Account{ID: id}
|
||||
if name != nil {
|
||||
a.Name = *name
|
||||
}
|
||||
}
|
||||
added[c] = a
|
||||
}
|
||||
rows.Close()
|
||||
var now map[string]float64
|
||||
if model != nil && model.Last() != nil {
|
||||
now = model.Last().ByCustomer
|
||||
}
|
||||
var out []Match
|
||||
for _, c := range custs {
|
||||
if !billed[c.ID] {
|
||||
continue
|
||||
}
|
||||
m := Match{Customer: c.Customer, MRR: now[c.ID], Prospect: prospects[c.ID]}
|
||||
if a, ok := man[c.ID]; ok {
|
||||
if a == "" {
|
||||
m.How = MatchNotInCRM
|
||||
} else {
|
||||
m.How, m.Account = MatchManual, ix.accounts[a]
|
||||
if m.Account.ID == "" {
|
||||
m.Account = Account{ID: a, Name: "(an Account not copied yet)"}
|
||||
}
|
||||
}
|
||||
out = append(out, m)
|
||||
continue
|
||||
}
|
||||
pick := func(ids []string, how string) bool {
|
||||
switch len(ids) {
|
||||
case 0:
|
||||
return false
|
||||
case 1:
|
||||
m.Account, m.How = ix.accounts[ids[0]], how
|
||||
default:
|
||||
m.How = MatchAmbiguous
|
||||
for _, id := range ids {
|
||||
m.Candidates = append(m.Candidates, ix.accounts[id])
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case added[c.ID].ID != "":
|
||||
m.Account, m.How = added[c.ID], MatchStoredID
|
||||
case c.EspoID != "" && ix.accounts[c.EspoID].ID != "":
|
||||
m.Account, m.How = ix.accounts[c.EspoID], MatchStoredID
|
||||
case ix.byStripe[c.ID] != "":
|
||||
m.Account, m.How = ix.accounts[ix.byStripe[c.ID]], MatchStoredID
|
||||
case c.Email != "" && pick(ix.byEmail[c.Email], MatchEmail):
|
||||
case pick(ix.byDomain[crm.EmailDomain(c.Email)], MatchDomain):
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b Match) int {
|
||||
switch {
|
||||
case a.MRR > b.MRR:
|
||||
return -1
|
||||
case a.MRR < b.MRR:
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email))
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SetMatch records the user's choice: an Account, "" for "not in the CRM",
|
||||
// or forget clears it (back to automatic).
|
||||
func SetMatch(d *db.DB, customer, account string, forget bool, now time.Time) error {
|
||||
if forget {
|
||||
_, err := d.Exec(`DELETE FROM crm_matches WHERE customer = ?`, customer)
|
||||
return err
|
||||
}
|
||||
_, err := d.Exec(`INSERT INTO crm_matches (customer, espo_id, set_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT (customer) DO UPDATE SET espo_id = excluded.espo_id, set_at = excluded.set_at`, customer, account, now.UTC().Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
|
||||
// Accounts lists the copied Accounts, by name, for choosing one.
|
||||
func Accounts(d *db.DB) ([]Account, error) {
|
||||
rows, err := d.Query(`SELECT espo_id, name, domain FROM crm_records WHERE entity = 'Account' ORDER BY name COLLATE NOCASE`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Account
|
||||
for rows.Next() {
|
||||
var a Account
|
||||
if err := rows.Scan(&a.ID, &a.Name, &a.Domain); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MatchSummary counts the matches by how they were made.
|
||||
func MatchSummary(ms []Match) map[string]int {
|
||||
out := map[string]int{}
|
||||
for _, m := range ms {
|
||||
out[m.How]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMatches(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Now()
|
||||
exec := func(q string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := d.Exec(q, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// The CRM: Acme (with a Contact), Beta (holding a Stripe ID), two
|
||||
// Accounts at one domain, and one at gmail.com.
|
||||
for _, r := range []struct{ entity, id, name, email, domain, data string }{
|
||||
{"Account", "a1", "Acme", "", "acme.example", `{}`},
|
||||
{"Contact", "c1", "Ann", "ann@acme.example", "acme.example", `{"accountId":"a1"}`},
|
||||
{"Account", "a2", "Beta", "", "beta.example", `{"cStripeCustomerId":"cus_beta"}`},
|
||||
{"Account", "a3", "Twin One", "", "twin.example", `{}`},
|
||||
{"Account", "a4", "Twin Two", "", "twin.example", `{}`},
|
||||
{"Account", "a5", "Solo", "solo@gmail.com", "gmail.com", `{}`},
|
||||
} {
|
||||
exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, synced_at) VALUES (?, ?, ?, ?, ?, ?, '')`,
|
||||
r.entity, r.id, r.name, r.email, r.domain, r.data)
|
||||
}
|
||||
for _, c := range []struct{ id, data string }{
|
||||
{"cus_ann", `{"name":"Ann","email":"ANN@acme.example"}`},
|
||||
{"cus_beta", `{"name":"Beta Inc","email":"x@elsewhere.example"}`},
|
||||
{"cus_meta", `{"name":"Meta","email":"m@meta.example","metadata":{"espocrm_id":"a1"}}`},
|
||||
{"cus_twin", `{"name":"Twin","email":"t@twin.example"}`},
|
||||
{"cus_gm", `{"name":"G","email":"other@gmail.com"}`},
|
||||
{"cus_free", `{"name":"Free","email":"free@nowhere.example"}`},
|
||||
{"cus_unbilled", `{"name":"Never billed","email":"ann@acme.example"}`},
|
||||
{"cus_new", `{"name":"Newco","email":"hi@newco.example"}`},
|
||||
} {
|
||||
exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', ?, ?, ?)`, c.id, c.id, c.data)
|
||||
if c.id != "cus_unbilled" {
|
||||
exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', ?, ?, 'paid', 'usd', '{}')`, "in_"+c.id, c.id)
|
||||
}
|
||||
}
|
||||
exec(`INSERT INTO crm_actions (key, kind, entity, fields, status, espo_id) VALUES ('stripe-customer:cus_new', 'create', 'Account', '{"name":"Newco"}', 'done', 'a9')`)
|
||||
|
||||
ms, err := Matches(d, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]Match{}
|
||||
for _, m := range ms {
|
||||
got[m.Customer.ID] = m
|
||||
}
|
||||
if _, ok := got["cus_unbilled"]; ok {
|
||||
t.Error("a customer never billed is listed")
|
||||
}
|
||||
for id, want := range map[string]struct{ account, how string }{
|
||||
"cus_ann": {"a1", MatchEmail}, "cus_beta": {"a2", MatchStoredID}, "cus_meta": {"a1", MatchStoredID},
|
||||
"cus_twin": {"", MatchAmbiguous}, "cus_gm": {"", MatchNone}, "cus_free": {"", MatchNone}, "cus_new": {"a9", MatchStoredID},
|
||||
} {
|
||||
if m := got[id]; m.Account.ID != want.account || m.How != want.how {
|
||||
t.Errorf("%s: %+v, want %s by %q", id, m, want.account, want.how)
|
||||
}
|
||||
}
|
||||
if len(got["cus_twin"].Candidates) != 2 || got["cus_new"].Account.Name != "Newco" {
|
||||
t.Errorf("twin: %+v; new: %+v", got["cus_twin"], got["cus_new"])
|
||||
}
|
||||
// The user decides.
|
||||
SetMatch(d, "cus_twin", "a4", false, now)
|
||||
SetMatch(d, "cus_free", "", false, now)
|
||||
SetMatch(d, "cus_ann", "a5", false, now)
|
||||
ms, _ = Matches(d, nil)
|
||||
for _, m := range ms {
|
||||
got[m.Customer.ID] = m
|
||||
}
|
||||
if got["cus_twin"].Account.Name != "Twin Two" || got["cus_twin"].How != MatchManual || got["cus_free"].How != MatchNotInCRM || got["cus_ann"].Account.ID != "a5" {
|
||||
t.Errorf("manual: %+v %+v %+v", got["cus_twin"], got["cus_free"], got["cus_ann"])
|
||||
}
|
||||
SetMatch(d, "cus_ann", "", true, now)
|
||||
ms, _ = Matches(d, nil)
|
||||
for _, m := range ms {
|
||||
got[m.Customer.ID] = m
|
||||
}
|
||||
if got["cus_ann"].How != MatchEmail {
|
||||
t.Errorf("back to automatic: %+v", got["cus_ann"])
|
||||
}
|
||||
if s := MatchSummary(ms); s[MatchStoredID] != 3 || s[MatchManual] != 1 || s[MatchNone] != 1 {
|
||||
t.Errorf("summary: %v", s)
|
||||
}
|
||||
if as, _ := Accounts(d); len(as) != 5 || as[0].Name != "Acme" {
|
||||
t.Errorf("accounts: %+v", as)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Exports are the tables that can be downloaded as CSV, by name.
|
||||
var Exports = []struct{ Name, Title string }{
|
||||
{"mrr", "MRR month by month"},
|
||||
{"nrr-cohorts", "NRR by cohort"},
|
||||
{"cohort-revenue", "Revenue by cohort"},
|
||||
{"cac", "CAC by month"},
|
||||
{"cac-channels", "CAC by channel (12 months)"},
|
||||
{"spend", "Spend log"},
|
||||
{"products", "Products and margins"},
|
||||
{"customers", "Customers: MRR and CRM match"},
|
||||
}
|
||||
|
||||
func dollars(cents float64) string { return strconv.FormatFloat(cents/100, 'f', 2, 64) }
|
||||
|
||||
func pct(f float64) string {
|
||||
if f < 0 {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatFloat(f, 'f', 1, 64)
|
||||
}
|
||||
|
||||
// Export writes one table as CSV, amounts in dollars.
|
||||
func Export(w io.Writer, d *db.DB, name string, now time.Time) error {
|
||||
model, err := Build(d, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cw := csv.NewWriter(w)
|
||||
defer cw.Flush()
|
||||
write := func(rows ...[]string) error {
|
||||
for _, r := range rows {
|
||||
if err := cw.Write(r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
switch name {
|
||||
case "mrr":
|
||||
write([]string{"month", "partial", "mrr", "customers", "arpa", "new", "new_customers", "expansion", "contraction", "churn",
|
||||
"churned_customers", "reactivation", "net_new", "nrr_pct", "nrr_12m_pct"})
|
||||
for _, m := range model.Months {
|
||||
if err := write([]string{m.Month, strconv.FormatBool(m.Partial), dollars(m.MRR), strconv.Itoa(m.Customers), dollars(m.ARPA()),
|
||||
dollars(m.New), strconv.Itoa(m.NewCount), dollars(m.Expansion), dollars(m.Contraction), dollars(m.Churn),
|
||||
strconv.Itoa(m.ChurnCount), dollars(m.Reactivation), dollars(m.NetNew()), pct(m.NRR), pct(m.NRR12)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "nrr-cohorts":
|
||||
head := []string{"first_paid", "customers", "starting_mrr"}
|
||||
for k := 0; k <= 24; k++ {
|
||||
head = append(head, fmt.Sprintf("month_%d_pct", k))
|
||||
}
|
||||
write(head)
|
||||
for _, c := range model.Cohorts(1000, 24) {
|
||||
row := []string{c.Month, strconv.Itoa(c.Customers), dollars(c.Start)}
|
||||
for _, r := range c.Retained {
|
||||
row = append(row, pct(r))
|
||||
}
|
||||
if err := write(row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "cohort-revenue":
|
||||
cs, err := RevenueByCohort(d, model, 1000, 24, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
head := []string{"first_paid", "customers"}
|
||||
for k := 0; k <= 24; k++ {
|
||||
head = append(head, fmt.Sprintf("month_%d_revenue_per_customer", k))
|
||||
}
|
||||
write(head)
|
||||
for _, c := range cs {
|
||||
row := []string{c.Month, strconv.Itoa(c.Customers)}
|
||||
for _, v := range c.PerCustomer {
|
||||
if v.Known {
|
||||
row = append(row, dollars(v.V))
|
||||
} else {
|
||||
row = append(row, "")
|
||||
}
|
||||
}
|
||||
if err := write(row); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "cac", "cac-channels":
|
||||
names, err := CustomerNames(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c, err := BuildCAC(d, model, names)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amount := func(f float64) string {
|
||||
if f < 0 {
|
||||
return ""
|
||||
}
|
||||
return dollars(f)
|
||||
}
|
||||
if name == "cac" {
|
||||
write([]string{"month", "spend", "new_customers", "cac", "cac_3_months"})
|
||||
months := slices.Clone(c.Months)
|
||||
slices.Reverse(months)
|
||||
for _, m := range months {
|
||||
if err := write([]string{m.Month, dollars(float64(m.Spend)), strconv.Itoa(m.New), amount(m.CAC), amount(m.Trailing3)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
write([]string{"channel", "spend", "new_customers", "cac"})
|
||||
for _, ch := range c.Channels {
|
||||
if err := write([]string{ChannelName(ch.Channel), dollars(float64(ch.Spend)), strconv.Itoa(ch.New), amount(ch.CAC)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "spend":
|
||||
log, err := SpendLog(d, 100000)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write([]string{"month", "channel", "amount", "note", "source"})
|
||||
for _, s := range log {
|
||||
if err := write([]string{s.Month, s.Channel, dollars(float64(s.AmountCents)), s.Note, s.Source}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "products":
|
||||
ps, err := Products(d, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write([]string{"product_id", "name", "billed_12_months", "invoices", "margin_pct", "own_margin"})
|
||||
for _, p := range ps {
|
||||
if err := write([]string{p.ID, p.Name, dollars(float64(p.Revenue)), strconv.Itoa(p.Invoices), pct(p.Margin), strconv.FormatBool(p.Own)}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "customers":
|
||||
ms, err := Matches(d, model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write([]string{"customer_id", "name", "email", "mrr_now", "first_paid", "crm_account_id", "crm_account", "matched_by"})
|
||||
for _, m := range ms {
|
||||
if err := write([]string{m.Customer.ID, m.Customer.Name, m.Customer.Email, dollars(m.MRR), model.First[m.Customer.ID],
|
||||
m.Account.ID, m.Account.Name, m.How}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("no table %q", name)
|
||||
}
|
||||
return cw.Error()
|
||||
}
|
||||
|
||||
// PublicParts are what an open metrics page can show; nothing about any
|
||||
// one customer is ever published.
|
||||
var PublicParts = []struct{ ID, Label string }{
|
||||
{"mrr", "MRR and ARR"},
|
||||
{"customers", "Paying customers and the average per customer"},
|
||||
{"growth", "Growth over 12 months"},
|
||||
{"nrr", "Net revenue retention (12 months)"},
|
||||
{"churn", "Monthly customer churn"},
|
||||
{"table", "A month-by-month table (MRR, customers, net change), last 12 months"},
|
||||
}
|
||||
|
||||
// PublicPage is the Markdown body of an open metrics page: totals only.
|
||||
func PublicPage(m *Model, clv *CLV, parts map[string]bool, now time.Time) string {
|
||||
months := m.Months
|
||||
if len(months) > 0 && months[len(months)-1].Partial {
|
||||
months = months[:len(months)-1]
|
||||
}
|
||||
if len(months) == 0 {
|
||||
return ""
|
||||
}
|
||||
last := months[len(months)-1]
|
||||
money := func(cents float64) string {
|
||||
s := strconv.FormatFloat(cents/100, 'f', 0, 64)
|
||||
for i := len(s) - 3; i > 0; i -= 3 {
|
||||
s = s[:i] + "," + s[i:]
|
||||
}
|
||||
return "$" + s
|
||||
}
|
||||
var b []string
|
||||
b = append(b, fmt.Sprintf("Our numbers at the end of %s, straight from our billing.", monthName(last.Month)), "")
|
||||
if parts["mrr"] {
|
||||
b = append(b, fmt.Sprintf("- **Monthly recurring revenue:** %s (%s a year)", money(last.MRR), money(12*last.MRR)))
|
||||
}
|
||||
if parts["customers"] {
|
||||
b = append(b, fmt.Sprintf("- **Paying customers:** %d, at %s a month on average", last.Customers, money(last.ARPA())))
|
||||
}
|
||||
if parts["growth"] && len(months) > 12 {
|
||||
if base := months[len(months)-13].MRR; base > 0 {
|
||||
b = append(b, fmt.Sprintf("- **Growth over 12 months:** %+.0f%%", 100*(last.MRR-base)/base))
|
||||
}
|
||||
}
|
||||
if parts["nrr"] && last.NRR12 >= 0 {
|
||||
b = append(b, fmt.Sprintf("- **Net revenue retention, 12 months:** %.0f%% (what customers of a year ago pay now)", last.NRR12))
|
||||
}
|
||||
if parts["churn"] && clv != nil && clv.ChurnMonths > 0 {
|
||||
b = append(b, fmt.Sprintf("- **Monthly customer churn:** %.1f%%, averaged over %d months", clv.Churn, clv.ChurnMonths))
|
||||
}
|
||||
if parts["table"] {
|
||||
b = append(b, "", "| Month | MRR | Customers | Net change |", "|---|---:|---:|---:|")
|
||||
from := max(0, len(months)-12)
|
||||
for i := len(months) - 1; i >= from; i-- {
|
||||
mo := months[i]
|
||||
sign := ""
|
||||
if mo.NetNew() > 0 {
|
||||
sign = "+"
|
||||
}
|
||||
b = append(b, fmt.Sprintf("| %s | %s | %d | %s%s |", monthName(mo.Month), money(mo.MRR), mo.Customers, sign, money(mo.NetNew())))
|
||||
}
|
||||
}
|
||||
b = append(b, "", fmt.Sprintf("*Updated %s. MRR counts recurring billing after discounts; trials, one-off charges and unpaid invoices don't count.*", now.Format("2 January 2006")))
|
||||
return joinLines(b)
|
||||
}
|
||||
|
||||
func monthName(ym string) string {
|
||||
t, err := time.Parse("2006-01", ym)
|
||||
if err != nil {
|
||||
return ym
|
||||
}
|
||||
return t.Format("January 2006")
|
||||
}
|
||||
|
||||
func joinLines(lines []string) string {
|
||||
out := ""
|
||||
for _, l := range lines {
|
||||
out += l + "\n"
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExportsAndPublicPage(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2027, 2, 15, 0, 0, 0, 0, time.UTC)
|
||||
addLines(t, d, monthly("cus_a", 10000, "2026-01", "2027-03")...)
|
||||
addLines(t, d, monthly("cus_b", 5000, "2026-06", "2027-03")...)
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', 'cus_a', 'cus_a', '{"name":"Secret Co","email":"ceo@secret.example"}')`)
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'pa', 'cus_a', 'paid', 'usd', '{"amount_paid":10000}')`)
|
||||
AddSpend(d, Spend{Month: "2026-06", Channel: "linkedin", AmountCents: 50000}, now)
|
||||
for _, e := range Exports {
|
||||
var buf bytes.Buffer
|
||||
if err := Export(&buf, d, e.Name, now); err != nil {
|
||||
t.Errorf("%s: %v", e.Name, err)
|
||||
continue
|
||||
}
|
||||
rows, err := csv.NewReader(&buf).ReadAll()
|
||||
if err != nil || len(rows) < 2 {
|
||||
t.Errorf("%s: %d rows %v", e.Name, len(rows), err)
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
Export(&buf, d, "mrr", now)
|
||||
if !strings.Contains(buf.String(), "2026-06,false,150.00,2,75.00,50.00,1,") {
|
||||
t.Errorf("mrr csv:\n%s", buf.String())
|
||||
}
|
||||
buf.Reset()
|
||||
Export(&buf, d, "customers", now)
|
||||
if !strings.Contains(buf.String(), "cus_a,Secret Co,ceo@secret.example,100.00,2026-01") {
|
||||
t.Errorf("customers csv:\n%s", buf.String())
|
||||
}
|
||||
if err := Export(&buf, d, "nope", now); err == nil {
|
||||
t.Error("an unknown table exported")
|
||||
}
|
||||
|
||||
m, _ := Build(d, now)
|
||||
clv, _ := BuildCLV(d, m, now)
|
||||
page := PublicPage(m, clv, map[string]bool{"mrr": true, "customers": true, "growth": true, "nrr": true, "churn": true, "table": true}, now)
|
||||
for _, want := range []string{"end of January 2027", "**Monthly recurring revenue:** $150 ($1,800 a year)", "**Paying customers:** 2",
|
||||
"**Growth over 12 months:** +50%", "| January 2027 | $150 | 2 |", "| June 2026 | $150 | 2 | +$50 |"} {
|
||||
if !strings.Contains(page, want) {
|
||||
t.Errorf("page lacks %q:\n%s", want, page)
|
||||
}
|
||||
}
|
||||
for _, never := range []string{"Secret", "secret.example", "cus_"} {
|
||||
if strings.Contains(page, never) {
|
||||
t.Errorf("the public page names a customer: %q", never)
|
||||
}
|
||||
}
|
||||
if p := PublicPage(m, clv, map[string]bool{"mrr": true}, now); strings.Contains(p, "|") || strings.Contains(p, "customers") {
|
||||
t.Errorf("unchosen parts shown:\n%s", p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// DefaultMargin is the gross margin used for products without their own,
|
||||
// in percent (the user's figure, 2026-11-22).
|
||||
const DefaultMargin = 60.0
|
||||
|
||||
// Margins are the gross margins, in percent: a default, and per product.
|
||||
type Margins struct {
|
||||
Default float64 `json:"default"`
|
||||
ByProduct map[string]float64 `json:"by_product"`
|
||||
}
|
||||
|
||||
const marginsKey = "metrics:margins"
|
||||
|
||||
// LoadMargins returns the saved margins, or the default for everything.
|
||||
func LoadMargins(d *db.DB) Margins {
|
||||
m := Margins{Default: DefaultMargin, ByProduct: map[string]float64{}}
|
||||
if ok, err := d.GetJSON(marginsKey, &m); err != nil || !ok {
|
||||
return Margins{Default: DefaultMargin, ByProduct: map[string]float64{}}
|
||||
}
|
||||
if m.ByProduct == nil {
|
||||
m.ByProduct = map[string]float64{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// SaveMargins stores the margins, after checking they're percentages.
|
||||
func SaveMargins(d *db.DB, m Margins) error {
|
||||
if m.Default < 0 || m.Default > 100 {
|
||||
return fmt.Errorf("a margin must be between 0 and 100%%")
|
||||
}
|
||||
for p, v := range m.ByProduct {
|
||||
if v < 0 || v > 100 {
|
||||
return fmt.Errorf("%s's margin must be between 0 and 100%%", p)
|
||||
}
|
||||
}
|
||||
return d.PutJSON(marginsKey, m)
|
||||
}
|
||||
|
||||
// For is a product's margin: its own, or the default.
|
||||
func (m Margins) For(product string) float64 {
|
||||
if v, ok := m.ByProduct[product]; ok {
|
||||
return v
|
||||
}
|
||||
return m.Default
|
||||
}
|
||||
|
||||
// Product is a product with what it brought in.
|
||||
type Product struct {
|
||||
ID string
|
||||
Name string
|
||||
Revenue int64 // the last 12 months' billed amount, after discounts, in cents
|
||||
Invoices int
|
||||
Margin float64
|
||||
Own bool // has its own margin
|
||||
}
|
||||
|
||||
var (
|
||||
quantityPrefix = regexp.MustCompile(`^\d+\s*[×x]\s*`)
|
||||
pricedSuffix = regexp.MustCompile(`\s*\((at|Tier).*\)$`)
|
||||
timeOnPrefix = regexp.MustCompile(`^(Unused|Remaining) time on\s+`)
|
||||
)
|
||||
|
||||
// nameFromLine reads a product's name from an invoice line's description:
|
||||
// "1 × Federated Core (at $49.00 / month)" → "Federated Core".
|
||||
func nameFromLine(desc string) string {
|
||||
desc = timeOnPrefix.ReplaceAllString(strings.TrimSpace(desc), "")
|
||||
desc = quantityPrefix.ReplaceAllString(desc, "")
|
||||
desc = pricedSuffix.ReplaceAllString(desc, "")
|
||||
if i := strings.Index(desc, " after "); i > 0 {
|
||||
desc = desc[:i]
|
||||
}
|
||||
return strings.TrimSpace(desc)
|
||||
}
|
||||
|
||||
// Products lists the products billed, with the last 12 months' revenue and
|
||||
// their margins, biggest first.
|
||||
func Products(d *db.DB, now time.Time) ([]Product, error) {
|
||||
names := map[string]string{}
|
||||
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ?`, KindProduct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, raw string
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
var p struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
names[id] = p.Name
|
||||
}
|
||||
rows.Close()
|
||||
m := LoadMargins(d) // before the next query: the database has one connection
|
||||
since := now.AddDate(-1, 0, 0).Unix()
|
||||
rows, err = d.Query(`SELECT product, coalesce(sum(CASE WHEN period_start >= ? THEN amount ELSE 0 END), 0), count(DISTINCT invoice),
|
||||
(SELECT description FROM stripe_invoice_lines l2 WHERE l2.product = l.product AND description != '' ORDER BY period_start DESC LIMIT 1)
|
||||
FROM stripe_invoice_lines l WHERE status IN ('paid', 'open') GROUP BY product`, since)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Product
|
||||
for rows.Next() {
|
||||
var p Product
|
||||
var desc *string
|
||||
if err := rows.Scan(&p.ID, &p.Revenue, &p.Invoices, &desc); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
p.Name = names[p.ID]
|
||||
if p.Name == "" && desc != nil {
|
||||
p.Name = nameFromLine(*desc)
|
||||
}
|
||||
if p.Name == "" {
|
||||
p.Name = or(p.ID, "(no product: one-off charges)")
|
||||
}
|
||||
_, p.Own = m.ByProduct[p.ID]
|
||||
p.Margin = m.For(p.ID)
|
||||
out = append(out, p)
|
||||
}
|
||||
rows.Close()
|
||||
slices.SortStableFunc(out, func(a, b Product) int {
|
||||
switch {
|
||||
case a.Revenue > b.Revenue:
|
||||
return -1
|
||||
case a.Revenue < b.Revenue:
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a.Name, b.Name)
|
||||
})
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// WeightedMargin is a set of lines' margin, weighted by revenue: what a
|
||||
// customer (or the business) keeps of each dollar.
|
||||
func WeightedMargin(m Margins, revenueByProduct map[string]int64) float64 {
|
||||
var total, kept float64
|
||||
for p, r := range revenueByProduct {
|
||||
total += float64(r)
|
||||
kept += float64(r) * m.For(p)
|
||||
}
|
||||
if total == 0 {
|
||||
return m.Default
|
||||
}
|
||||
return kept / total
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNameFromLine(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"1 × Federated Core (at $49.00 / month)": "Federated Core",
|
||||
"3 x Seats (Tier 1 at $10.00 / month)": "Seats",
|
||||
"Unused time on Federated Core after 12 Nov 2026": "Federated Core",
|
||||
"Remaining time on 2 × Federated Core after 12 Nov 2026": "Federated Core",
|
||||
"Setup fee": "Setup fee",
|
||||
} {
|
||||
if got := nameFromLine(in); got != want {
|
||||
t.Errorf("%q: %q", in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductsAndMargins(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC)
|
||||
recent, old := now.AddDate(0, -2, 0).Unix(), now.AddDate(-2, 0, 0).Unix()
|
||||
for _, l := range []struct {
|
||||
inv, id, product, desc, status string
|
||||
amount, start int64
|
||||
}{
|
||||
{"in_1", "il_1", "prod_core", "1 × Federated Core (at $49.00 / month)", "paid", 4900, recent},
|
||||
{"in_2", "il_2", "prod_core", "1 × Federated Core (at $49.00 / month)", "paid", 4900, old},
|
||||
{"in_3", "il_3", "prod_ai", "1 × Superbrain (at $20.00 / month)", "open", 2000, recent},
|
||||
{"in_4", "il_4", "prod_ai", "1 × Superbrain (at $20.00 / month)", "void", 2000, recent},
|
||||
{"in_5", "il_5", "", "Setup fee", "paid", 10000, recent},
|
||||
} {
|
||||
d.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, product, description)
|
||||
VALUES (?, ?, 'cus_a', ?, 'usd', ?, ?, ?, ?, ?)`, l.inv, l.id, l.status, l.amount, l.start, l.start+2592000, l.product, l.desc)
|
||||
}
|
||||
d.Exec(`INSERT INTO stripe_objects (kind, id, data) VALUES ('product', 'prod_ai', '{"id":"prod_ai","name":"Superbrain AI"}')`)
|
||||
|
||||
ps, err := Products(d, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ps) != 3 || ps[0].ID != "" || ps[0].Revenue != 10000 || ps[1].Name != "Federated Core" || ps[1].Revenue != 4900 || ps[1].Invoices != 2 ||
|
||||
ps[2].Name != "Superbrain AI" || ps[2].Revenue != 2000 || ps[2].Margin != 60 {
|
||||
t.Fatalf("products: %+v", ps)
|
||||
}
|
||||
if err := SaveMargins(d, Margins{Default: 60, ByProduct: map[string]float64{"prod_ai": 30}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveMargins(d, Margins{Default: 120}); err == nil {
|
||||
t.Error("saved a margin over 100%")
|
||||
}
|
||||
m := LoadMargins(d)
|
||||
if m.For("prod_ai") != 30 || m.For("prod_core") != 60 {
|
||||
t.Errorf("margins: %+v", m)
|
||||
}
|
||||
// $49 at 60% and $20 at 30%: (29.4 + 6) / 69 = 51.3%.
|
||||
if w := WeightedMargin(m, map[string]int64{"prod_core": 4900, "prod_ai": 2000}); w < 51.3 || w > 51.31 {
|
||||
t.Errorf("weighted: %v", w)
|
||||
}
|
||||
if ps, _ := Products(d, now); !ps[2].Own || ps[2].Margin != 30 {
|
||||
t.Errorf("own margin: %+v", ps[2])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// line is an invoice line, as the MRR model needs it.
|
||||
type line struct {
|
||||
customer string
|
||||
amount int64
|
||||
start, end int64
|
||||
interval string
|
||||
intervalCount int
|
||||
proration bool
|
||||
product string
|
||||
}
|
||||
|
||||
const avgMonthSeconds = 365.25 / 12 * 24 * 3600
|
||||
|
||||
// monthly is a line's contribution to MRR, in cents: its amount spread over
|
||||
// its billing interval, or, for a proration, over the part period it
|
||||
// covers.
|
||||
func (l line) monthly() float64 {
|
||||
if !l.proration {
|
||||
n := float64(max(l.intervalCount, 1))
|
||||
switch l.interval {
|
||||
case "month":
|
||||
return float64(l.amount) / n
|
||||
case "year":
|
||||
return float64(l.amount) / (12 * n)
|
||||
case "week":
|
||||
return float64(l.amount) * 52 / 12 / n
|
||||
case "day":
|
||||
return float64(l.amount) * 365 / 12 / n
|
||||
}
|
||||
}
|
||||
months := float64(l.end-l.start) / avgMonthSeconds
|
||||
if months <= 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(l.amount) / months
|
||||
}
|
||||
|
||||
// loadLines reads the recurring lines of billed invoices (paid or open; not
|
||||
// void, not uncollectible) in the main currency.
|
||||
func loadLines(d *db.DB, currency string) ([]line, error) {
|
||||
rows, err := d.Query(`SELECT customer, amount, period_start, period_end, interval, interval_count, proration, product
|
||||
FROM stripe_invoice_lines WHERE recurring = 1 AND status IN ('paid', 'open') AND currency = ? AND customer != ''
|
||||
AND period_end > period_start`, currency)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []line
|
||||
for rows.Next() {
|
||||
var l line
|
||||
if err := rows.Scan(&l.customer, &l.amount, &l.start, &l.end, &l.interval, &l.intervalCount, &l.proration, &l.product); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, l)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MainCurrency is the currency most invoices are in, or "".
|
||||
func MainCurrency(d *db.DB) string {
|
||||
cs, _ := currencies(d)
|
||||
if len(cs) == 0 {
|
||||
return ""
|
||||
}
|
||||
return cs[0]
|
||||
}
|
||||
|
||||
// Movement kinds.
|
||||
const (
|
||||
MoveNew = "new"
|
||||
MoveExpansion = "expansion"
|
||||
MoveContraction = "contraction"
|
||||
MoveChurn = "churn"
|
||||
MoveReactivation = "reactivation"
|
||||
)
|
||||
|
||||
// Month is one month's MRR and how it moved since the month before. Amounts
|
||||
// are in cents.
|
||||
type Month struct {
|
||||
Month string // YYYY-MM
|
||||
At time.Time
|
||||
Partial bool // the current month, measured now
|
||||
MRR float64
|
||||
Customers int
|
||||
New float64
|
||||
Expansion float64
|
||||
Contraction float64 // positive: the MRR lost
|
||||
Churn float64 // positive
|
||||
Reactivation float64
|
||||
NewCount, ChurnCount int
|
||||
NRR float64 // this month: kept MRR of last month's customers ÷ last month's MRR; -1 if none
|
||||
NRR12 float64 // trailing 12 months: the customers paying 12 months ago, now; -1 if not enough history
|
||||
// By customer, for the month's detail.
|
||||
ByCustomer map[string]float64
|
||||
Moves map[string]string // customer → movement kind
|
||||
}
|
||||
|
||||
// ARPA is the average MRR per paying customer.
|
||||
func (m Month) ARPA() float64 {
|
||||
if m.Customers == 0 {
|
||||
return 0
|
||||
}
|
||||
return m.MRR / float64(m.Customers)
|
||||
}
|
||||
|
||||
// NetNew is the month's change in MRR.
|
||||
func (m Month) NetNew() float64 {
|
||||
return m.New + m.Expansion + m.Reactivation - m.Contraction - m.Churn
|
||||
}
|
||||
|
||||
// Model is the MRR over time.
|
||||
type Model struct {
|
||||
Currency string
|
||||
Months []Month // oldest first, from Start
|
||||
First map[string]string // customer → the month they first paid (from Start)
|
||||
Start string // the first month counted ("" for all)
|
||||
Suggest *Suggestion // a start month worth considering, when none is set
|
||||
}
|
||||
|
||||
// Suggestion is a month where most of the business appears at once, which
|
||||
// usually means billing moved to Stripe then: counting from it keeps those
|
||||
// customers from looking new.
|
||||
type Suggestion struct {
|
||||
Month string
|
||||
Customers int
|
||||
MRR float64
|
||||
}
|
||||
|
||||
const startKey = "metrics:start"
|
||||
|
||||
// StartMonth is the month the metrics count from, or "".
|
||||
func StartMonth(d *db.DB) string {
|
||||
var s string
|
||||
_, _ = d.GetJSON(startKey, &s)
|
||||
return s
|
||||
}
|
||||
|
||||
// SetStartMonth sets it ("" counts everything).
|
||||
func SetStartMonth(d *db.DB, month string) error {
|
||||
if month != "" {
|
||||
if _, err := time.Parse("2006-01", month); err != nil {
|
||||
return fmt.Errorf("%q isn't a month (YYYY-MM)", month)
|
||||
}
|
||||
}
|
||||
return d.PutJSON(startKey, month)
|
||||
}
|
||||
|
||||
// mrrAt is each customer's MRR at an instant: the lines whose period
|
||||
// covers it.
|
||||
func mrrAt(lines []line, t int64) map[string]float64 {
|
||||
out := map[string]float64{}
|
||||
for _, l := range lines {
|
||||
if l.start <= t && t < l.end {
|
||||
out[l.customer] += l.monthly()
|
||||
}
|
||||
}
|
||||
for c, v := range out {
|
||||
if v < 0.5 { // less than a cent: a trial, or credits that cancel out
|
||||
delete(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Build works out MRR month by month, from the first billed month to now
|
||||
// (the current month measured now, the others at their last second).
|
||||
func Build(d *db.DB, now time.Time) (*Model, error) {
|
||||
cur := MainCurrency(d)
|
||||
m := &Model{Currency: cur, First: map[string]string{}, Start: StartMonth(d)}
|
||||
if cur == "" {
|
||||
return m, nil
|
||||
}
|
||||
lines, err := loadLines(d, cur)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
return m, nil
|
||||
}
|
||||
first := lines[0].start
|
||||
for _, l := range lines {
|
||||
first = min(first, l.start)
|
||||
}
|
||||
now = now.UTC()
|
||||
month := time.Unix(first, 0).UTC()
|
||||
month = time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
if s, err := time.Parse("2006-01", m.Start); err == nil && s.After(month) {
|
||||
month = s
|
||||
}
|
||||
startMonth := month.Format("2006-01")
|
||||
var prev map[string]float64
|
||||
ever := map[string]bool{}
|
||||
for !month.After(now) {
|
||||
next := month.AddDate(0, 1, 0)
|
||||
at, partial := next.Add(-time.Second), false
|
||||
if at.After(now) {
|
||||
at, partial = now, true
|
||||
}
|
||||
by := mrrAt(lines, at.Unix())
|
||||
mo := Month{Month: month.Format("2006-01"), At: at, Partial: partial, ByCustomer: by, Moves: map[string]string{}, NRR: -1, NRR12: -1}
|
||||
for c, v := range by {
|
||||
mo.MRR += v
|
||||
mo.Customers++
|
||||
p := prev[c]
|
||||
switch {
|
||||
case mo.Month == startMonth && m.Start != "":
|
||||
// Already paying when the count starts: the base, not new.
|
||||
m.First[c] = mo.Month
|
||||
case p == 0 && !ever[c]:
|
||||
mo.New += v
|
||||
mo.NewCount++
|
||||
mo.Moves[c] = MoveNew
|
||||
m.First[c] = mo.Month
|
||||
case p == 0:
|
||||
mo.Reactivation += v
|
||||
mo.Moves[c] = MoveReactivation
|
||||
case v > p+noise(p):
|
||||
mo.Expansion += v - p
|
||||
mo.Moves[c] = MoveExpansion
|
||||
case v < p-noise(p):
|
||||
mo.Contraction += p - v
|
||||
mo.Moves[c] = MoveContraction
|
||||
}
|
||||
ever[c] = true
|
||||
}
|
||||
for c, p := range prev {
|
||||
if _, still := by[c]; !still {
|
||||
mo.Churn += p
|
||||
mo.ChurnCount++
|
||||
mo.Moves[c] = MoveChurn
|
||||
}
|
||||
}
|
||||
if prevTotal := sum(prev); prevTotal > 0 {
|
||||
kept := 0.0
|
||||
for c := range prev {
|
||||
kept += by[c] // what last month's customers pay now (0 if they left)
|
||||
}
|
||||
mo.NRR = 100 * kept / prevTotal
|
||||
}
|
||||
m.Months = append(m.Months, mo)
|
||||
prev = by
|
||||
month = next
|
||||
}
|
||||
if m.Start == "" {
|
||||
m.Suggest = suggest(m.Months)
|
||||
}
|
||||
// Trailing 12 months: the customers paying 12 months before, now.
|
||||
for i := 12; i < len(m.Months); i++ {
|
||||
base := m.Months[i-12].ByCustomer
|
||||
if total := sum(base); total > 0 {
|
||||
kept := 0.0
|
||||
for c := range base {
|
||||
kept += m.Months[i].ByCustomer[c]
|
||||
}
|
||||
m.Months[i].NRR12 = 100 * kept / total
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func sum(m map[string]float64) float64 {
|
||||
t := 0.0
|
||||
for _, v := range m {
|
||||
t += v
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Last is the latest month, or nil.
|
||||
func (m *Model) Last() *Month {
|
||||
if len(m.Months) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &m.Months[len(m.Months)-1]
|
||||
}
|
||||
|
||||
// Find is a month by its YYYY-MM, or nil.
|
||||
func (m *Model) Find(month string) *Month {
|
||||
for i := range m.Months {
|
||||
if m.Months[i].Month == month {
|
||||
return &m.Months[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Recent are the last n months, newest first.
|
||||
func (m *Model) Recent(n int) []Month {
|
||||
out := slices.Clone(m.Months)
|
||||
slices.Reverse(out)
|
||||
if len(out) > n {
|
||||
out = out[:n]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Cohort is the customers who first paid in one month, and the share of
|
||||
// their starting MRR they pay in each month after (net revenue retention by
|
||||
// cohort).
|
||||
type Cohort struct {
|
||||
Month string
|
||||
Customers int
|
||||
Start float64 // their MRR in their first month
|
||||
Retained []float64 // percent of Start, for month 0, 1, 2…; -1 beyond today
|
||||
}
|
||||
|
||||
// Cohorts are the last n signup cohorts, newest first, each followed for up
|
||||
// to span months.
|
||||
func (m *Model) Cohorts(n, span int) []Cohort {
|
||||
idx := map[string]int{}
|
||||
for i, mo := range m.Months {
|
||||
idx[mo.Month] = i
|
||||
}
|
||||
members := map[string][]string{}
|
||||
for c, first := range m.First {
|
||||
members[first] = append(members[first], c)
|
||||
}
|
||||
var out []Cohort
|
||||
for i := len(m.Months) - 1; i >= 0 && len(out) < n; i-- {
|
||||
mo := m.Months[i]
|
||||
cs := members[mo.Month]
|
||||
if len(cs) == 0 {
|
||||
continue
|
||||
}
|
||||
co := Cohort{Month: mo.Month, Customers: len(cs)}
|
||||
for _, c := range cs {
|
||||
co.Start += mo.ByCustomer[c]
|
||||
}
|
||||
for k := 0; k <= span; k++ {
|
||||
if i+k >= len(m.Months) || co.Start == 0 {
|
||||
co.Retained = append(co.Retained, -1)
|
||||
continue
|
||||
}
|
||||
kept := 0.0
|
||||
for _, c := range cs {
|
||||
kept += m.Months[i+k].ByCustomer[c]
|
||||
}
|
||||
co.Retained = append(co.Retained, 100*kept/co.Start)
|
||||
}
|
||||
out = append(out, co)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// suggest finds a month, after the first, where at least 20 customers and
|
||||
// most of the MRR appear as new at once.
|
||||
func suggest(months []Month) *Suggestion {
|
||||
for i := 1; i < len(months); i++ {
|
||||
mo := months[i]
|
||||
if mo.NewCount >= 20 && mo.New >= 0.5*mo.MRR {
|
||||
return &Suggestion{Month: mo.Month, Customers: mo.NewCount, MRR: mo.New}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Customer is a Stripe customer's name and email.
|
||||
type Customer struct {
|
||||
ID, Name, Email string
|
||||
}
|
||||
|
||||
// CustomerNames reads the names and emails of the customers stored.
|
||||
func CustomerNames(d *db.DB) (map[string]Customer, error) {
|
||||
rows, err := d.Query(`SELECT id, data FROM stripe_objects WHERE kind = ?`, KindCustomer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]Customer{}
|
||||
for rows.Next() {
|
||||
var id, raw string
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &c)
|
||||
out[id] = Customer{ID: id, Name: c.Name, Email: c.Email}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Change is one customer's move in a month.
|
||||
type Change struct {
|
||||
Customer Customer
|
||||
Kind string
|
||||
Before, After float64
|
||||
}
|
||||
|
||||
// Changes are a month's moves, biggest first.
|
||||
func (m *Model) Changes(month string, names map[string]Customer) []Change {
|
||||
i := -1
|
||||
for j := range m.Months {
|
||||
if m.Months[j].Month == month {
|
||||
i = j
|
||||
}
|
||||
}
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
var prev map[string]float64
|
||||
if i > 0 {
|
||||
prev = m.Months[i-1].ByCustomer
|
||||
}
|
||||
mo := m.Months[i]
|
||||
var out []Change
|
||||
for c, k := range mo.Moves {
|
||||
cu := names[c]
|
||||
if cu.ID == "" {
|
||||
cu.ID = c
|
||||
}
|
||||
out = append(out, Change{Customer: cu, Kind: k, Before: prev[c], After: mo.ByCustomer[c]})
|
||||
}
|
||||
slices.SortFunc(out, func(a, b Change) int {
|
||||
da, db := a.After-a.Before, b.After-b.Before
|
||||
if da < 0 {
|
||||
da = -da
|
||||
}
|
||||
if db < 0 {
|
||||
db = -db
|
||||
}
|
||||
switch {
|
||||
case da > db:
|
||||
return -1
|
||||
case da < db:
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// noise is the change in a customer's MRR too small to be a real move: a
|
||||
// dollar, or 1%. Spreading prorations over exact part-months leaves cents
|
||||
// of difference that aren't an upgrade or a downgrade.
|
||||
func noise(mrr float64) float64 { return max(100, mrr/100) }
|
||||
@@ -0,0 +1,152 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
func day(s string) int64 {
|
||||
t, _ := time.Parse("2006-01-02", s)
|
||||
return t.Unix()
|
||||
}
|
||||
|
||||
type ln struct {
|
||||
cust, from, to, interval string
|
||||
amount int64
|
||||
proration bool
|
||||
status string
|
||||
}
|
||||
|
||||
var lineN int
|
||||
|
||||
func addLines(t *testing.T, d *db.DB, ls ...ln) {
|
||||
t.Helper()
|
||||
for _, l := range ls {
|
||||
lineN++
|
||||
status := l.status
|
||||
if status == "" {
|
||||
status = "paid"
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end,
|
||||
interval, interval_count, proration, recurring) VALUES (?, ?, ?, ?, 'usd', ?, ?, ?, ?, 1, ?, 1)`,
|
||||
fmt.Sprintf("in_%d", lineN), fmt.Sprintf("il_%d", lineN), l.cust, status, l.amount, day(l.from), day(l.to), l.interval, l.proration); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
d.Exec(`INSERT OR IGNORE INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_x', 'usd', '{}')`)
|
||||
}
|
||||
|
||||
// monthly bills a customer $amount a month on the 10th, from one month to
|
||||
// another (exclusive).
|
||||
func monthly(cust string, amount int64, from, to string) []ln {
|
||||
var out []ln
|
||||
start, _ := time.Parse("2006-01-02", from+"-10")
|
||||
end, _ := time.Parse("2006-01-02", to+"-10")
|
||||
for s := start; s.Before(end); s = s.AddDate(0, 1, 0) {
|
||||
out = append(out, ln{cust: cust, from: s.Format("2006-01-02"), to: s.AddDate(0, 1, 0).Format("2006-01-02"), interval: "month", amount: amount})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func near(a, b float64) bool { return math.Abs(a-b) < 1 }
|
||||
|
||||
func TestBuild(t *testing.T) {
|
||||
d := openDB(t)
|
||||
addLines(t, d, monthly("cus_a", 5000, "2026-01", "2026-07")...) // $50 Jan–Jun
|
||||
addLines(t, d, monthly("cus_b", 2000, "2026-02", "2026-04")...) // $20 Feb–Mar, then gone
|
||||
addLines(t, d, monthly("cus_b", 2000, "2026-05", "2026-07")...) // back in May
|
||||
// cus_c pays $1,200 a year from March: $100 a month.
|
||||
addLines(t, d, ln{cust: "cus_c", from: "2026-03-15", to: "2027-03-15", interval: "year", amount: 120000})
|
||||
// cus_a upgrades on 25 April: credit for unused $50 time, charge for $80
|
||||
// time, to 10 May; then $80 a month.
|
||||
addLines(t, d,
|
||||
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: -2500, proration: true},
|
||||
ln{cust: "cus_a", from: "2026-04-25", to: "2026-05-10", amount: 4000, proration: true})
|
||||
d.Exec(`UPDATE stripe_invoice_lines SET amount = 8000 WHERE customer = 'cus_a' AND period_start >= ?`, day("2026-05-10"))
|
||||
// A trial, a void invoice and an uncollectible one count for nothing.
|
||||
addLines(t, d, ln{cust: "cus_t", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 0},
|
||||
ln{cust: "cus_v", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "void"},
|
||||
ln{cust: "cus_u", from: "2026-03-01", to: "2026-04-01", interval: "month", amount: 9900, status: "uncollectible"})
|
||||
|
||||
m, err := Build(d, time.Date(2026, 6, 20, 12, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Currency != "usd" || len(m.Months) != 6 || m.Months[0].Month != "2026-01" || !m.Last().Partial {
|
||||
t.Fatalf("months: %d %+v", len(m.Months), m.Months[0])
|
||||
}
|
||||
want := map[string]struct {
|
||||
mrr float64
|
||||
cust int
|
||||
}{
|
||||
"2026-01": {5000, 1}, "2026-02": {7000, 2}, "2026-03": {17000, 3},
|
||||
// April: cus_a's proration covers 25 April–10 May: +$15 over half a
|
||||
// month, about $30 a month on top of $50.
|
||||
"2026-04": {15000 + 3044, 2}, "2026-05": {20000, 3}, "2026-06": {20000, 3},
|
||||
}
|
||||
for _, mo := range m.Months {
|
||||
w := want[mo.Month]
|
||||
if !near(mo.MRR, w.mrr) || mo.Customers != w.cust {
|
||||
t.Errorf("%s: MRR %.0f with %d, want %.0f with %d", mo.Month, mo.MRR, mo.Customers, w.mrr, w.cust)
|
||||
}
|
||||
}
|
||||
apr, may := m.Find("2026-04"), m.Find("2026-05")
|
||||
if !near(apr.Churn, 2000) || apr.ChurnCount != 1 || apr.Moves["cus_b"] != MoveChurn || apr.Moves["cus_a"] != MoveExpansion {
|
||||
t.Errorf("april: %+v", apr.Moves)
|
||||
}
|
||||
if !near(may.Reactivation, 2000) || may.Moves["cus_b"] != MoveReactivation || may.Moves["cus_a"] != "" { // the upgrade counted in April
|
||||
t.Errorf("may: %+v %v", may.Moves, may.Reactivation)
|
||||
}
|
||||
if mar := m.Find("2026-03"); !near(mar.New, 10000) || mar.NewCount != 1 {
|
||||
t.Errorf("march new: %+v", mar)
|
||||
}
|
||||
// April's NRR: March's customers (a, b, c: $170) pay $180.44 in April.
|
||||
if !near(apr.NRR*170, 18044) {
|
||||
t.Errorf("april NRR: %v", apr.NRR)
|
||||
}
|
||||
if apr.NRR12 != -1 {
|
||||
t.Error("NRR over 12 months without a year of data")
|
||||
}
|
||||
if n := apr.NetNew(); !near(n, apr.MRR-m.Find("2026-03").MRR) {
|
||||
t.Errorf("net new %v doesn't add up", n)
|
||||
}
|
||||
cos := m.Cohorts(12, 3)
|
||||
if len(cos) != 3 || cos[0].Month != "2026-03" || cos[2].Month != "2026-01" || cos[2].Retained[0] != 100 || !near(cos[2].Retained[3], 100*(5000+3044)/5000) {
|
||||
t.Errorf("cohorts: %+v", cos)
|
||||
}
|
||||
ch := m.Changes("2026-04", map[string]Customer{"cus_b": {ID: "cus_b", Name: "Bea"}})
|
||||
if len(ch) != 2 || ch[0].Customer.Name != "" || ch[1].Customer.Name != "Bea" || ch[1].Kind != MoveChurn {
|
||||
t.Errorf("changes: %+v", ch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartMonthAndSuggestion(t *testing.T) {
|
||||
d := openDB(t)
|
||||
addLines(t, d, monthly("cus_old", 1000, "2024-01", "2024-03")...)
|
||||
for i := 0; i < 25; i++ {
|
||||
addLines(t, d, monthly(fmt.Sprintf("cus_%d", i), 4000, "2025-01", "2025-04")...)
|
||||
}
|
||||
now := time.Date(2025, 3, 20, 0, 0, 0, 0, time.UTC)
|
||||
m, _ := Build(d, now)
|
||||
if m.Suggest == nil || m.Suggest.Month != "2025-01" || m.Suggest.Customers != 25 {
|
||||
t.Fatalf("suggestion: %+v", m.Suggest)
|
||||
}
|
||||
if err := SetStartMonth(d, "2025-01"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetStartMonth(d, "January"); err == nil {
|
||||
t.Error("a bad month was saved")
|
||||
}
|
||||
m, _ = Build(d, now)
|
||||
jan := m.Months[0]
|
||||
if jan.Month != "2025-01" || jan.New != 0 || jan.Customers != 25 || m.Suggest != nil {
|
||||
t.Errorf("counted from January: %+v", jan)
|
||||
}
|
||||
if cos := m.Cohorts(5, 2); len(cos) != 1 || cos[0].Customers != 25 {
|
||||
t.Errorf("the starting base's cohort: %+v", cos)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
// ChannelGeneral is spend that no one channel owns: tools, people, the
|
||||
// website's hosting.
|
||||
const ChannelGeneral = "general"
|
||||
|
||||
// SpendChannels are the channels spend can be logged against.
|
||||
func SpendChannels() []signals.Stage {
|
||||
return append(slices.Clone(signals.Channels), signals.Stage{ID: ChannelGeneral, Label: "General (no one channel)"})
|
||||
}
|
||||
|
||||
// ChannelName is how a spend channel is shown.
|
||||
func ChannelName(id string) string {
|
||||
switch id {
|
||||
case ChannelGeneral:
|
||||
return "General"
|
||||
case "":
|
||||
return "Unknown"
|
||||
}
|
||||
return signals.ChannelLabel(id)
|
||||
}
|
||||
|
||||
func validChannel(c string) bool {
|
||||
for _, ch := range SpendChannels() {
|
||||
if ch.ID == c {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Spend is one entry in the log.
|
||||
type Spend struct {
|
||||
ID int64
|
||||
Month string
|
||||
Channel string
|
||||
AmountCents int64
|
||||
Note string
|
||||
Source string
|
||||
}
|
||||
|
||||
// AddSpend logs an amount for a month and channel.
|
||||
func AddSpend(d *db.DB, sp Spend, now time.Time) error {
|
||||
if _, err := time.Parse("2006-01", sp.Month); err != nil {
|
||||
return fmt.Errorf("%q isn't a month (YYYY-MM)", sp.Month)
|
||||
}
|
||||
if !validChannel(sp.Channel) {
|
||||
return fmt.Errorf("unknown channel %q", sp.Channel)
|
||||
}
|
||||
if sp.AmountCents == 0 {
|
||||
return errors.New("give an amount")
|
||||
}
|
||||
if sp.Source == "" {
|
||||
sp.Source = "manual"
|
||||
}
|
||||
_, err := d.Exec(`INSERT INTO spend (month, channel, amount_cents, note, source, created_at) VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
sp.Month, sp.Channel, sp.AmountCents, strings.TrimSpace(sp.Note), sp.Source, now.UTC().Format(time.RFC3339))
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteSpend removes an entry.
|
||||
func DeleteSpend(d *db.DB, id int64) error {
|
||||
_, err := d.Exec(`DELETE FROM spend WHERE id = ?`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// SpendLog lists the entries, newest month first.
|
||||
func SpendLog(d *db.DB, limit int) ([]Spend, error) {
|
||||
rows, err := d.Query(`SELECT id, month, channel, amount_cents, note, source FROM spend ORDER BY month DESC, id DESC LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []Spend
|
||||
for rows.Next() {
|
||||
var s Spend
|
||||
if err := rows.Scan(&s.ID, &s.Month, &s.Channel, &s.AmountCents, &s.Note, &s.Source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ParseAmount reads "1,250.50", "$80" or "80" as cents.
|
||||
func ParseAmount(s string) (int64, error) {
|
||||
s = strings.NewReplacer("$", "", ",", "", " ", "").Replace(strings.TrimSpace(s))
|
||||
f, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil || math.IsNaN(f) || math.IsInf(f, 0) {
|
||||
return 0, fmt.Errorf("%q isn't an amount", s)
|
||||
}
|
||||
return int64(math.Round(f * 100)), nil
|
||||
}
|
||||
|
||||
// ImportSpendCSV adds rows of month,channel,amount[,note]; a header row is
|
||||
// skipped. Channels may be given by name ("LinkedIn") or ID ("linkedin").
|
||||
// Nothing is added unless every row is good.
|
||||
func ImportSpendCSV(d *db.DB, r io.Reader, now time.Time) (int, error) {
|
||||
cr := csv.NewReader(r)
|
||||
cr.FieldsPerRecord = -1 // the note is optional
|
||||
cr.TrimLeadingSpace = true
|
||||
rows, err := cr.ReadAll()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
byName := map[string]string{}
|
||||
for _, c := range SpendChannels() {
|
||||
byName[strings.ToLower(c.ID)] = c.ID
|
||||
byName[strings.ToLower(c.Label)] = c.ID
|
||||
}
|
||||
byName["general"] = ChannelGeneral
|
||||
var entries []Spend
|
||||
for i, row := range rows {
|
||||
if len(row) < 3 {
|
||||
return 0, fmt.Errorf("row %d: needs month, channel and amount", i+1)
|
||||
}
|
||||
month, ch, amt := strings.TrimSpace(row[0]), strings.ToLower(strings.TrimSpace(row[1])), row[2]
|
||||
if i == 0 && strings.EqualFold(month, "month") {
|
||||
continue
|
||||
}
|
||||
if t, err := time.Parse("2006-01-02", month); err == nil {
|
||||
month = t.Format("2006-01")
|
||||
}
|
||||
if _, err := time.Parse("2006-01", month); err != nil {
|
||||
return 0, fmt.Errorf("row %d: %q isn't a month (YYYY-MM)", i+1, month)
|
||||
}
|
||||
id, ok := byName[ch]
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("row %d: unknown channel %q", i+1, row[1])
|
||||
}
|
||||
cents, err := ParseAmount(amt)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("row %d: %w", i+1, err)
|
||||
}
|
||||
note := ""
|
||||
if len(row) > 3 {
|
||||
note = row[3]
|
||||
}
|
||||
entries = append(entries, Spend{Month: month, Channel: id, AmountCents: cents, Note: note, Source: "csv"})
|
||||
}
|
||||
for _, e := range entries {
|
||||
if err := AddSpend(d, e, now); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return len(entries), nil
|
||||
}
|
||||
|
||||
// SyncOutsideSpend adds what outside campaigns (origami.chat, explee.com)
|
||||
// have spent since last seen, to the current month and their channel. The
|
||||
// first time, a campaign's whole spend so far is added, with a note.
|
||||
func SyncOutsideSpend(d *db.DB, now time.Time) (int, error) {
|
||||
rows, err := d.Query(`SELECT c.source, c.id, c.name, c.spend_cents, s.spend_cents FROM outside_campaigns c
|
||||
LEFT JOIN spend_seen s ON s.source = c.source AND s.campaign = c.id WHERE c.spend_cents > 0`)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
type seen struct {
|
||||
source, id, name string
|
||||
total int64
|
||||
before *int64
|
||||
}
|
||||
var all []seen
|
||||
for rows.Next() {
|
||||
var s seen
|
||||
if err := rows.Scan(&s.source, &s.id, &s.name, &s.total, &s.before); err != nil {
|
||||
rows.Close()
|
||||
return 0, err
|
||||
}
|
||||
all = append(all, s)
|
||||
}
|
||||
rows.Close()
|
||||
added := 0
|
||||
month := now.Format("2006-01")
|
||||
for _, s := range all {
|
||||
var prev int64
|
||||
note := "spent in “" + s.name + "”"
|
||||
if s.before == nil {
|
||||
note = "spent in “" + s.name + "” before Supermarket tracked it month by month"
|
||||
} else {
|
||||
prev = *s.before
|
||||
}
|
||||
if delta := s.total - prev; delta != 0 {
|
||||
if err := AddSpend(d, Spend{Month: month, Channel: s.source, AmountCents: delta, Note: note, Source: s.source}, now); err != nil {
|
||||
return added, err
|
||||
}
|
||||
added++
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO spend_seen (source, campaign, spend_cents) VALUES (?, ?, ?)
|
||||
ON CONFLICT (source, campaign) DO UPDATE SET spend_cents = excluded.spend_cents`, s.source, s.id, s.total); err != nil {
|
||||
return added, err
|
||||
}
|
||||
}
|
||||
return added, nil
|
||||
}
|
||||
|
||||
// --- CAC ---
|
||||
|
||||
// CACMonth is one month's spend, new customers and CAC.
|
||||
type CACMonth struct {
|
||||
Month string
|
||||
Spend int64 // cents
|
||||
New int
|
||||
CAC float64 // cents; -1 with no new customers
|
||||
Trailing3 float64 // three months' spend ÷ three months' new customers; -1 when none
|
||||
}
|
||||
|
||||
// CACChannel is a channel's spend and new customers over a period.
|
||||
type CACChannel struct {
|
||||
Channel string
|
||||
Spend int64
|
||||
New int
|
||||
CAC float64 // -1 with no new customers
|
||||
}
|
||||
|
||||
// CAC is spend over new paying customers.
|
||||
type CAC struct {
|
||||
Months []CACMonth // newest first
|
||||
Channels []CACChannel // over the last 12 months
|
||||
Unknown int // new customers with no known first touch
|
||||
}
|
||||
|
||||
// firstTouch is each email's first funnel channel, from the events the
|
||||
// funnel recorded before a payment (Stripe's own steps don't count).
|
||||
func firstTouch(d *db.DB) (map[string]string, error) {
|
||||
rows, err := d.Query(`SELECT email, channel FROM funnel_events WHERE email != '' AND source != 'stripe' ORDER BY at`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var e, c string
|
||||
if err := rows.Scan(&e, &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e = strings.ToLower(e)
|
||||
if _, ok := out[e]; !ok {
|
||||
out[e] = c
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// BuildCAC works out CAC from the spend log and the MRR model's new
|
||||
// customers, by month and, over the last 12 months, by each new customer's
|
||||
// first funnel channel.
|
||||
func BuildCAC(d *db.DB, model *Model, names map[string]Customer) (*CAC, error) {
|
||||
spend := map[string]int64{}
|
||||
byChan := map[string]int64{}
|
||||
rows, err := d.Query(`SELECT month, channel, sum(amount_cents) FROM spend GROUP BY month, channel`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var last12 map[string]bool
|
||||
if n := len(model.Months); n > 0 {
|
||||
last12 = map[string]bool{}
|
||||
for i := max(0, n-12); i < n; i++ {
|
||||
last12[model.Months[i].Month] = true
|
||||
}
|
||||
}
|
||||
for rows.Next() {
|
||||
var m, c string
|
||||
var a int64
|
||||
if err := rows.Scan(&m, &c, &a); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
spend[m] += a
|
||||
if last12[m] {
|
||||
byChan[c] += a
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
touch, err := firstTouch(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := &CAC{}
|
||||
newByChan := map[string]int{}
|
||||
ms := model.Months
|
||||
for i := len(ms) - 1; i >= 0; i-- {
|
||||
mo := ms[i]
|
||||
cm := CACMonth{Month: mo.Month, Spend: spend[mo.Month], New: mo.NewCount, CAC: -1, Trailing3: -1}
|
||||
if cm.New > 0 && cm.Spend != 0 {
|
||||
cm.CAC = float64(cm.Spend) / float64(cm.New)
|
||||
}
|
||||
var s3 int64
|
||||
n3 := 0
|
||||
for j := i; j > i-3 && j >= 0; j-- {
|
||||
s3 += spend[ms[j].Month]
|
||||
n3 += ms[j].NewCount
|
||||
}
|
||||
// Without spend logged, CAC is unknown, not zero.
|
||||
if n3 > 0 && i >= 2 && s3 != 0 {
|
||||
cm.Trailing3 = float64(s3) / float64(n3)
|
||||
}
|
||||
out.Months = append(out.Months, cm)
|
||||
if last12[mo.Month] {
|
||||
for c, k := range mo.Moves {
|
||||
if k != MoveNew {
|
||||
continue
|
||||
}
|
||||
ch := touch[strings.ToLower(names[c].Email)]
|
||||
if ch == "" {
|
||||
out.Unknown++
|
||||
}
|
||||
newByChan[ch]++
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for c := range byChan {
|
||||
keys[c] = true
|
||||
}
|
||||
for c := range newByChan {
|
||||
keys[c] = true
|
||||
}
|
||||
for c := range keys {
|
||||
cc := CACChannel{Channel: c, Spend: byChan[c], New: newByChan[c], CAC: -1}
|
||||
if cc.New > 0 && c != "" && c != ChannelGeneral {
|
||||
cc.CAC = float64(cc.Spend) / float64(cc.New)
|
||||
}
|
||||
out.Channels = append(out.Channels, cc)
|
||||
}
|
||||
slices.SortFunc(out.Channels, func(a, b CACChannel) int {
|
||||
if a.Spend != b.Spend {
|
||||
if a.Spend > b.Spend {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
return b.New - a.New
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSpendLog(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC)
|
||||
if err := AddSpend(d, Spend{Month: "2026-11", Channel: "linkedin", AmountCents: 32000}, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []Spend{{Month: "Nov", Channel: "linkedin", AmountCents: 1}, {Month: "2026-11", Channel: "tv", AmountCents: 1}, {Month: "2026-11", Channel: "email"}} {
|
||||
if err := AddSpend(d, bad, now); err == nil {
|
||||
t.Errorf("accepted %+v", bad)
|
||||
}
|
||||
}
|
||||
if c, err := ParseAmount("$1,250.50"); err != nil || c != 125050 {
|
||||
t.Errorf("amount: %d %v", c, err)
|
||||
}
|
||||
// A CSV with a bad row adds nothing.
|
||||
if _, err := ImportSpendCSV(d, strings.NewReader("month,channel,amount,note\n2026-10,LinkedIn,100,ads\n2026-10,Radio,5\n"), now); err == nil || !strings.Contains(err.Error(), "row 3") {
|
||||
t.Errorf("bad csv: %v", err)
|
||||
}
|
||||
n, err := ImportSpendCSV(d, strings.NewReader("month,channel,amount,note\n2026-10-01,LinkedIn,100,ads\n2026-10,general,\"1,000\",tools\n"), now)
|
||||
if err != nil || n != 2 {
|
||||
t.Fatalf("csv: %d %v", n, err)
|
||||
}
|
||||
log, _ := SpendLog(d, 10)
|
||||
if len(log) != 3 || log[0].Month != "2026-11" || log[2].Channel != "linkedin" || log[1].AmountCents != 100000 || log[2].Source != "csv" {
|
||||
t.Errorf("log: %+v", log)
|
||||
}
|
||||
DeleteSpend(d, log[0].ID)
|
||||
if log, _ := SpendLog(d, 10); len(log) != 2 {
|
||||
t.Errorf("after delete: %+v", log)
|
||||
}
|
||||
|
||||
// Outside campaigns: the whole spend the first time, then the difference.
|
||||
d.Exec(`INSERT INTO outside_campaigns (source, id, name, spend_cents, synced_at) VALUES ('explee', '7', 'Nonprofits', 20000, ''), ('origami', 'x', 'Zero', 0, '')`)
|
||||
if n, _ := SyncOutsideSpend(d, now); n != 1 {
|
||||
t.Errorf("first sync: %d", n)
|
||||
}
|
||||
d.Exec(`UPDATE outside_campaigns SET spend_cents = 26500 WHERE id = '7'`)
|
||||
SyncOutsideSpend(d, now.AddDate(0, 1, 0))
|
||||
if n, _ := SyncOutsideSpend(d, now.AddDate(0, 1, 0)); n != 0 {
|
||||
t.Error("synced the same spend twice")
|
||||
}
|
||||
var dec int64
|
||||
var note string
|
||||
d.QueryRow(`SELECT amount_cents, note FROM spend WHERE source = 'explee' AND month = '2026-12'`).Scan(&dec, ¬e)
|
||||
if dec != 6500 || !strings.Contains(note, "Nonprofits") {
|
||||
t.Errorf("delta: %d %q", dec, note)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCAC(t *testing.T) {
|
||||
d := openDB(t)
|
||||
now := time.Date(2026, 6, 20, 0, 0, 0, 0, time.UTC)
|
||||
addLines(t, d, monthly("cus_a", 5000, "2026-03", "2026-07")...)
|
||||
addLines(t, d, monthly("cus_b", 5000, "2026-04", "2026-07")...)
|
||||
addLines(t, d, monthly("cus_c", 5000, "2026-04", "2026-07")...)
|
||||
addLines(t, d, monthly("cus_d", 5000, "2026-06", "2026-07")...)
|
||||
names := map[string]Customer{"cus_a": {Email: "a@x.example"}, "cus_b": {Email: "b@x.example"}, "cus_c": {Email: "c@x.example"}, "cus_d": {Email: "d@x.example"}}
|
||||
// b came from an outreach email, c from LinkedIn (first touch wins), d's
|
||||
// only step is its Stripe payment, which doesn't count.
|
||||
for _, e := range []struct{ email, channel, source, at string }{
|
||||
{"b@x.example", "email", "supermarket", "2026-03-01"}, {"c@x.example", "linkedin", "manual", "2026-02-01"},
|
||||
{"c@x.example", "email", "supermarket", "2026-03-01"}, {"d@x.example", "website", "stripe", "2026-06-11"},
|
||||
} {
|
||||
d.Exec(`INSERT INTO funnel_events (stage, channel, email, source, at) VALUES ('contacted', ?, ?, ?, ?)`, e.channel, e.email, e.source, e.at+"T00:00:00Z")
|
||||
}
|
||||
for _, s := range []Spend{{Month: "2026-04", Channel: "email", AmountCents: 30000}, {Month: "2026-04", Channel: "general", AmountCents: 10000},
|
||||
{Month: "2026-06", Channel: "linkedin", AmountCents: 20000}} {
|
||||
if err := AddSpend(d, s, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
m, _ := Build(d, now)
|
||||
c, err := BuildCAC(d, m, names)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]CACMonth{}
|
||||
for _, cm := range c.Months {
|
||||
got[cm.Month] = cm
|
||||
}
|
||||
if apr := got["2026-04"]; apr.New != 2 || apr.Spend != 40000 || apr.CAC != 20000 {
|
||||
t.Errorf("april: %+v", apr)
|
||||
}
|
||||
if may := got["2026-05"]; may.CAC != -1 {
|
||||
t.Errorf("may has no new customers: %+v", may)
|
||||
}
|
||||
// June, three months: $600 over 3 customers (b, c, d; a was in March).
|
||||
if jun := got["2026-06"]; jun.Trailing3 != 20000 || jun.CAC != 20000 {
|
||||
t.Errorf("june: %+v", jun)
|
||||
}
|
||||
ch := map[string]CACChannel{}
|
||||
for _, x := range c.Channels {
|
||||
ch[x.Channel] = x
|
||||
}
|
||||
if ch["email"].New != 1 || ch["email"].CAC != 30000 || ch["linkedin"].New != 1 || ch["linkedin"].CAC != 20000 || ch["general"].CAC != -1 {
|
||||
t.Errorf("channels: %+v", ch)
|
||||
}
|
||||
if c.Unknown != 2 || ch[""].New != 2 {
|
||||
t.Errorf("unknown: %d %+v", c.Unknown, ch[""])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
// Package metrics turns the company's Stripe data into the numbers a
|
||||
// subscription business runs on: MRR and its movements, NRR, CAC, CLV and
|
||||
// cohorts. Every number is computed here from the synced data; nothing is
|
||||
// estimated.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/stripe"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Kinds of Stripe object kept.
|
||||
const (
|
||||
KindCustomer = "customer"
|
||||
KindInvoice = "invoice"
|
||||
KindCreditNote = "credit_note"
|
||||
KindRefund = "refund"
|
||||
KindProduct = "product"
|
||||
)
|
||||
|
||||
// eventsKept is how long Stripe keeps events; a watermark older than this
|
||||
// needs a new backfill.
|
||||
const eventsKept = 29 * 24 * time.Hour
|
||||
|
||||
type syncState struct {
|
||||
Backfilled time.Time `json:"backfilled"`
|
||||
LastEvent int64 `json:"last_event"` // created time of the last event applied
|
||||
}
|
||||
|
||||
const stateKey = "metrics:stripe-state"
|
||||
|
||||
// SyncResult is what a sync did.
|
||||
type SyncResult struct {
|
||||
At time.Time `json:"at"`
|
||||
Full bool `json:"full"` // a backfill, not just events
|
||||
Events int `json:"events"` // events applied
|
||||
Counts map[string]int `json:"counts"` // objects stored, by kind
|
||||
Error string `json:"error,omitempty"`
|
||||
Currency []string `json:"currency"` // the currencies seen
|
||||
Notes []string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
const resultKey = "metrics:stripe-last"
|
||||
|
||||
// LastSync is the last sync's result, or nil.
|
||||
func LastSync(d *db.DB) *SyncResult {
|
||||
var r SyncResult
|
||||
if ok, _ := d.GetJSON(resultKey, &r); !ok {
|
||||
return nil
|
||||
}
|
||||
return &r
|
||||
}
|
||||
|
||||
// Sync brings the Stripe data up to date: a full backfill the first time
|
||||
// (or when the events since the last sync are no longer kept), then the
|
||||
// events since the last one.
|
||||
func Sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceFull bool) (*SyncResult, error) {
|
||||
res := &SyncResult{At: now, Counts: map[string]int{}}
|
||||
err := sync(ctx, d, c, now, forceFull, res)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
res.Currency, _ = currencies(d)
|
||||
if perr := d.PutJSON(resultKey, res); perr != nil && err == nil {
|
||||
err = perr
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func sync(ctx context.Context, d *db.DB, c *stripe.Client, now time.Time, forceFull bool, res *SyncResult) error {
|
||||
var st syncState
|
||||
if _, err := d.GetJSON(stateKey, &st); err != nil {
|
||||
return err
|
||||
}
|
||||
if forceFull || st.LastEvent == 0 || now.Sub(time.Unix(st.LastEvent, 0)) > eventsKept {
|
||||
res.Full = true
|
||||
// Events from the moment the backfill starts are applied next time,
|
||||
// so nothing falls between the two.
|
||||
start := now.Add(-time.Minute)
|
||||
for _, l := range []struct {
|
||||
kind, path string
|
||||
q url.Values
|
||||
}{
|
||||
{KindCustomer, "/v1/customers", nil},
|
||||
{KindInvoice, "/v1/invoices", nil},
|
||||
{KindCreditNote, "/v1/credit_notes", nil},
|
||||
{KindRefund, "/v1/refunds", url.Values{"expand[]": {"data.charge"}}},
|
||||
{KindProduct, "/v1/products", nil},
|
||||
} {
|
||||
raws, err := c.ListRaw(ctx, l.path, l.q, 0)
|
||||
if err != nil && l.kind == KindProduct {
|
||||
// Optional: without Products access, names come from the
|
||||
// invoice lines.
|
||||
res.Notes = append(res.Notes, "Product names come from invoice lines: the key can't read Products ("+err.Error()+").")
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %ss: %w", l.kind, err)
|
||||
}
|
||||
for _, r := range raws {
|
||||
if err := store(ctx, d, c, l.kind, r.JSON); err != nil {
|
||||
return err
|
||||
}
|
||||
res.Counts[l.kind]++
|
||||
}
|
||||
}
|
||||
st = syncState{Backfilled: now, LastEvent: start.Unix()}
|
||||
return d.PutJSON(stateKey, st)
|
||||
}
|
||||
// Products change rarely and have no events followed: read them all.
|
||||
if raws, err := c.ListRaw(ctx, "/v1/products", nil, 0); err == nil {
|
||||
for _, r := range raws {
|
||||
if err := store(ctx, d, c, KindProduct, r.JSON); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
events, err := c.Events(ctx, time.Unix(st.LastEvent, 0))
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading events: %w", err)
|
||||
}
|
||||
for _, e := range events {
|
||||
kind, obj := "", e.Data.Object
|
||||
var head struct {
|
||||
Object string `json:"object"`
|
||||
ID string `json:"id"`
|
||||
Refunds struct {
|
||||
Data []json.RawMessage `json:"data"`
|
||||
} `json:"refunds"`
|
||||
}
|
||||
_ = json.Unmarshal(obj, &head)
|
||||
switch head.Object {
|
||||
case "customer":
|
||||
kind = KindCustomer
|
||||
if e.Type == "customer.deleted" {
|
||||
if _, err := d.Exec(`UPDATE stripe_objects SET status = 'deleted' WHERE kind = ? AND id = ?`, KindCustomer, head.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
st.LastEvent = e.Created
|
||||
res.Events++
|
||||
continue
|
||||
}
|
||||
case "invoice":
|
||||
kind = KindInvoice
|
||||
case "credit_note":
|
||||
kind = KindCreditNote
|
||||
case "refund":
|
||||
kind = KindRefund
|
||||
// Read it again with its charge, for the customer.
|
||||
if full, err := c.GetRaw(ctx, "/v1/refunds/"+url.PathEscape(head.ID), url.Values{"expand[]": {"charge"}}); err == nil {
|
||||
obj = full
|
||||
}
|
||||
case "charge":
|
||||
// charge.refunded: its refunds are what matter.
|
||||
for _, r := range head.Refunds.Data {
|
||||
var rh struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(r, &rh)
|
||||
full, err := c.GetRaw(ctx, "/v1/refunds/"+url.PathEscape(rh.ID), url.Values{"expand[]": {"charge"}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store(ctx, d, c, KindRefund, full); err != nil {
|
||||
return err
|
||||
}
|
||||
res.Counts[KindRefund]++
|
||||
}
|
||||
}
|
||||
if kind != "" {
|
||||
if err := store(ctx, d, c, kind, obj); err != nil {
|
||||
return err
|
||||
}
|
||||
res.Counts[kind]++
|
||||
}
|
||||
st.LastEvent = e.Created
|
||||
res.Events++
|
||||
}
|
||||
return d.PutJSON(stateKey, st)
|
||||
}
|
||||
|
||||
// store keeps one object, and an invoice's lines.
|
||||
func store(ctx context.Context, d *db.DB, c *stripe.Client, kind string, raw json.RawMessage) error {
|
||||
var o struct {
|
||||
ID string `json:"id"`
|
||||
Customer json.RawMessage `json:"customer"`
|
||||
Created int64 `json:"created"`
|
||||
Status string `json:"status"`
|
||||
Currency string `json:"currency"`
|
||||
Total int64 `json:"total"`
|
||||
Amount int64 `json:"amount"`
|
||||
Deleted bool `json:"deleted"`
|
||||
Charge json.RawMessage `json:"charge"`
|
||||
Lines struct {
|
||||
Data []json.RawMessage `json:"data"`
|
||||
HasMore bool `json:"has_more"`
|
||||
} `json:"lines"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &o); err != nil {
|
||||
return err
|
||||
}
|
||||
customer, amount := stripe.IDOf(o.Customer), o.Total
|
||||
switch kind {
|
||||
case KindCustomer:
|
||||
customer = o.ID
|
||||
if o.Deleted {
|
||||
o.Status = "deleted"
|
||||
}
|
||||
case KindRefund:
|
||||
amount = o.Amount
|
||||
var ch struct {
|
||||
Customer json.RawMessage `json:"customer"`
|
||||
}
|
||||
_ = json.Unmarshal(o.Charge, &ch)
|
||||
customer = stripe.IDOf(ch.Customer)
|
||||
case KindInvoice:
|
||||
if o.Status == "draft" {
|
||||
return nil // not billed yet
|
||||
}
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO stripe_objects (kind, id, customer, created, status, currency, amount, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (kind, id) DO UPDATE SET customer = excluded.customer, created = excluded.created, status = excluded.status,
|
||||
currency = excluded.currency, amount = excluded.amount, data = excluded.data`,
|
||||
kind, o.ID, customer, o.Created, o.Status, o.Currency, amount, string(raw)); err != nil {
|
||||
return err
|
||||
}
|
||||
if kind != KindInvoice {
|
||||
return nil
|
||||
}
|
||||
lines := o.Lines.Data
|
||||
if o.Lines.HasMore {
|
||||
all, err := c.InvoiceLines(ctx, o.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s's lines: %w", o.ID, err)
|
||||
}
|
||||
lines = all
|
||||
}
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`DELETE FROM stripe_invoice_lines WHERE invoice = ?`, o.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, raw := range lines {
|
||||
l, err := stripe.ParseLine(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end,
|
||||
subscription, price, product, interval, interval_count, quantity, proration, recurring, description)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, o.ID, l.ID, customer, o.Status, or(l.Currency, o.Currency), l.Amount,
|
||||
l.PeriodStart, l.PeriodEnd, l.Subscription, l.Price, l.Product, l.Interval, l.IntervalCount, l.Quantity, l.Proration, l.Recurring,
|
||||
l.Description); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func or(a, b string) string {
|
||||
if a != "" {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// currencies are the currencies in the invoices, most used first.
|
||||
func currencies(d *db.DB) ([]string, error) {
|
||||
rows, err := d.Query(`SELECT currency FROM stripe_objects WHERE kind = 'invoice' AND currency != '' GROUP BY currency ORDER BY count(*) DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var c string
|
||||
if err := rows.Scan(&c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Counts are how many objects of each kind are stored.
|
||||
func Counts(d *db.DB) (map[string]int, error) {
|
||||
rows, err := d.Query(`SELECT kind, count(*) FROM stripe_objects GROUP BY kind`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]int{}
|
||||
for rows.Next() {
|
||||
var k string
|
||||
var n int
|
||||
if err := rows.Scan(&k, &n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[k] = n
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/stripe"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
func openDB(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
return d
|
||||
}
|
||||
|
||||
// An invoice in the older line shape, and one in the 2025 shape with more
|
||||
// lines than fit in the embedded list.
|
||||
const (
|
||||
oldInvoice = `{"id":"in_1","object":"invoice","customer":"cus_a","created":1760000000,"status":"paid","currency":"usd","total":4500,
|
||||
"lines":{"has_more":false,"data":[{"id":"il_1","amount":5000,"currency":"usd","period":{"start":1760000000,"end":1762678400},
|
||||
"quantity":5,"proration":false,"type":"subscription","subscription":"sub_1",
|
||||
"price":{"id":"price_m","product":"prod_x","recurring":{"interval":"month","interval_count":1}},
|
||||
"discount_amounts":[{"amount":500}]}]}}`
|
||||
newInvoice = `{"id":"in_2","object":"invoice","customer":"cus_b","created":1761000000,"status":"open","currency":"usd","total":120000,
|
||||
"lines":{"has_more":true,"data":[]}}`
|
||||
newLines = `{"data":[{"id":"il_2","object":"line_item","amount":120000,"currency":"usd","period":{"start":1761000000,"end":1792536000},
|
||||
"pricing":{"price_details":{"price":"price_y","product":"prod_x"}},
|
||||
"parent":{"type":"subscription_item_details","subscription_item_details":{"subscription":"sub_2","proration":false}}}],"has_more":false}`
|
||||
)
|
||||
|
||||
var noProducts bool
|
||||
|
||||
func fakeStripe(t *testing.T, events *string) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/v1/customers":
|
||||
fmt.Fprint(w, `{"data":[{"id":"cus_a","object":"customer","created":1750000000,"email":"a@x.example"},{"id":"cus_b","object":"customer","created":1750000001}],"has_more":false}`)
|
||||
case "/v1/invoices":
|
||||
fmt.Fprintf(w, `{"data":[%s,%s,{"id":"in_draft","object":"invoice","customer":"cus_a","status":"draft","lines":{"data":[]}}],"has_more":false}`, oldInvoice, newInvoice)
|
||||
case "/v1/invoices/in_2/lines":
|
||||
fmt.Fprint(w, newLines)
|
||||
case "/v1/credit_notes":
|
||||
fmt.Fprint(w, `{"data":[{"id":"cn_1","object":"credit_note","customer":"cus_a","created":1760100000,"status":"issued","currency":"usd","total":1000}],"has_more":false}`)
|
||||
case "/v1/refunds":
|
||||
if r.URL.Query().Get("expand[]") != "data.charge" {
|
||||
t.Errorf("refunds without their charge: %s", r.URL)
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[{"id":"re_1","object":"refund","amount":2000,"currency":"usd","created":1760200000,"status":"succeeded","charge":{"id":"ch_1","customer":"cus_a"}}],"has_more":false}`)
|
||||
case "/v1/refunds/re_2":
|
||||
fmt.Fprint(w, `{"id":"re_2","object":"refund","amount":300,"currency":"usd","created":1762000000,"status":"succeeded","charge":{"id":"ch_2","customer":"cus_b"}}`)
|
||||
case "/v1/products":
|
||||
if noProducts {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprint(w, `{"error":{"message":"The provided key does not have the required permissions"}}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"data":[{"id":"prod_x","object":"product","name":"Federated Core","created":1700000000}],"has_more":false}`)
|
||||
case "/v1/events":
|
||||
if len(r.URL.Query()["types[]"]) != len(stripe.EventTypes) {
|
||||
t.Errorf("event types: %v", r.URL.Query()["types[]"])
|
||||
}
|
||||
fmt.Fprint(w, *events)
|
||||
default:
|
||||
t.Errorf("unexpected %s", r.URL)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func TestSync(t *testing.T) {
|
||||
d := openDB(t)
|
||||
events := `{"data":[],"has_more":false}`
|
||||
srv := fakeStripe(t, &events)
|
||||
defer srv.Close()
|
||||
c := stripe.New("rk_test").WithBase(srv.URL)
|
||||
ctx := context.Background()
|
||||
now := time.Unix(1762100000, 0)
|
||||
|
||||
res, err := Sync(ctx, d, c, now, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !res.Full || res.Counts[KindCustomer] != 2 || res.Counts[KindInvoice] != 3 || res.Counts[KindRefund] != 1 || strings.Join(res.Currency, ",") != "usd" {
|
||||
t.Fatalf("backfill: %+v", res)
|
||||
}
|
||||
counts, _ := Counts(d)
|
||||
if counts[KindProduct] != 1 {
|
||||
t.Errorf("products: %v", counts)
|
||||
}
|
||||
if counts[KindInvoice] != 2 {
|
||||
t.Errorf("a draft invoice was kept: %v", counts)
|
||||
}
|
||||
var amount, start, end int64
|
||||
var interval string
|
||||
d.QueryRow(`SELECT amount, period_start, period_end, interval FROM stripe_invoice_lines WHERE id = 'il_1'`).Scan(&amount, &start, &end, &interval)
|
||||
if amount != 4500 || interval != "month" || end-start != 2678400 {
|
||||
t.Errorf("old line: %d %s %d", amount, interval, end-start)
|
||||
}
|
||||
var sub, cust string
|
||||
var recurring bool
|
||||
d.QueryRow(`SELECT subscription, customer, recurring FROM stripe_invoice_lines WHERE id = 'il_2'`).Scan(&sub, &cust, &recurring)
|
||||
if sub != "sub_2" || cust != "cus_b" || !recurring {
|
||||
t.Errorf("new line: %q %q %v", sub, cust, recurring)
|
||||
}
|
||||
var refundCustomer string
|
||||
d.QueryRow(`SELECT customer FROM stripe_objects WHERE kind = 'refund' AND id = 're_1'`).Scan(&refundCustomer)
|
||||
if refundCustomer != "cus_a" {
|
||||
t.Errorf("refund's customer: %q", refundCustomer)
|
||||
}
|
||||
|
||||
// Then events: the open invoice is paid, a customer is deleted, a charge
|
||||
// is refunded.
|
||||
paid := strings.Replace(strings.Replace(newInvoice, `"status":"open"`, `"status":"paid"`, 1), `"has_more":true`, `"has_more":false`, 1)
|
||||
paid = strings.Replace(paid, `"data":[]`, `"data":[{"id":"il_2","amount":120000,"currency":"usd","period":{"start":1761000000,"end":1792536000},"type":"subscription","subscription":"sub_2","price":{"id":"price_y","product":"prod_x","recurring":{"interval":"year","interval_count":1}}}]`, 1)
|
||||
events = fmt.Sprintf(`{"data":[
|
||||
{"id":"evt_3","type":"charge.refunded","created":1762300000,"data":{"object":{"id":"ch_2","object":"charge","refunds":{"data":[{"id":"re_2"}]}}}},
|
||||
{"id":"evt_2","type":"customer.deleted","created":1762200000,"data":{"object":{"id":"cus_a","object":"customer","deleted":true}}},
|
||||
{"id":"evt_1","type":"invoice.paid","created":1762150000,"data":{"object":%s}}],"has_more":false}`, paid)
|
||||
res, err = Sync(ctx, d, c, now.Add(time.Hour), false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Full || res.Events != 3 {
|
||||
t.Fatalf("events: %+v", res)
|
||||
}
|
||||
var status string
|
||||
d.QueryRow(`SELECT status FROM stripe_objects WHERE kind = 'invoice' AND id = 'in_2'`).Scan(&status)
|
||||
d.QueryRow(`SELECT interval FROM stripe_invoice_lines WHERE id = 'il_2'`).Scan(&interval)
|
||||
if status != "paid" || interval != "year" {
|
||||
t.Errorf("paid invoice: %q %q", status, interval)
|
||||
}
|
||||
d.QueryRow(`SELECT status FROM stripe_objects WHERE kind = 'customer' AND id = 'cus_a'`).Scan(&status)
|
||||
if status != "deleted" {
|
||||
t.Errorf("deleted customer: %q", status)
|
||||
}
|
||||
if counts, _ := Counts(d); counts[KindRefund] != 2 {
|
||||
t.Errorf("refund from charge.refunded: %v", counts)
|
||||
}
|
||||
// A month later the events are gone: everything is read again.
|
||||
events = `{"data":[],"has_more":false}`
|
||||
if res, _ := Sync(ctx, d, c, now.AddDate(0, 0, 40), false); !res.Full {
|
||||
t.Error("an old watermark didn't trigger a backfill")
|
||||
}
|
||||
if LastSync(d) == nil {
|
||||
t.Error("the result isn't kept")
|
||||
}
|
||||
// A key without Products access still syncs, and says so.
|
||||
noProducts = true
|
||||
defer func() { noProducts = false }()
|
||||
res, err = Sync(ctx, d, c, now.AddDate(0, 0, 80), true)
|
||||
if err != nil || len(res.Notes) != 1 || !strings.Contains(res.Notes[0], "can't read Products") {
|
||||
t.Errorf("without products: %+v %v", res, err)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/gitea"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/hugorepo"
|
||||
)
|
||||
@@ -265,3 +266,48 @@ func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) e
|
||||
st.PRNumber, st.PRURL, st.Note = pr.Number, pr.HTMLURL, note
|
||||
return nil
|
||||
}
|
||||
|
||||
// PublishPage opens a pull request that adds a page to the site, or
|
||||
// updates it if it's there: used for the open metrics page. The build
|
||||
// checks the page comes out.
|
||||
func (ap *Applier) PublishPage(ctx context.Context, pagePath, title, description, body, why string) (*gitea.Pull, string, error) {
|
||||
wc, full, branch, err := ap.workingCopy(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
canBuild, note := buildCheck(ctx, wc)
|
||||
pagePath = "/" + strings.Trim(pagePath, "/") + "/"
|
||||
work := "supermarket/page" + strings.TrimSuffix(strings.ReplaceAll(pagePath, "/", "-"), "-")
|
||||
if err := wc.NewBranch(ctx, work); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
file, err := wc.FindContent(pagePath)
|
||||
if err != nil {
|
||||
file = "content" + strings.TrimSuffix(pagePath, "/") + ".md"
|
||||
}
|
||||
fields := []hugorepo.Field{{Key: "title", Value: title}, {Key: "description", Value: description}, {Key: "date", Value: time.Now().Format("2006-01-02")}}
|
||||
if err := wc.UpsertPage(file, fields, body); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if canBuild {
|
||||
out, err := wc.Build(ctx)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("after the change, %w", err)
|
||||
}
|
||||
_, _, err = hugorepo.BuiltHead(out, pagePath)
|
||||
os.RemoveAll(out)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("the site builds, but %w", err)
|
||||
}
|
||||
note = "Checked with a build: the page is at " + pagePath + "."
|
||||
}
|
||||
subject := "Update " + pagePath + ": " + title
|
||||
if err := wc.CommitAndPush(ctx, work, subject); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, why+"\n\n"+note+"\n\nMerging publishes it.")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return pr, file, nil
|
||||
}
|
||||
|
||||
@@ -111,3 +111,31 @@ func TestSetupSite(t *testing.T) {
|
||||
t.Error("the setup isn't kept")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishPage(t *testing.T) {
|
||||
if hugorepo.HugoVersion(context.Background()) == "" {
|
||||
t.Skip("no hugo")
|
||||
}
|
||||
clone := hugotest.Site(t)
|
||||
n := 0
|
||||
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/v1/repos/o/site":
|
||||
json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}})
|
||||
case r.URL.Path == "/api/v1/repos/o/site/pulls":
|
||||
n++
|
||||
json.NewEncoder(w).Encode(map[string]any{"number": n, "html_url": fmt.Sprintf("https://gitea.example/pr/%d", n)})
|
||||
}
|
||||
}))
|
||||
defer g.Close()
|
||||
ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "P <p@example.com>"}
|
||||
pr, file, err := ap.PublishPage(context.Background(), "/metrics/", "Open metrics", "Our numbers.", "MRR: $150\n", "why")
|
||||
if err != nil || pr.Number != 1 || file != "content/metrics.md" {
|
||||
t.Fatalf("publish: %+v %q %v", pr, file, err)
|
||||
}
|
||||
repo := strings.TrimPrefix(clone, "file://")
|
||||
out, _ := exec.Command("git", "-C", repo, "show", "supermarket/page-metrics:content/metrics.md").CombinedOutput()
|
||||
if !strings.Contains(string(out), `title: "Open metrics"`) || !strings.Contains(string(out), "MRR: $150") {
|
||||
t.Errorf("page: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
@@ -58,3 +60,136 @@ func TestEnginesPage(t *testing.T) {
|
||||
t.Error("the ping isn't listed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarginsForm(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, status, currency, amount, period_start, product, description)
|
||||
VALUES ('in_1', 'il_1', 'paid', 'usd', 4900, strftime('%s', 'now'), 'prod_core', '1 × Federated Core (at $49.00 / month)')`)
|
||||
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Federated Core") || !strings.Contains(body, `placeholder="60"`) {
|
||||
t.Fatal("the margin table isn't shown")
|
||||
}
|
||||
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"55%"}, "margin:prod_core": {"70"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("save: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, `name="margin:prod_core" value="70"`) || !strings.Contains(body, `name="default" value="55"`) {
|
||||
t.Error("the margins weren't saved")
|
||||
}
|
||||
if rec := postForm(h, "/metrics/margins", url.Values{"default": {"abc"}}); !strings.Contains(rec.Body.String(), "percentage") {
|
||||
t.Error("a bad default was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMRRPages(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}'),
|
||||
('customer', 'cus_a', '', '{"id":"cus_a","name":"Acme","email":"a@acme.example"}')`)
|
||||
now := time.Now().UTC()
|
||||
for i := 3; i >= 0; i-- {
|
||||
start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -i, 0)
|
||||
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
|
||||
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), start.Unix(), start.AddDate(0, 1, 0).Unix())
|
||||
}
|
||||
body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String()
|
||||
for _, want := range []string{"$99", "ARR $1,188", "Month by month", "<svg class=\"chart\"", "Cohorts"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics lacks %q", want)
|
||||
}
|
||||
}
|
||||
first := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -3, 0).Format("2006-01")
|
||||
if body := do(h, http.MethodGet, "/metrics/month/"+first, nil, nil).Body.String(); !strings.Contains(body, "Acme") || !strings.Contains(body, "new") {
|
||||
t.Errorf("month detail: %s", first)
|
||||
}
|
||||
if rec := do(h, http.MethodGet, "/metrics/month/1999-01", nil, nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("unknown month: %d", rec.Code)
|
||||
}
|
||||
postForm(h, "/metrics/start", url.Values{"month": {first}})
|
||||
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Counted from "+first) {
|
||||
t.Error("the start month isn't used")
|
||||
}
|
||||
if rec := postForm(h, "/metrics/start", url.Values{"month": {"soon"}}); !strings.Contains(rec.Body.String(), "isn't a month") {
|
||||
t.Errorf("bad month: %s", rec.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomersPage(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
s.DB.Exec(`INSERT INTO crm_records (entity, espo_id, name, email, domain, data, synced_at) VALUES ('Account', 'a1', 'Acme', '', 'acme.example', '{}', '')`)
|
||||
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, data) VALUES ('customer', 'cus_x', 'cus_x', '{"name":"Xco","email":"x@xco.example"}'),
|
||||
('customer', 'cus_a', 'cus_a', '{"name":"Acme Ltd","email":"pay@acme.example"}')`)
|
||||
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, customer, status, currency, data) VALUES ('invoice', 'in_1', 'cus_x', 'paid', 'usd', '{}'), ('invoice', 'in_2', 'cus_a', 'paid', 'usd', '{}')`)
|
||||
body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "Xco") || strings.Contains(body, "Acme Ltd") {
|
||||
t.Fatal("the to-fix list should hold only the unmatched customer")
|
||||
}
|
||||
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"account"}, "account": {"Acme"}})
|
||||
if body := do(h, http.MethodGet, "/metrics/customers?show=all", nil, nil).Body.String(); !strings.Contains(body, "Acme <span class=\"muted small\">by you</span>") {
|
||||
t.Error("the manual match isn't shown")
|
||||
}
|
||||
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"auto"}})
|
||||
postForm(h, "/metrics/customers/cus_x", url.Values{"do": {"add"}})
|
||||
if acts, _ := crm.List(s.DB, 10); len(acts) != 1 || acts[0].Entity != "Account" || acts[0].Fields["website"] != "https://xco.example" {
|
||||
t.Errorf("queued: %+v", acts)
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/metrics/customers", nil, nil).Body.String(); !strings.Contains(body, "queued for the CRM") {
|
||||
t.Error("the queued Account isn't shown")
|
||||
}
|
||||
if rec := postForm(h, "/metrics/customers/bad", url.Values{"do": {"none"}}); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("bad id: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpendPage(t *testing.T) {
|
||||
_, h := newTestServer(t, nil)
|
||||
if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"$320"}, "note": {"ads"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("add: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if rec := postForm(h, "/metrics/spend", url.Values{"csv": {"2026-09,general,1000,tools"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("csv: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String()
|
||||
for _, want := range []string{"$320", "ads", "$1,000", "General"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("spend page lacks %q", want)
|
||||
}
|
||||
}
|
||||
if rec := postForm(h, "/metrics/spend", url.Values{"month": {"2026-10"}, "channel": {"linkedin"}, "amount": {"lots"}}); !strings.Contains(rec.Body.String(), "isn't an amount") {
|
||||
t.Error("a bad amount was accepted")
|
||||
}
|
||||
postForm(h, "/metrics/spend/1/delete", nil)
|
||||
if body := do(h, http.MethodGet, "/metrics/spend", nil, nil).Body.String(); strings.Contains(body, ">ads<") {
|
||||
t.Error("the entry wasn't deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportAndPublishPages(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
|
||||
s.DB.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_0', 'usd', '{}')`)
|
||||
start := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -2, 0)
|
||||
for i := 0; i < 3; i++ {
|
||||
ps := start.AddDate(0, i, 0)
|
||||
s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, customer, status, currency, amount, period_start, period_end, interval, interval_count, recurring)
|
||||
VALUES (?, ?, 'cus_a', 'paid', 'usd', 9900, ?, ?, 'month', 1, 1)`, fmt.Sprint("in_", i), fmt.Sprint("il_", i), ps.Unix(), ps.AddDate(0, 1, 0).Unix())
|
||||
}
|
||||
rec := do(h, http.MethodGet, "/metrics/export/mrr.csv", nil, nil)
|
||||
if rec.Header().Get("Content-Type") != "text/csv; charset=utf-8" || !strings.Contains(rec.Header().Get("Content-Disposition"), "supermarket-mrr-") ||
|
||||
!strings.HasPrefix(rec.Body.String(), "month,partial,mrr") {
|
||||
t.Errorf("export: %v %s", rec.Header(), rec.Body)
|
||||
}
|
||||
if rec := do(h, http.MethodGet, "/metrics/export/secrets.csv", nil, nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("unknown export: %d", rec.Code)
|
||||
}
|
||||
if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "/metrics/export/mrr.csv") {
|
||||
t.Error("no download link on Metrics")
|
||||
}
|
||||
postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {"/numbers/"}, "title": {"Our numbers"}, "part": {"mrr", "table"}, "do": {"save"}})
|
||||
body := do(h, http.MethodGet, "/metrics/publish", nil, nil).Body.String()
|
||||
for _, want := range []string{`value="/numbers/"`, "Monthly recurring revenue:** $99", "| Month | MRR |"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("publish page lacks %q", want)
|
||||
}
|
||||
}
|
||||
if rec := postForm(h, "/metrics/publish", url.Values{"site": {"0"}, "path": {""}, "title": {"x"}}); !strings.Contains(rec.Body.String(), "an address and a title") {
|
||||
t.Error("an empty address was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,555 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/metrics"
|
||||
)
|
||||
|
||||
func (s *Server) metricsPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderMetrics(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderMetrics(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
counts, err := metrics.Counts(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
products, err := metrics.Products(s.DB, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
model, err := metrics.Build(s.DB, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
clv, err := metrics.BuildCLV(s.DB, model, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.render(w, r, "metrics", page{Title: "Metrics", Nav: "metrics/overview", Error: errMsg, Data: map[string]any{
|
||||
"Stripe": s.stripe() != nil,
|
||||
"Last": metrics.LastSync(s.DB),
|
||||
"Counts": counts,
|
||||
"Products": products,
|
||||
"Margins": metrics.LoadMargins(s.DB),
|
||||
"Model": model,
|
||||
"CLV": clv,
|
||||
"Now": model.Last(),
|
||||
"Recent": model.Recent(13),
|
||||
"Bars": bars(model, 24),
|
||||
"Cohorts": model.Cohorts(12, 12),
|
||||
"Span": make([]int, 13),
|
||||
}})
|
||||
}
|
||||
|
||||
// bar is one month on the MRR chart.
|
||||
type bar struct {
|
||||
Month string
|
||||
MRR float64
|
||||
X, W, H float64 // in the SVG's units
|
||||
Y float64
|
||||
Label bool
|
||||
}
|
||||
|
||||
// bars lays out the last n months of MRR as an SVG bar chart, 600 by 160.
|
||||
func bars(m *metrics.Model, n int) []bar {
|
||||
ms := m.Months
|
||||
if len(ms) > n {
|
||||
ms = ms[len(ms)-n:]
|
||||
}
|
||||
top := 0.0
|
||||
for _, mo := range ms {
|
||||
top = max(top, mo.MRR)
|
||||
}
|
||||
if top == 0 || len(ms) == 0 {
|
||||
return nil
|
||||
}
|
||||
w := 600.0 / float64(len(ms))
|
||||
out := make([]bar, len(ms))
|
||||
for i, mo := range ms {
|
||||
h := 140 * mo.MRR / top
|
||||
out[i] = bar{Month: mo.Month, MRR: mo.MRR, X: float64(i)*w + 1, W: w - 2, H: h, Y: 150 - h, Label: i%3 == 0 || i == len(ms)-1}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// metricsStart sets the month the metrics count from.
|
||||
func (s *Server) metricsStart(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := metrics.SetStartMonth(s.DB, strings.TrimSpace(r.PostFormValue("month"))); err != nil {
|
||||
s.renderMetrics(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics", "saved")
|
||||
}
|
||||
|
||||
// metricsMonth shows one month's moves, customer by customer.
|
||||
func (s *Server) metricsMonth(w http.ResponseWriter, r *http.Request) {
|
||||
model, err := metrics.Build(s.DB, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
month := r.PathValue("month")
|
||||
mo := model.Find(month)
|
||||
if mo == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
names, err := metrics.CustomerNames(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.render(w, r, "metrics-month", page{Title: "MRR in " + month, Nav: "metrics/overview", Data: map[string]any{
|
||||
"M": mo, "Changes": model.Changes(month, names),
|
||||
}})
|
||||
}
|
||||
|
||||
// metricsMargins saves the gross margins: the default, and per product (an
|
||||
// empty box uses the default).
|
||||
func (s *Server) metricsMargins(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
parse := func(v string) (float64, bool, error) {
|
||||
v = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(v), "%"))
|
||||
if v == "" {
|
||||
return 0, false, nil
|
||||
}
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
return f, true, err
|
||||
}
|
||||
m := metrics.Margins{ByProduct: map[string]float64{}}
|
||||
def, ok, err := parse(r.PostFormValue("default"))
|
||||
if err != nil || !ok {
|
||||
s.renderMetrics(w, r, "Give the default margin as a percentage.")
|
||||
return
|
||||
}
|
||||
m.Default = def
|
||||
for key, vals := range r.PostForm {
|
||||
id, isProduct := strings.CutPrefix(key, "margin:")
|
||||
if !isProduct || len(vals) == 0 {
|
||||
continue
|
||||
}
|
||||
v, set, err := parse(vals[0])
|
||||
if err != nil {
|
||||
s.renderMetrics(w, r, "A margin isn't a number: "+vals[0])
|
||||
return
|
||||
}
|
||||
if set {
|
||||
m.ByProduct[id] = v
|
||||
}
|
||||
}
|
||||
if err := metrics.SaveMargins(s.DB, m); err != nil {
|
||||
s.renderMetrics(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics#margins", "saved")
|
||||
}
|
||||
|
||||
// metricsSync syncs Stripe now; "full" reads everything again.
|
||||
func (s *Server) metricsSync(w http.ResponseWriter, r *http.Request) {
|
||||
c := s.stripe()
|
||||
if c == nil {
|
||||
s.renderMetrics(w, r, "Save a Stripe key under Settings → Website & sales first.")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
|
||||
defer cancel()
|
||||
if _, err := metrics.Sync(ctx, s.DB, c, time.Now(), r.PostFormValue("full") == "1"); err != nil {
|
||||
s.renderMetrics(w, r, "Syncing Stripe: "+err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics", "synced")
|
||||
}
|
||||
|
||||
// RunMetrics syncs Stripe every hour.
|
||||
func (s *Server) RunMetrics(ctx context.Context) {
|
||||
tick := time.NewTicker(10 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if c := s.stripe(); c != nil {
|
||||
if _, err := metrics.SyncOutsideSpend(s.DB, time.Now()); err != nil {
|
||||
s.Log.Warn("metrics: outside spend", "err", err)
|
||||
}
|
||||
last := metrics.LastSync(s.DB)
|
||||
if last == nil || time.Since(last.At) >= time.Hour {
|
||||
sctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||
if _, err := metrics.Sync(sctx, s.DB, c, time.Now(), false); err != nil && !errors.Is(err, context.Canceled) {
|
||||
s.Log.Warn("metrics: Stripe sync", "err", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Stripe customers and CRM Accounts ---
|
||||
|
||||
func (s *Server) metricsCustomers(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderCustomers(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderCustomers(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
model, err := metrics.Build(s.DB, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
all, err := metrics.Matches(s.DB, model)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
show := r.URL.Query().Get("show")
|
||||
var shown []metrics.Match
|
||||
for _, m := range all {
|
||||
open := m.How == metrics.MatchNone || m.How == metrics.MatchAmbiguous
|
||||
if show == "all" || (show == "" && open) || (show == "paying" && m.MRR > 0) {
|
||||
shown = append(shown, m)
|
||||
}
|
||||
}
|
||||
accounts, err := metrics.Accounts(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
counts, _ := crm.RecordCounts(s.DB)
|
||||
sync, _ := crm.LoadSync(s.DB)
|
||||
queued := map[string]bool{}
|
||||
if acts, err := crm.List(s.DB, 1000); err == nil {
|
||||
for _, a := range acts {
|
||||
if strings.HasPrefix(a.Key, "stripe-customer:") && a.Status != "cancelled" {
|
||||
queued[strings.TrimPrefix(a.Key, "stripe-customer:")] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
s.render(w, r, "metrics-customers", page{Title: "Customers and the CRM", Nav: "metrics/customers", Error: errMsg, Data: map[string]any{
|
||||
"Matches": shown, "Total": len(all), "Summary": metrics.MatchSummary(all), "Accounts": accounts,
|
||||
"CRMCount": counts["Account"], "Synced": sync.Last, "Show": show, "Queued": queued,
|
||||
}})
|
||||
}
|
||||
|
||||
// metricsCustomerMatch handles a customer's buttons: choose an Account, say
|
||||
// it isn't in the CRM, go back to automatic, or add it to the CRM.
|
||||
func (s *Server) metricsCustomerMatch(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cust := r.PathValue("id")
|
||||
if !strings.HasPrefix(cust, "cus_") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
var err error
|
||||
switch r.PostFormValue("do") {
|
||||
case "account":
|
||||
acc := strings.TrimSpace(r.PostFormValue("account"))
|
||||
// The box takes a name; find its Account.
|
||||
if accounts, aerr := metrics.Accounts(s.DB); aerr == nil {
|
||||
for _, a := range accounts {
|
||||
if strings.EqualFold(a.Name, acc) || a.ID == acc {
|
||||
acc = a.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
if acc == "" {
|
||||
err = errors.New("choose an Account")
|
||||
} else {
|
||||
err = metrics.SetMatch(s.DB, cust, acc, false, now)
|
||||
}
|
||||
case "none":
|
||||
err = metrics.SetMatch(s.DB, cust, "", false, now)
|
||||
case "auto":
|
||||
err = metrics.SetMatch(s.DB, cust, "", true, now)
|
||||
case "add":
|
||||
err = s.queueAccount(cust)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.renderCustomers(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics/customers?show="+r.PostFormValue("show"), "saved")
|
||||
}
|
||||
|
||||
// queueAccount asks Hermes to add a paying Stripe customer to the CRM as an
|
||||
// Account (and remembers the match once it exists).
|
||||
func (s *Server) queueAccount(cust string) error {
|
||||
names, err := metrics.CustomerNames(s.DB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c, ok := names[cust]
|
||||
if !ok {
|
||||
return errors.New("no such customer")
|
||||
}
|
||||
name := c.Name
|
||||
if name == "" {
|
||||
name = c.Email
|
||||
}
|
||||
if name == "" {
|
||||
return errors.New("the customer has no name or email to create an Account from")
|
||||
}
|
||||
fields := map[string]any{"name": name, "description": "Added by Supermarket: a paying Stripe customer (" + cust + ")."}
|
||||
match := map[string]string{"name": name}
|
||||
if dom := crm.EmailDomain(c.Email); dom != "" && !crm.IsFreeMail(dom) {
|
||||
fields["website"] = "https://" + dom
|
||||
match = map[string]string{"website": "https://" + dom}
|
||||
}
|
||||
if c.Email != "" {
|
||||
fields["emailAddress"] = c.Email
|
||||
}
|
||||
_, err = crm.Enqueue(s.DB, crm.Action{Key: "stripe-customer:" + cust, Entity: "Account", Fields: fields, Match: match, Origin: "stripe-customer:" + cust})
|
||||
return err
|
||||
}
|
||||
|
||||
// --- Spend and CAC ---
|
||||
|
||||
func (s *Server) metricsSpend(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderSpend(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSpend(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
model, err := metrics.Build(s.DB, time.Now())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
names, err := metrics.CustomerNames(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
cac, err := metrics.BuildCAC(s.DB, model, names)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
log, err := metrics.SpendLog(s.DB, 200)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
months := cac.Months
|
||||
if len(months) > 13 {
|
||||
months = months[:13]
|
||||
}
|
||||
s.render(w, r, "metrics-spend", page{Title: "Spend and CAC", Nav: "metrics/spend", Error: errMsg, Data: map[string]any{
|
||||
"CAC": cac, "Months": months, "Log": log, "Channels": metrics.SpendChannels(), "This": time.Now().Format("2006-01"),
|
||||
}})
|
||||
}
|
||||
|
||||
// metricsSpendAdd logs spend, or imports a CSV.
|
||||
func (s *Server) metricsSpendAdd(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
if csvText := strings.TrimSpace(r.PostFormValue("csv")); csvText != "" {
|
||||
n, err := metrics.ImportSpendCSV(s.DB, strings.NewReader(csvText), now)
|
||||
if err != nil {
|
||||
s.renderSpend(w, r, "Nothing imported: "+err.Error())
|
||||
return
|
||||
}
|
||||
s.Log.Info("metrics: spend imported", "rows", n)
|
||||
redirect(w, r, "/metrics/spend", "imported")
|
||||
return
|
||||
}
|
||||
cents, err := metrics.ParseAmount(r.PostFormValue("amount"))
|
||||
if err == nil {
|
||||
err = metrics.AddSpend(s.DB, metrics.Spend{Month: strings.TrimSpace(r.PostFormValue("month")), Channel: r.PostFormValue("channel"),
|
||||
AmountCents: cents, Note: r.PostFormValue("note")}, now)
|
||||
}
|
||||
if err != nil {
|
||||
s.renderSpend(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics/spend", "saved")
|
||||
}
|
||||
|
||||
func (s *Server) metricsSpendDelete(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := metrics.DeleteSpend(s.DB, id); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/metrics/spend", "deleted")
|
||||
}
|
||||
|
||||
// --- CLV and cohorts ---
|
||||
|
||||
func (s *Server) metricsCLV(w http.ResponseWriter, r *http.Request) {
|
||||
now := time.Now()
|
||||
model, err := metrics.Build(s.DB, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
clv, err := metrics.BuildCLV(s.DB, model, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
cohorts, err := metrics.RevenueByCohort(s.DB, model, 18, 12, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.render(w, r, "metrics-clv", page{Title: "CLV and cohorts", Nav: "metrics/clv", Data: map[string]any{
|
||||
"CLV": clv, "Cohorts": cohorts, "Span": make([]int, 13), "Profit": r.URL.Query().Get("view") == "profit",
|
||||
"Currency": model.Currency,
|
||||
}})
|
||||
}
|
||||
|
||||
// --- CSV export and the open metrics page ---
|
||||
|
||||
func (s *Server) metricsExport(w http.ResponseWriter, r *http.Request) {
|
||||
name := strings.TrimSuffix(r.PathValue("name"), ".csv")
|
||||
known := false
|
||||
for _, e := range metrics.Exports {
|
||||
known = known || e.Name == name
|
||||
}
|
||||
if !known {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-`+name+`-`+time.Now().Format("2006-01-02")+`.csv"`)
|
||||
if err := metrics.Export(w, s.DB, name, time.Now()); err != nil {
|
||||
s.Log.Error("metrics: export", "table", name, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// publishOptions are the open metrics page's settings.
|
||||
type publishOptions struct {
|
||||
Site int `json:"site"`
|
||||
Path string `json:"path"`
|
||||
Title string `json:"title"`
|
||||
Parts map[string]bool `json:"parts"`
|
||||
PRURL string `json:"pr_url"`
|
||||
PRAt time.Time `json:"pr_at"`
|
||||
}
|
||||
|
||||
const publishKey = "metrics:publish"
|
||||
|
||||
func (s *Server) publishOptions() publishOptions {
|
||||
o := publishOptions{Path: "/metrics/", Title: "Open metrics", Parts: map[string]bool{"mrr": true, "customers": true, "growth": true, "nrr": true}}
|
||||
_, _ = s.DB.GetJSON(publishKey, &o)
|
||||
return o
|
||||
}
|
||||
|
||||
func (s *Server) metricsPublishPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderPublish(w, r, s.publishOptions(), "")
|
||||
}
|
||||
|
||||
func (s *Server) renderPublish(w http.ResponseWriter, r *http.Request, o publishOptions, errMsg string) {
|
||||
now := time.Now()
|
||||
model, err := metrics.Build(s.DB, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
clv, err := metrics.BuildCLV(s.DB, model, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.render(w, r, "metrics-publish", page{Title: "Publish metrics", Nav: "metrics/publish", Error: errMsg, Data: map[string]any{
|
||||
"O": o, "Parts": metrics.PublicParts, "Sites": s.seoSites(), "Gitea": s.gitea() != nil,
|
||||
"Preview": metrics.PublicPage(model, clv, o.Parts, now),
|
||||
}})
|
||||
}
|
||||
|
||||
// metricsPublish saves the page's settings, and with "pr" opens the pull
|
||||
// request.
|
||||
func (s *Server) metricsPublish(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
o := s.publishOptions()
|
||||
o.Site, _ = strconv.Atoi(r.PostFormValue("site"))
|
||||
o.Path = strings.TrimSpace(r.PostFormValue("path"))
|
||||
o.Title = strings.TrimSpace(r.PostFormValue("title"))
|
||||
o.Parts = map[string]bool{}
|
||||
for _, p := range r.PostForm["part"] {
|
||||
o.Parts[p] = true
|
||||
}
|
||||
if o.Path == "" || o.Title == "" {
|
||||
s.renderPublish(w, r, o, "Give the page an address and a title.")
|
||||
return
|
||||
}
|
||||
if r.PostFormValue("do") == "pr" {
|
||||
var site *seoSite
|
||||
for _, st := range s.seoSites() {
|
||||
if st.Index == o.Site {
|
||||
site = &st
|
||||
}
|
||||
}
|
||||
if site == nil {
|
||||
s.renderPublish(w, r, o, "Choose a website.")
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
model, err := metrics.Build(s.DB, now)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
clv, _ := metrics.BuildCLV(s.DB, model, now)
|
||||
body := metrics.PublicPage(model, clv, o.Parts, now)
|
||||
if body == "" {
|
||||
s.renderPublish(w, r, o, "There's no complete month of billing to publish yet.")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
|
||||
defer cancel()
|
||||
pr, _, err := s.applier(*site).PublishPage(ctx, o.Path, o.Title, "Our revenue numbers, straight from our billing.", body,
|
||||
"Proposed by Supermarket: the open metrics page, with totals only (nothing about any one customer).")
|
||||
if err != nil {
|
||||
s.renderPublish(w, r, o, "Couldn't open the pull request: "+err.Error())
|
||||
return
|
||||
}
|
||||
o.PRURL, o.PRAt = pr.HTMLURL, now
|
||||
}
|
||||
if err := s.DB.PutJSON(publishKey, o); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
msg := "saved"
|
||||
if r.PostFormValue("do") == "pr" {
|
||||
msg = "setup-opened"
|
||||
}
|
||||
redirect(w, r, "/metrics/publish", msg)
|
||||
}
|
||||
+36
-2
@@ -7,6 +7,7 @@ import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"supermarket/internal/core"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/legacy"
|
||||
"supermarket/internal/metrics"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
@@ -159,6 +161,20 @@ 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 /metrics", s.metricsPage)
|
||||
mux.HandleFunc("POST /metrics/sync", s.metricsSync)
|
||||
mux.HandleFunc("POST /metrics/margins", s.metricsMargins)
|
||||
mux.HandleFunc("POST /metrics/start", s.metricsStart)
|
||||
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
|
||||
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
|
||||
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
|
||||
mux.HandleFunc("GET /metrics/clv", s.metricsCLV)
|
||||
mux.HandleFunc("GET /metrics/export/{name}", s.metricsExport)
|
||||
mux.HandleFunc("GET /metrics/publish", s.metricsPublishPage)
|
||||
mux.HandleFunc("POST /metrics/publish", s.metricsPublish)
|
||||
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
|
||||
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
|
||||
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
|
||||
mux.HandleFunc("GET /seo", s.seoPage)
|
||||
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
|
||||
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
|
||||
@@ -302,7 +318,25 @@ func (s *Server) loadTemplates() error {
|
||||
},
|
||||
"xreserve": twitter.URLReserve,
|
||||
// money shows cents as dollars: $1,234 or $12.50.
|
||||
"money": money,
|
||||
"money": money,
|
||||
// usd shows float cents as whole dollars: $9,835.
|
||||
"usd": func(cents float64) string { return money(int64(math.Round(cents/100)) * 100) },
|
||||
"mul12": func(f float64) float64 { return 12 * f },
|
||||
"sub": func(a, b float64) float64 { return a - b },
|
||||
"pct": func(f float64) string {
|
||||
if f < 0 {
|
||||
return "·"
|
||||
}
|
||||
return strconv.FormatFloat(f, 'f', 0, 64) + "%"
|
||||
},
|
||||
"spendChannel": metrics.ChannelName,
|
||||
"dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
||||
"cents": func(f float64) string {
|
||||
if f < 0 {
|
||||
return "·"
|
||||
}
|
||||
return money(int64(math.Round(f)))
|
||||
},
|
||||
"num": seo.Thousands,
|
||||
"cls": func(x100 int) float64 { return float64(x100) / 100 },
|
||||
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
||||
@@ -378,7 +412,7 @@ var modules = []module{
|
||||
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
|
||||
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
|
||||
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"},
|
||||
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
|
||||
{"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"},
|
||||
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
|
||||
}
|
||||
|
||||
|
||||
@@ -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", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
|
||||
"/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", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish",
|
||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
@@ -436,3 +436,12 @@ table.runs { margin-top: 0.75rem; }
|
||||
.checks li, .list td .small, .list td a { overflow-wrap: anywhere; }
|
||||
|
||||
textarea.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9rem; }
|
||||
|
||||
/* Metrics */
|
||||
svg.chart { width: 100%; height: auto; margin: 0.75rem 0 0.25rem; }
|
||||
svg.chart rect { fill: hsl(var(--primary)); opacity: 0.85; }
|
||||
svg.chart rect:hover { opacity: 1; }
|
||||
svg.chart text { font-size: 9px; fill: hsl(var(--muted-foreground)); }
|
||||
table.cohorts td, table.cohorts th { padding-left: 0.4rem; padding-right: 0.4rem; font-size: 0.85rem; }
|
||||
.table-wrap { overflow-x: auto; }
|
||||
table.compact th, table.compact td { white-space: nowrap; padding-left: 0.5rem; padding-right: 0.5rem; font-size: 0.85rem; }
|
||||
|
||||
@@ -50,6 +50,15 @@
|
||||
<a href="/seo/engines" {{if eq $nav "seo/engines"}}aria-current="page"{{end}}>Search engines</a>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq .ID "metrics"}}
|
||||
<div class="subnav">
|
||||
<a href="/metrics" {{if eq $nav "metrics/overview"}}aria-current="page"{{end}}>MRR and NRR</a>
|
||||
<a href="/metrics/spend" {{if eq $nav "metrics/spend"}}aria-current="page"{{end}}>Spend and CAC</a>
|
||||
<a href="/metrics/clv" {{if eq $nav "metrics/clv"}}aria-current="page"{{end}}>CLV and cohorts</a>
|
||||
<a href="/metrics/customers" {{if eq $nav "metrics/customers"}}aria-current="page"{{end}}>Customers and the CRM</a>
|
||||
<a href="/metrics/publish" {{if eq $nav "metrics/publish"}}aria-current="page"{{end}}>Publish</a>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq .ID "prospects"}}
|
||||
<div class="subnav">
|
||||
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading"><h1>CLV and cohorts</h1></div>
|
||||
<p class="lede">What a customer is worth over their life with you, and what each signup cohort has actually paid. CLV is a projection from today's numbers; the cohort table is money that came in, net of refunds and credits.</p>
|
||||
|
||||
{{with .CLV}}
|
||||
<section class="card">
|
||||
<h2>Customer lifetime value <span class="muted small">measured on {{.Month}}</span></h2>
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">CLV</span><strong>{{cents .Value}}</strong><span class="rate">gross profit per customer</span></div>
|
||||
<div class="step"><span class="label">CAC, 12 months</span><strong>{{cents .CAC}}</strong></div>
|
||||
<div class="step"><span class="label">CLV : CAC</span><strong>{{if ge .Ratio 0.0}}{{dec1f .Ratio}} : 1{{else}}·{{end}}</strong><span class="rate">3 : 1 or more is healthy</span></div>
|
||||
<div class="step"><span class="label">Average per customer</span><strong>{{usd .ARPA}}</strong><span class="rate">a month</span></div>
|
||||
<div class="step"><span class="label">Gross margin</span><strong>{{dec1f .Margin}}%</strong><span class="rate">weighted by product</span></div>
|
||||
<div class="step"><span class="label">Churn</span><strong>{{dec1f .Churn}}%</strong><span class="rate">of customers a month, {{.ChurnMonths}}-month average</span></div>
|
||||
<div class="step"><span class="label">Lifetime</span><strong>{{if .Lifetime}}{{dec1f .Lifetime}}{{else}}·{{end}}</strong><span class="rate">months, on average</span></div>
|
||||
</div>
|
||||
<p class="small muted">CLV = average MRR per customer × gross margin ÷ monthly churn. The margin weighs each product's margin (set on <a href="/metrics#margins">MRR and NRR</a>) by what it billed over 12 months. CAC is the spend logged over the same 12 months ÷ the new customers in them{{if lt .CAC 0.0}}: <a href="/metrics/spend">log your spend</a> to see it{{end}}.</p>
|
||||
</section>
|
||||
{{else}}
|
||||
<section class="card empty"><p>CLV needs at least two complete months of billing from Stripe.</p></section>
|
||||
{{end}}
|
||||
|
||||
{{if .Cohorts}}
|
||||
<h2>Revenue by cohort</h2>
|
||||
<p class="help">Customers by the month they first paid, and what they've paid since, per customer, cumulative: invoices paid, less refunds and credits. Month 0 is the month they first paid.</p>
|
||||
<nav class="tabs">
|
||||
<a href="/metrics/clv" {{if not .Profit}}aria-current="page"{{end}}>Revenue</a>
|
||||
<a href="/metrics/clv?view=profit" {{if .Profit}}aria-current="page"{{end}}>Gross profit</a>
|
||||
</nav>
|
||||
<div class="table-wrap"><table class="list compact cohorts">
|
||||
<thead><tr><th>First paid</th><th class="num">Customers</th>{{range $i, $_ := .Span}}<th class="num">{{$i}}</th>{{end}}</tr></thead>
|
||||
<tbody>{{range .Cohorts}}<tr><td>{{.Month}}</td><td class="num">{{.Customers}}</td>
|
||||
{{if $d.Profit}}{{range .Margin}}<td class="num">{{if .Known}}{{usd .V}}{{end}}</td>{{end}}{{else}}{{range .PerCustomer}}<td class="num">{{if .Known}}{{usd .V}}{{end}}</td>{{end}}{{end}}
|
||||
</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
<p class="small"><a href="/metrics/export/cohort-revenue.csv">Download as CSV</a> (every cohort, 24 months)</p>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,52 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading"><h1>Customers and the CRM</h1></div>
|
||||
<p class="lede">Each Stripe customer with billing, matched to its EspoCRM Account: first by a stored ID (a Stripe customer ID in the Account, or an EspoCRM ID in Stripe's metadata), then by email (the Account's, or one of its Contacts'), then by the email's domain (free mail like Gmail doesn't count). Fix what it gets wrong; your choice is kept. Pipeline influence and per-account numbers build on this.</p>
|
||||
|
||||
<section class="card">
|
||||
{{if not .CRMCount}}
|
||||
<p class="warn-text">No CRM Accounts copied yet, so nothing can be matched. Hermes copies them once the CRM bridge works (see <a href="/crm">CRM queue</a>); until then you can say which customers aren't in the CRM, or queue them to be added.</p>
|
||||
{{else}}<p class="small muted">{{num .CRMCount}} Accounts copied from the CRM{{if not .Synced.IsZero}} {{ago .Synced}}{{end}}.</p>{{end}}
|
||||
{{$s := .Summary}}
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">Customers</span><strong>{{num .Total}}</strong></div>
|
||||
<div class="step"><span class="label">By stored ID</span><strong>{{or (index $s "stored ID") 0}}</strong></div>
|
||||
<div class="step"><span class="label">By email</span><strong>{{or (index $s "email") 0}}</strong></div>
|
||||
<div class="step"><span class="label">By domain</span><strong>{{or (index $s "domain") 0}}</strong></div>
|
||||
<div class="step"><span class="label">By you</span><strong>{{or (index $s "by you") 0}}</strong></div>
|
||||
<div class="step"><span class="label">To choose</span><strong>{{or (index $s "several") 0}}</strong></div>
|
||||
<div class="step"><span class="label">No match</span><strong>{{or (index $s "") 0}}</strong></div>
|
||||
<div class="step"><span class="label">Not in the CRM</span><strong>{{or (index $s "not in the CRM") 0}}</strong></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="small"><a href="/metrics/export/customers.csv">Download every customer as CSV</a></p>
|
||||
<nav class="tabs">
|
||||
<a href="/metrics/customers" {{if eq .Show ""}}aria-current="page"{{end}}>To fix</a>
|
||||
<a href="/metrics/customers?show=paying" {{if eq .Show "paying"}}aria-current="page"{{end}}>Paying now</a>
|
||||
<a href="/metrics/customers?show=all" {{if eq .Show "all"}}aria-current="page"{{end}}>All</a>
|
||||
</nav>
|
||||
|
||||
<datalist id="accounts">{{range .Accounts}}<option value="{{.Name}}">{{.Domain}}</option>{{end}}</datalist>
|
||||
{{if .Matches}}
|
||||
<div class="table-wrap"><table class="list compact">
|
||||
<thead><tr><th>Customer</th><th class="num">MRR now</th><th>Account</th><th></th></tr></thead>
|
||||
<tbody>{{range .Matches}}<tr>
|
||||
<td>{{or .Customer.Name .Customer.Email .Customer.ID}}{{if and .Customer.Name .Customer.Email}}<br><span class="muted small">{{.Customer.Email}}</span>{{end}}{{if .Prospect}}<br><span class="badge">a prospect</span>{{end}}</td>
|
||||
<td class="num">{{if .MRR}}{{usd .MRR}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td>{{if .Account.ID}}{{.Account.Name}} <span class="muted small">{{.How}}</span>
|
||||
{{else if eq .How "several"}}<span class="warn-text small">Several fit:</span> {{range $i, $a := .Candidates}}{{if $i}}, {{end}}{{$a.Name}}{{end}}
|
||||
{{else if eq .How "not in the CRM"}}<span class="muted">not in the CRM</span>
|
||||
{{else}}<span class="muted">no match</span>{{if index $d.Queued .Customer.ID}} <span class="badge draft">queued for the CRM</span>{{end}}{{end}}</td>
|
||||
<td>
|
||||
<form method="post" action="/metrics/customers/{{.Customer.ID}}" class="row wrap">
|
||||
<input type="hidden" name="show" value="{{$d.Show}}">
|
||||
{{if $d.Accounts}}<input name="account" list="accounts" placeholder="an Account" size="16"><button type="submit" name="do" value="account" class="secondary small">Match</button>{{end}}
|
||||
{{if or .Account.ID (eq .How "not in the CRM")}}{{if or (eq .How "by you") (eq .How "not in the CRM")}}<button type="submit" name="do" value="auto" class="link small">automatic</button>{{end}}
|
||||
{{else}}<button type="submit" name="do" value="none" class="link small">not in the CRM</button>
|
||||
{{if and .MRR (not (index $d.Queued .Customer.ID))}}<button type="submit" name="do" value="add" class="link small">add to the CRM</button>{{end}}{{end}}
|
||||
</form>
|
||||
</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
{{else}}<section class="card empty"><p>{{if eq .Show ""}}Nothing to fix.{{else}}No customers.{{end}}</p></section>{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,17 @@
|
||||
{{define "content"}}{{with .Data}}{{$m := .M}}
|
||||
<div class="heading">
|
||||
<h1>MRR in {{$m.Month}}</h1>
|
||||
<div class="buttons"><a class="button secondary" href="/metrics">Metrics</a></div>
|
||||
</div>
|
||||
<p class="lede">{{usd $m.MRR}} from {{num $m.Customers}} customers{{if $m.Partial}}, so far this month{{end}}. Net change {{usd $m.NetNew}}: new {{usd $m.New}}, expansion {{usd $m.Expansion}}, reactivation {{usd $m.Reactivation}}, contraction −{{usd $m.Contraction}}, churn −{{usd $m.Churn}}.</p>
|
||||
{{if .Changes}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Customer</th><th>Movement</th><th class="num">MRR before</th><th class="num">After</th><th class="num">Change</th></tr></thead>
|
||||
<tbody>{{range .Changes}}<tr>
|
||||
<td>{{or .Customer.Name .Customer.Email .Customer.ID}}{{if and .Customer.Name .Customer.Email}} <span class="muted small">{{.Customer.Email}}</span>{{end}}</td>
|
||||
<td><span class="badge {{if or (eq .Kind "churn") (eq .Kind "contraction")}}failed{{else}}published{{end}}">{{.Kind}}</span></td>
|
||||
<td class="num">{{usd .Before}}</td><td class="num">{{usd .After}}</td><td class="num">{{usd (sub .After .Before)}}</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{else}}<p class="help">No customer moved this month.</p>{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,23 @@
|
||||
{{define "content"}}{{with .Data}}{{$o := .O}}
|
||||
<div class="heading"><h1>Publish your metrics</h1></div>
|
||||
<p class="lede">An "open metrics" page on your website: your revenue numbers, straight from billing, for customers and investors who like seeing a company's real numbers. Only totals are published, never anything about any one customer. It goes to the site as a pull request, like the SEO changes; merging publishes it. Open it again whenever you want the numbers updated.</p>
|
||||
|
||||
<form method="post" action="/metrics/publish" class="card">
|
||||
<div class="cols">
|
||||
<label>Website <select name="site">{{range .Sites}}<option value="{{.Index}}" {{if eq .Index $o.Site}}selected{{end}}>{{.URL}}</option>{{end}}</select></label>
|
||||
<label>Address on the site <input name="path" value="{{$o.Path}}"></label>
|
||||
</div>
|
||||
<label>Title <input name="title" value="{{$o.Title}}"></label>
|
||||
<fieldset><legend>What to show</legend>
|
||||
{{range .Parts}}<label class="check"><input type="checkbox" name="part" value="{{.ID}}" {{if index $o.Parts .ID}}checked{{end}}> {{.Label}}</label>{{end}}
|
||||
</fieldset>
|
||||
<div class="actions">
|
||||
<button type="submit" class="secondary" name="do" value="save">Save and preview</button>
|
||||
<button type="submit" name="do" value="pr" data-busy="Opening…" {{if not .Gitea}}disabled title="Save a Gitea token under Settings → Search engines"{{end}}>Open a pull request</button>
|
||||
</div>
|
||||
{{with $o.PRURL}}<p class="small">Last opened {{ago $o.PRAt}}: <a href="{{.}}" target="_blank" rel="noopener noreferrer">the pull request ↗</a></p>{{end}}
|
||||
</form>
|
||||
|
||||
<h2>Preview</h2>
|
||||
{{if .Preview}}<pre class="sample">{{.Preview}}</pre>{{else}}<p class="help">There's no complete month of billing to publish yet.</p>{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,52 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading"><h1>Spend and CAC</h1></div>
|
||||
<p class="lede">What it costs to win a paying customer: the month's marketing and sales spend over the customers who first paid that month. Stripe has no spend, so log it here: by hand, from a CSV, or automatically for origami.chat and explee.com campaigns. Channel CAC uses each new customer's first step in the funnel (a reply, a visit, an outreach email…), matched by email.</p>
|
||||
|
||||
<section class="card">
|
||||
<h2>CAC by month</h2>
|
||||
<div class="table-wrap"><table class="list compact">
|
||||
<thead><tr><th>Month</th><th class="num">Spend</th><th class="num">New customers</th><th class="num">CAC</th><th class="num">CAC, 3 months</th></tr></thead>
|
||||
<tbody>{{range .Months}}<tr><td>{{.Month}}</td><td class="num">{{if .Spend}}{{money .Spend}}{{else}}<span class="muted">·</span>{{end}}</td><td class="num">{{.New}}</td>
|
||||
<td class="num">{{if .Spend}}{{cents .CAC}}{{else}}<span class="muted">no spend logged</span>{{end}}</td><td class="num">{{cents .Trailing3}}</td></tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
<p class="help">One month's CAC swings with a handful of customers; the three-month figure is steadier. <a href="/metrics/export/cac.csv">Download as CSV</a></p>
|
||||
</section>
|
||||
|
||||
{{with .CAC.Channels}}
|
||||
<section class="card">
|
||||
<h2>By channel, last 12 months</h2>
|
||||
<table class="list compact">
|
||||
<thead><tr><th>Channel</th><th class="num">Spend</th><th class="num">New customers</th><th class="num">CAC</th></tr></thead>
|
||||
<tbody>{{range .}}<tr><td>{{spendChannel .Channel}}</td><td class="num">{{money .Spend}}</td><td class="num">{{.New}}</td><td class="num">{{cents .CAC}}</td></tr>{{end}}</tbody>
|
||||
</table>
|
||||
<p class="help">{{if $d.CAC.Unknown}}{{$d.CAC.Unknown}} new customers had no step in the funnel before paying, so their channel is unknown. {{end}}General spend counts in the monthly CAC, not in any one channel's. <a href="/metrics/export/cac-channels.csv">Download as CSV</a></p>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<form method="post" action="/metrics/spend" class="card">
|
||||
<h2>Log spend</h2>
|
||||
<div class="row wrap">
|
||||
<label class="small">Month <input name="month" value="{{.This}}" size="8" placeholder="YYYY-MM"></label>
|
||||
<label class="small">Channel <select name="channel">{{range .Channels}}<option value="{{.ID}}">{{.Label}}</option>{{end}}</select></label>
|
||||
<label class="small">Amount <input name="amount" inputmode="decimal" size="9" placeholder="e.g. 250"></label>
|
||||
<label class="small grow">Note <input name="note" placeholder="optional: what it was"></label>
|
||||
<button type="submit" class="small">Add</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form method="post" action="/metrics/spend" class="card">
|
||||
<h2>Import from CSV</h2>
|
||||
<p class="help">Paste rows of <code>month,channel,amount,note</code>, e.g. <code>2026-10,LinkedIn,320,ads</code>. A header row is skipped; nothing is added unless every row is good.</p>
|
||||
<textarea name="csv" rows="4" class="mono" placeholder="month,channel,amount,note"></textarea>
|
||||
<div class="actions"><button type="submit" class="secondary small">Import</button></div>
|
||||
</form>
|
||||
|
||||
{{if .Log}}
|
||||
<h2>The log <a class="small" href="/metrics/export/spend.csv">Download as CSV</a></h2>
|
||||
<table class="list compact">
|
||||
<thead><tr><th>Month</th><th>Channel</th><th class="num">Amount</th><th>Note</th><th>From</th><th></th></tr></thead>
|
||||
<tbody>{{range .Log}}<tr><td>{{.Month}}</td><td>{{spendChannel .Channel}}</td><td class="num">{{money .AmountCents}}</td><td class="small">{{.Note}}</td><td class="small muted">{{.Source}}</td>
|
||||
<td><form method="post" action="/metrics/spend/{{.ID}}/delete" data-confirm="Delete this entry?"><button type="submit" class="link small">delete</button></form></td></tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,114 @@
|
||||
{{define "content"}}{{with .Data}}
|
||||
<div class="heading">
|
||||
<h1>Metrics</h1>
|
||||
{{if .Stripe}}<div class="buttons">
|
||||
<form method="post" action="/metrics/sync" data-busy="Syncing…"><button type="submit" class="secondary">Sync now</button></form>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
<p class="lede">MRR and its movements, NRR, CAC and CLV, computed from your Stripe data: every customer, invoice, credit note and refund. MRR comes from the invoice lines (what each customer was billed, for which period), so past months are exact. Supermarket only reads Stripe.</p>
|
||||
|
||||
{{with .Now}}{{$d := $.Data}}
|
||||
{{with $d.Model.Suggest}}
|
||||
<section class="card">
|
||||
<p class="warn-text">In {{.Month}}, {{.Customers}} customers ({{usd .MRR}} of MRR) appear in Stripe at once. That usually means billing moved to Stripe then, not that they all signed up that month. Counting from {{.Month}} makes them the starting base instead of new customers.</p>
|
||||
<div class="row">
|
||||
<form method="post" action="/metrics/start"><input type="hidden" name="month" value="{{.Month}}"><button type="submit" class="small">Count from {{.Month}}</button></form>
|
||||
<form method="post" action="/metrics/start"><input type="hidden" name="month" value="all"><button type="submit" class="secondary small">Keep counting everything</button></form>
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<section class="card">
|
||||
<h2>MRR {{if .Partial}}<span class="muted small">today</span>{{else}}<span class="muted small">at the end of {{.Month}}</span>{{end}}</h2>
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">MRR</span><strong>{{usd .MRR}}</strong><span class="rate">ARR {{usd (mul12 .MRR)}}</span></div>
|
||||
<div class="step"><span class="label">Paying customers</span><strong>{{num .Customers}}</strong></div>
|
||||
<div class="step"><span class="label">Average per customer</span><strong>{{usd .ARPA}}</strong></div>
|
||||
<div class="step"><span class="label">NRR, this month</span><strong>{{pct .NRR}}</strong><span class="rate">of last month's MRR kept</span></div>
|
||||
<div class="step"><span class="label">NRR, 12 months</span><strong>{{pct .NRR12}}</strong><span class="rate">what customers of a year ago pay now</span></div>
|
||||
</div>
|
||||
{{with $d.CLV}}
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">Churn</span><strong>{{dec1f .Churn}}%</strong><span class="rate">of customers a month</span></div>
|
||||
<div class="step"><span class="label">CLV</span><strong>{{cents .Value}}</strong><span class="rate">gross profit per customer</span></div>
|
||||
<div class="step"><span class="label">CAC</span><strong>{{cents .CAC}}</strong><span class="rate">{{if lt .CAC 0.0}}<a href="/metrics/spend">log spend</a>{{else}}12 months{{end}}</span></div>
|
||||
<div class="step"><span class="label">CLV : CAC</span><strong>{{if ge .Ratio 0.0}}{{dec1f .Ratio}} : 1{{else}}·{{end}}</strong></div>
|
||||
</div>
|
||||
{{end}}
|
||||
{{with $d.Bars}}
|
||||
<svg class="chart" viewBox="0 0 600 170" role="img" aria-label="MRR by month">
|
||||
{{range .}}<rect x="{{.X}}" y="{{.Y}}" width="{{.W}}" height="{{.H}}"><title>{{.Month}}: {{usd .MRR}}</title></rect>{{if .Label}}<text x="{{.X}}" y="166">{{.Month}}</text>{{end}}{{end}}
|
||||
</svg>
|
||||
{{end}}
|
||||
<p class="small muted">From the invoice lines of paid and open invoices, in {{$d.Model.Currency}}: each recurring line's amount after discounts, spread over its billing period. Trials ($0), one-off charges, void and uncollectible invoices don't count.{{with $d.Model.Start}}{{if ne . "all"}} Counted from {{.}}.{{end}}{{end}}</p>
|
||||
</section>
|
||||
|
||||
<h2>Month by month</h2>
|
||||
<div class="table-wrap"><table class="list compact">
|
||||
<thead><tr><th>Month</th><th class="num">MRR</th><th class="num">Customers</th><th class="num">Net change</th><th class="num">NRR</th><th class="num">New</th><th class="num">Expansion</th><th class="num">Contraction</th><th class="num">Churn</th><th class="num">Reactivation</th></tr></thead>
|
||||
<tbody>{{range $d.Recent}}<tr>
|
||||
<td><a href="/metrics/month/{{.Month}}">{{.Month}}</a>{{if .Partial}} <span class="muted small">so far</span>{{end}}</td>
|
||||
<td class="num">{{usd .MRR}}</td><td class="num">{{num .Customers}}</td>
|
||||
<td class="num"><strong>{{usd .NetNew}}</strong></td>
|
||||
<td class="num">{{pct .NRR}}</td>
|
||||
<td class="num">{{if .New}}{{usd .New}} <span class="muted small">({{.NewCount}})</span>{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td class="num">{{if .Expansion}}{{usd .Expansion}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td class="num">{{if .Contraction}}−{{usd .Contraction}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td class="num">{{if .Churn}}−{{usd .Churn}} <span class="muted small">({{.ChurnCount}})</span>{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
<td class="num">{{if .Reactivation}}{{usd .Reactivation}}{{else}}<span class="muted">·</span>{{end}}</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
<p class="small"><a href="/metrics/export/mrr.csv">Download as CSV</a> (every month)</p>
|
||||
|
||||
{{if $d.Cohorts}}
|
||||
<h2>Cohorts</h2>
|
||||
<p class="help">Customers by the month they first paid, and the share of their first month's MRR they pay each month after: above 100% means they grew.</p>
|
||||
<div class="table-wrap"><table class="list compact cohorts">
|
||||
<thead><tr><th>First paid</th><th class="num">Customers</th><th class="num">Starting MRR</th>{{range $i, $_ := $d.Span}}<th class="num">{{$i}}</th>{{end}}</tr></thead>
|
||||
<tbody>{{range $d.Cohorts}}<tr><td>{{.Month}}</td><td class="num">{{.Customers}}</td><td class="num">{{usd .Start}}</td>{{range .Retained}}<td class="num">{{if ge . 0.0}}{{pct .}}{{end}}</td>{{end}}</tr>{{end}}</tbody>
|
||||
</table></div>
|
||||
<p class="small"><a href="/metrics/export/nrr-cohorts.csv">Download as CSV</a> (every cohort, 24 months)</p>
|
||||
{{end}}
|
||||
|
||||
<form method="post" action="/metrics/start" class="row small">
|
||||
<label class="small">Count from <input name="month" value="{{with $d.Model.Start}}{{if ne . "all"}}{{.}}{{end}}{{end}}" placeholder="YYYY-MM, empty for everything" size="12"></label>
|
||||
<button type="submit" class="secondary small">Save</button>
|
||||
</form>
|
||||
{{end}}
|
||||
|
||||
<section class="card">
|
||||
<h2>Stripe</h2>
|
||||
{{if not .Stripe}}
|
||||
<p class="warn-text">Save a restricted Stripe key under <a href="/settings/tracking#stripe">Settings → Website & sales</a>. For the metrics it needs read access to Customers, Invoices, Credit notes, Charges and Refunds, and Events, on top of Checkout Sessions.</p>
|
||||
{{else}}
|
||||
{{with .Last}}
|
||||
<p class="small {{if .Error}}error-text{{else}}muted{{end}}">Synced {{ago .At}}{{if .Full}} (everything read){{else}} ({{.Events}} changes since the last sync){{end}}{{with .Error}}: {{.}}{{end}}.{{with .Currency}} Currencies: {{range $i, $c := .}}{{if $i}}, {{end}}{{$c}}{{end}}.{{end}}</p>
|
||||
{{else}}<p class="help">Not synced yet: the first sync reads all your Stripe history, which can take a few minutes.</p>{{end}}
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">Customers</span><strong>{{num (or (index .Counts "customer") 0)}}</strong></div>
|
||||
<div class="step"><span class="label">Invoices</span><strong>{{num (or (index .Counts "invoice") 0)}}</strong></div>
|
||||
<div class="step"><span class="label">Credit notes</span><strong>{{num (or (index .Counts "credit_note") 0)}}</strong></div>
|
||||
<div class="step"><span class="label">Refunds</span><strong>{{num (or (index .Counts "refund") 0)}}</strong></div>
|
||||
</div>
|
||||
<form method="post" action="/metrics/sync" data-busy="Reading everything…" class="inline"><input type="hidden" name="full" value="1"><button type="submit" class="link small">Read everything again</button></form>
|
||||
{{with .Last}}{{range .Notes}}<p class="small muted">{{.}}</p>{{end}}{{end}}
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
{{if .Products}}{{$m := .Margins}}
|
||||
<form method="post" action="/metrics/margins" class="card" id="margins">
|
||||
<h2>Gross margin by product</h2>
|
||||
<p class="small">What you keep of each dollar a product brings in, after what it costs you to deliver (hosting, licences, support). CLV weighs each customer's revenue by the margin of what they buy. An empty box uses the default.</p>
|
||||
<label>Default <input name="default" value="{{$m.Default}}" inputmode="decimal" size="5"> %</label>
|
||||
<table class="list">
|
||||
<thead><tr><th>Product</th><th class="num">Billed, last 12 months</th><th class="num">Invoices</th><th class="num">Margin</th></tr></thead>
|
||||
<tbody>{{range .Products}}<tr>
|
||||
<td>{{.Name}}{{if and .ID (ne .Name .ID)}} <span class="muted small">{{.ID}}</span>{{end}}</td>
|
||||
<td class="num">{{money .Revenue}}</td><td class="num">{{num .Invoices}}</td>
|
||||
<td class="num">{{if .ID}}<input name="margin:{{.ID}}" value="{{if .Own}}{{.Margin}}{{end}}" placeholder="{{$m.Default}}" inputmode="decimal" size="5"> %{{else}}<span class="muted">default</span>{{end}}</td>
|
||||
</tr>{{end}}</tbody>
|
||||
</table>
|
||||
<div class="actions"><button type="submit">Save margins</button> <a class="small" href="/metrics/export/products.csv">Download as CSV</a></div>
|
||||
</form>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -19,7 +19,7 @@ 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"}
|
||||
"In Stripe, Developers → API keys → Create restricted key, with Read access only, to Checkout Sessions, Invoices, Customers, Credit notes, Charges and Refunds, and Events (the last four for Metrics). It starts rk_live_.", "https://dashboard.stripe.com/apikeys"}
|
||||
)
|
||||
|
||||
const plausibleURLKey = "tracking:plausible-url"
|
||||
|
||||
Reference in New Issue
Block a user