Phase 14, part 1: plans, each team's account, and their limits
The multi-tenant edition's plans (Free and Paid as decided, or a plans file) and each team's billing account, with a 14-day trial of Paid. A team's plan caps what its people and agents may change: modules outside it stay readable, a lapsed team changes nothing, and agents, Market entries, crawls and background jobs keep to it. Without a Stripe key, no billing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
package billing
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Subscription statuses, as Stripe's (and free: no subscription).
|
||||
const (
|
||||
Trialing = "trialing"
|
||||
Active = "active"
|
||||
PastDue = "past_due"
|
||||
Canceled = "canceled"
|
||||
Free = "free"
|
||||
)
|
||||
|
||||
// How long a lapse lasts before what.
|
||||
const (
|
||||
ReadOnlyAfter = 14 * 24 * time.Hour // past due this long: read-only
|
||||
DeleteAfter = 60 * 24 * time.Hour // past due this long: deleted (Phase 13, part 8)
|
||||
)
|
||||
|
||||
// Account is a team's billing.
|
||||
type Account struct {
|
||||
Team int64
|
||||
Plan string
|
||||
Status string
|
||||
TrialEnds time.Time
|
||||
Customer string
|
||||
Subscription string
|
||||
Seats int
|
||||
StorageBlocks int
|
||||
PeriodEnd time.Time
|
||||
PastDueSince time.Time
|
||||
KeptMember int64
|
||||
StorageUsed int64
|
||||
Warned string
|
||||
Updated time.Time
|
||||
}
|
||||
|
||||
const timeFormat = "2006-01-02T15:04:05.000Z"
|
||||
|
||||
func ts(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return t.UTC().Format(timeFormat)
|
||||
}
|
||||
|
||||
func parseTS(s string) time.Time {
|
||||
t, _ := time.Parse(timeFormat, s)
|
||||
return t
|
||||
}
|
||||
|
||||
const cols = `team_id, plan, status, trial_ends, customer, subscription, seats, storage_blocks, period_end, past_due_since, kept_member, storage_used, warned, updated_at`
|
||||
|
||||
func scan(row interface{ Scan(...any) error }) (*Account, error) {
|
||||
var a Account
|
||||
var trial, period, pastDue, updated string
|
||||
err := row.Scan(&a.Team, &a.Plan, &a.Status, &trial, &a.Customer, &a.Subscription, &a.Seats, &a.StorageBlocks, &period, &pastDue, &a.KeptMember, &a.StorageUsed, &a.Warned, &updated)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.TrialEnds, a.PeriodEnd, a.PastDueSince, a.Updated = parseTS(trial), parseTS(period), parseTS(pastDue), parseTS(updated)
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// StartTrial gives a new team its trial of the paid plan.
|
||||
func StartTrial(d *db.DB, team int64, p *Plans, now time.Time) error {
|
||||
_, err := d.Exec(`INSERT INTO billing (team_id, plan, status, trial_ends, updated_at) VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (team_id) DO NOTHING`, team, p.Paid, Trialing, ts(now.Add(time.Duration(p.TrialDays)*24*time.Hour)), ts(now))
|
||||
return err
|
||||
}
|
||||
|
||||
// Get is a team's account; a team with none (made before billing) is on
|
||||
// the free plan.
|
||||
func Get(d *db.DB, team int64) (*Account, error) {
|
||||
a, err := scan(d.QueryRow(`SELECT `+cols+` FROM billing WHERE team_id = ?`, team))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return &Account{Team: team, Plan: "", Status: Free}, nil
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// All are every team's accounts.
|
||||
func All(d *db.DB) ([]*Account, error) {
|
||||
rows, err := d.Query(`SELECT ` + cols + ` FROM billing ORDER BY team_id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Account
|
||||
for rows.Next() {
|
||||
a, err := scan(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Save writes an account.
|
||||
func Save(d *db.DB, a *Account, now time.Time) error {
|
||||
a.Updated = now
|
||||
_, err := d.Exec(`INSERT INTO billing (`+cols+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (team_id) DO UPDATE SET plan = excluded.plan, status = excluded.status, trial_ends = excluded.trial_ends,
|
||||
customer = excluded.customer, subscription = excluded.subscription, seats = excluded.seats, storage_blocks = excluded.storage_blocks,
|
||||
period_end = excluded.period_end, past_due_since = excluded.past_due_since, kept_member = excluded.kept_member,
|
||||
storage_used = excluded.storage_used, warned = excluded.warned, updated_at = excluded.updated_at`,
|
||||
a.Team, a.Plan, a.Status, ts(a.TrialEnds), a.Customer, a.Subscription, a.Seats, a.StorageBlocks, ts(a.PeriodEnd),
|
||||
ts(a.PastDueSince), a.KeptMember, a.StorageUsed, a.Warned, ts(now))
|
||||
return err
|
||||
}
|
||||
|
||||
// ByCustomer finds a team's account by its Stripe customer.
|
||||
func ByCustomer(d *db.DB, customer string) (*Account, error) {
|
||||
if customer == "" {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
return scan(d.QueryRow(`SELECT `+cols+` FROM billing WHERE customer = ?`, customer))
|
||||
}
|
||||
|
||||
// Effective is the plan a team has now, and whether it's read-only:
|
||||
// - a trial before its end, or a subscription active or past due (for
|
||||
// under ReadOnlyAfter): the plan subscribed to
|
||||
// - past due longer: the plan, but read-only
|
||||
// - otherwise (the trial ended, canceled, free): the free plan
|
||||
func (a *Account) Effective(p *Plans, now time.Time) (plan *Plan, readOnly bool) {
|
||||
switch a.Status {
|
||||
case Trialing:
|
||||
if now.Before(a.TrialEnds) {
|
||||
return p.Get(a.Plan), false
|
||||
}
|
||||
if a.Subscription != "" { // a trial with a subscription behind it: Stripe says when it ends
|
||||
return p.Get(a.Plan), false
|
||||
}
|
||||
case Active:
|
||||
return p.Get(a.Plan), false
|
||||
case PastDue:
|
||||
return p.Get(a.Plan), !a.PastDueSince.IsZero() && now.Sub(a.PastDueSince) >= ReadOnlyAfter
|
||||
}
|
||||
return p.Get(p.Free), false
|
||||
}
|
||||
|
||||
// SeenEvent records a Stripe event, and says whether it was new: each is
|
||||
// handled once, whichever copy of the app it reaches.
|
||||
func SeenEvent(d *db.DB, id, typ string, now time.Time) (bool, error) {
|
||||
res, err := d.Exec(`INSERT INTO stripe_events (id, type, received_at) VALUES (?, ?, ?) ON CONFLICT (id) DO NOTHING`, id, typ, ts(now))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package billing
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
func TestPlans(t *testing.T) {
|
||||
p, err := Load("", "price_m", "", "price_b")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
free, paid := p.Get("free"), p.Get("paid")
|
||||
if !free.Includes("seo") || free.Includes("prospects") || !paid.Includes("prospects") || free.Paid() || !paid.Paid() {
|
||||
t.Error("modules")
|
||||
}
|
||||
if free.Seats != 2 || free.Agents != 1 || paid.Agents != 5 || free.StorageBytes(0, 0) != 1<<30 || paid.StorageBytes(3, 1) != 40<<30 {
|
||||
t.Errorf("limits %+v %+v", free, paid)
|
||||
}
|
||||
if free.CrawlInterval() != 7*24*time.Hour || paid.CrawlInterval() != 24*time.Hour || paid.PriceMonth != "price_m" {
|
||||
t.Error("crawl or price")
|
||||
}
|
||||
if p.Get("nonsense") != free {
|
||||
t.Error("unknown plan isn't free")
|
||||
}
|
||||
f := filepath.Join(t.TempDir(), "plans.yaml")
|
||||
os.WriteFile(f, []byte("trial_days: 30\ntax: true\nplans:\n free: {name: Free, modules: [content], seats: 1}\n paid: {name: Team, modules: [all], price_month: price_x, price_year: price_y}\n"), 0o600)
|
||||
p, err = Load(f, "price_m", "", "")
|
||||
if err != nil || p.TrialDays != 30 || !p.Tax || p.Get("paid").PriceMonth != "price_x" || p.Get("paid").PriceYear != "price_y" {
|
||||
t.Errorf("file: %+v %v", p, err)
|
||||
}
|
||||
os.WriteFile(f, []byte("plans:\n basic: {name: B, modules: [all]}\n"), 0o600)
|
||||
if _, err := Load(f, "", "", ""); err == nil {
|
||||
t.Error("no free plan accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccounts(t *testing.T) {
|
||||
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
p := Defaults()
|
||||
now := time.Now()
|
||||
if a, _ := Get(d, 9); a.Status != Free {
|
||||
t.Errorf("no account: %+v", a)
|
||||
}
|
||||
StartTrial(d, 1, p, now)
|
||||
a, _ := Get(d, 1)
|
||||
if pl, ro := a.Effective(p, now); pl.ID != "paid" || ro {
|
||||
t.Errorf("trial: %s %v", pl.ID, ro)
|
||||
}
|
||||
if pl, _ := a.Effective(p, now.Add(15*24*time.Hour)); pl.ID != "free" {
|
||||
t.Errorf("after the trial: %s", pl.ID)
|
||||
}
|
||||
a.Status, a.PastDueSince = PastDue, now
|
||||
Save(d, a, now)
|
||||
if pl, ro := a.Effective(p, now.Add(13*24*time.Hour)); pl.ID != "paid" || ro {
|
||||
t.Error("past due, under 14 days")
|
||||
}
|
||||
if _, ro := a.Effective(p, now.Add(15*24*time.Hour)); !ro {
|
||||
t.Error("past due 15 days: not read-only")
|
||||
}
|
||||
a.Status, a.Customer = Canceled, "cus_1"
|
||||
Save(d, a, now)
|
||||
if b, err := ByCustomer(d, "cus_1"); err != nil || b.Team != 1 {
|
||||
t.Errorf("by customer: %v", err)
|
||||
}
|
||||
if pl, _ := a.Effective(p, now); pl.ID != "free" {
|
||||
t.Error("canceled isn't free")
|
||||
}
|
||||
if n, _ := SeenEvent(d, "evt_1", "x", now); !n {
|
||||
t.Error("first event")
|
||||
}
|
||||
if n, _ := SeenEvent(d, "evt_1", "x", now); n {
|
||||
t.Error("event twice")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Package billing is the multi-tenant edition's plans and each team's
|
||||
// subscription to one, through the platform's own Stripe account (Stripe
|
||||
// Billing): Checkout to subscribe, the Customer Portal to pay and see
|
||||
// invoices, webhooks to follow the subscription. Separate from a team's own
|
||||
// Stripe connection, which the Metrics module reads.
|
||||
package billing
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Plan is what a team may do.
|
||||
type Plan struct {
|
||||
ID string `yaml:"-"`
|
||||
Name string `yaml:"name"`
|
||||
Modules []string `yaml:"modules"` // "all", or module IDs
|
||||
// Seats: how many people; 0 on a paid plan means as many as are paid
|
||||
// for (Stripe's quantity).
|
||||
Seats int `yaml:"seats"`
|
||||
Agents int `yaml:"agents"` // not counted as people
|
||||
// Storage: StorageGB for the team, or StorageGBPerSeat for each paid
|
||||
// person, pooled; more in blocks of StorageBlockGB.
|
||||
StorageGB int `yaml:"storage_gb"`
|
||||
StorageGBPerSeat int `yaml:"storage_gb_per_seat"`
|
||||
StorageBlockGB int `yaml:"storage_block_gb"`
|
||||
CrawlPages int `yaml:"crawl_pages"`
|
||||
CrawlEvery string `yaml:"crawl_every"` // daily or weekly
|
||||
Sources int `yaml:"sources"` // Market entries watched; 0: no limit beyond fair use
|
||||
|
||||
// Stripe's prices: per person a month, and (if offered) a year; and
|
||||
// per extra storage block a month.
|
||||
PriceMonth string `yaml:"price_month"`
|
||||
PriceYear string `yaml:"price_year"`
|
||||
PriceStorageBlock string `yaml:"price_storage_block"`
|
||||
PerSeatCents int `yaml:"per_seat_cents"` // to show: 1500 is $15
|
||||
}
|
||||
|
||||
// Paid says whether the plan is paid for.
|
||||
func (p *Plan) Paid() bool { return p.PriceMonth != "" || p.PriceYear != "" || p.PerSeatCents > 0 }
|
||||
|
||||
// Includes says whether a module is in the plan.
|
||||
func (p *Plan) Includes(module string) bool {
|
||||
for _, m := range p.Modules {
|
||||
if m == "all" || m == module {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CrawlInterval is how often a site is audited.
|
||||
func (p *Plan) CrawlInterval() time.Duration {
|
||||
if p.CrawlEvery == "daily" {
|
||||
return 24 * time.Hour
|
||||
}
|
||||
return 7 * 24 * time.Hour
|
||||
}
|
||||
|
||||
// StorageBytes is the plan's storage for a team with seats paid people
|
||||
// and blocks extra blocks.
|
||||
func (p *Plan) StorageBytes(seats, blocks int) int64 {
|
||||
gb := p.StorageGB + p.StorageGBPerSeat*seats + p.StorageBlockGB*blocks
|
||||
return int64(gb) << 30
|
||||
}
|
||||
|
||||
// Plans are the platform's.
|
||||
type Plans struct {
|
||||
Plans map[string]*Plan `yaml:"plans"`
|
||||
Free string `yaml:"free"` // the plan a team drops to
|
||||
Paid string `yaml:"paid"` // the plan a trial is of
|
||||
TrialDays int `yaml:"trial_days"` // a new team's trial of Paid
|
||||
Tax bool `yaml:"tax"` // Stripe Tax on Checkout (automatic_tax)
|
||||
}
|
||||
|
||||
// Defaults are the plans decided on 2026-11-25 (PLAN.md, Phase 14), without
|
||||
// Stripe's price IDs, which come from SUPERMARKET_PLANS or the environment.
|
||||
func Defaults() *Plans {
|
||||
return &Plans{
|
||||
Free: "free", Paid: "paid", TrialDays: 14,
|
||||
Plans: map[string]*Plan{
|
||||
"free": {ID: "free", Name: "Free", Modules: []string{"content", "seo", "market"}, Seats: 2, Agents: 1,
|
||||
StorageGB: 1, CrawlPages: 500, CrawlEvery: "weekly", Sources: 10},
|
||||
"paid": {ID: "paid", Name: "Paid", Modules: []string{"all"}, Agents: 5,
|
||||
StorageGBPerSeat: 5, StorageBlockGB: 25, CrawlPages: 10000, CrawlEvery: "daily", PerSeatCents: 1500},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Load reads the plans: a YAML file (SUPERMARKET_PLANS), or the defaults.
|
||||
// priceMonth, priceYear and priceBlock fill the paid plan's Stripe prices
|
||||
// when the file doesn't.
|
||||
func Load(path, priceMonth, priceYear, priceBlock string) (*Plans, error) {
|
||||
p := Defaults()
|
||||
if path != "" {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var f Plans
|
||||
if err := yaml.Unmarshal(raw, &f); err != nil {
|
||||
return nil, fmt.Errorf("the plans file: %w", err)
|
||||
}
|
||||
if len(f.Plans) > 0 {
|
||||
p.Plans = f.Plans
|
||||
}
|
||||
if f.Free != "" {
|
||||
p.Free = f.Free
|
||||
}
|
||||
if f.Paid != "" {
|
||||
p.Paid = f.Paid
|
||||
}
|
||||
if f.TrialDays != 0 {
|
||||
p.TrialDays = f.TrialDays
|
||||
}
|
||||
p.Tax = f.Tax
|
||||
}
|
||||
for id, pl := range p.Plans {
|
||||
pl.ID = id
|
||||
if len(pl.Modules) == 0 {
|
||||
return nil, fmt.Errorf("plan %s has no modules", id)
|
||||
}
|
||||
}
|
||||
paid, free := p.Plans[p.Paid], p.Plans[p.Free]
|
||||
if paid == nil || free == nil {
|
||||
return nil, errors.New("the plans need a free plan and a paid one (free:, paid:)")
|
||||
}
|
||||
if paid.PriceMonth == "" {
|
||||
paid.PriceMonth = priceMonth
|
||||
}
|
||||
if paid.PriceYear == "" {
|
||||
paid.PriceYear = priceYear
|
||||
}
|
||||
if paid.PriceStorageBlock == "" {
|
||||
paid.PriceStorageBlock = priceBlock
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Get is a plan by ID, or the free one.
|
||||
func (p *Plans) Get(id string) *Plan {
|
||||
if pl, ok := p.Plans[id]; ok {
|
||||
return pl
|
||||
}
|
||||
return p.Plans[p.Free]
|
||||
}
|
||||
Reference in New Issue
Block a user