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]
|
||||
}
|
||||
@@ -98,6 +98,13 @@ type Config struct {
|
||||
// PlatformAdmins are the email addresses of the people running the
|
||||
// multi-tenant service (its /platform area).
|
||||
PlatformAdmins []string
|
||||
|
||||
// Billing (multi-tenant): the platform's own Stripe account; empty, no
|
||||
// billing (every team has everything).
|
||||
StripeKey, StripeWebhookSecret string
|
||||
StripePrice, StripePriceYear string // per person, a month and a year
|
||||
StripePriceStorage string // an extra storage block, a month
|
||||
PlansFile string // the plans, if not the defaults
|
||||
}
|
||||
|
||||
// Environment variables.
|
||||
@@ -121,6 +128,12 @@ const (
|
||||
EnvMailFrom = "SUPERMARKET_MAIL_FROM"
|
||||
EnvPGBackups = "SUPERMARKET_PG_BACKUPS"
|
||||
EnvPlatform = "SUPERMARKET_PLATFORM_ADMINS"
|
||||
EnvStripeKey = "SUPERMARKET_STRIPE_KEY"
|
||||
EnvStripeHook = "SUPERMARKET_STRIPE_WEBHOOK_SECRET"
|
||||
EnvStripePrice = "SUPERMARKET_STRIPE_PRICE"
|
||||
EnvStripeYear = "SUPERMARKET_STRIPE_PRICE_YEAR"
|
||||
EnvStripeStore = "SUPERMARKET_STRIPE_PRICE_STORAGE"
|
||||
EnvPlans = "SUPERMARKET_PLANS"
|
||||
)
|
||||
|
||||
// Load reads the settings through getenv (os.Getenv) and checks them. All
|
||||
@@ -229,6 +242,23 @@ func Load(getenv func(string) string) (*Config, error) {
|
||||
bad("%s is for the multi-tenant edition", EnvPlatform)
|
||||
}
|
||||
|
||||
// Billing.
|
||||
c.StripeKey, c.StripeWebhookSecret = get(EnvStripeKey, ""), get(EnvStripeHook, "")
|
||||
c.StripePrice, c.StripePriceYear, c.StripePriceStorage = get(EnvStripePrice, ""), get(EnvStripeYear, ""), get(EnvStripeStore, "")
|
||||
c.PlansFile = get(EnvPlans, "")
|
||||
if c.StripeKey != "" {
|
||||
switch {
|
||||
case c.Edition != Multi:
|
||||
bad("%s is for the multi-tenant edition: it bills its teams", EnvStripeKey)
|
||||
case !strings.HasPrefix(c.StripeKey, "sk_") && !strings.HasPrefix(c.StripeKey, "rk_"):
|
||||
bad("%s isn't a Stripe secret key (sk_…)", EnvStripeKey)
|
||||
case c.StripeWebhookSecret == "":
|
||||
bad("%s is needed with %s: the webhook's signing secret (whsec_…), from Stripe's dashboard", EnvStripeHook, EnvStripeKey)
|
||||
case c.StripePrice == "" && c.PlansFile == "":
|
||||
bad("%s is needed with %s: the paid plan's price per person a month (price_…)", EnvStripePrice, EnvStripeKey)
|
||||
}
|
||||
}
|
||||
|
||||
if len(problems) > 0 {
|
||||
return c, errors.New(strings.Join(problems, "\n"))
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ type Migration struct {
|
||||
// PlatformTables are the tables every team shares on the multi-tenant
|
||||
// edition, in the main schema; every other table is a team's, in its own
|
||||
// schema.
|
||||
var PlatformTables = []string{"instances", "locks", "users", "memberships", "sessions", "links", "throttle", "agent_keys", "teams"}
|
||||
var PlatformTables = []string{"instances", "locks", "users", "memberships", "sessions", "links", "throttle", "agent_keys", "teams", "billing", "stripe_events"}
|
||||
|
||||
// both are the migrations after schema 29, on both databases: schema 30
|
||||
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
|
||||
@@ -301,6 +301,34 @@ ALTER TABLE sessions ADD COLUMN view_reason TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE users ADD COLUMN oidc_subject TEXT NOT NULL DEFAULT ''; -- <issuer>|<subject>: who they are at the Core
|
||||
CREATE UNIQUE INDEX users_oidc_subject ON users(oidc_subject) WHERE oidc_subject <> '';
|
||||
ALTER TABLE sessions ADD COLUMN via TEXT NOT NULL DEFAULT 'password'; -- password or core
|
||||
`,
|
||||
},
|
||||
// 44
|
||||
{
|
||||
Note: "billing: each team's plan and Stripe subscription, and the Stripe events seen (multi-tenant edition)",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE billing (
|
||||
team_id INTEGER PRIMARY KEY,
|
||||
plan TEXT NOT NULL DEFAULT 'paid', -- the plan subscribed to (or trialed)
|
||||
status TEXT NOT NULL DEFAULT 'trialing', -- trialing, active, past_due, canceled, free
|
||||
trial_ends TEXT NOT NULL DEFAULT '',
|
||||
customer TEXT NOT NULL DEFAULT '', -- Stripe's customer
|
||||
subscription TEXT NOT NULL DEFAULT '', -- Stripe's subscription
|
||||
seats INTEGER NOT NULL DEFAULT 0, -- people paid for
|
||||
storage_blocks INTEGER NOT NULL DEFAULT 0, -- extra storage blocks paid for
|
||||
period_end TEXT NOT NULL DEFAULT '', -- the subscription's current period: when the next invoice comes
|
||||
past_due_since TEXT NOT NULL DEFAULT '',
|
||||
kept_member INTEGER NOT NULL DEFAULT 0, -- on Free with too many people: the one besides the owner who keeps their access
|
||||
storage_used INTEGER NOT NULL DEFAULT 0, -- bytes, measured hourly
|
||||
warned TEXT NOT NULL DEFAULT '', -- the last lapse email sent: past-due, read-only, deleting
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE stripe_events (
|
||||
id TEXT PRIMARY KEY, -- Stripe's event ID: each is handled once
|
||||
type TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL
|
||||
);
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -106,6 +106,7 @@ type Fetcher struct {
|
||||
Client *http.Client
|
||||
UserAgent string
|
||||
Delay time.Duration // between requests, to be polite
|
||||
MaxPages int // pages an audit reads; 0: MaxAuditPages
|
||||
}
|
||||
|
||||
// NewFetcher returns a fetcher that doesn't follow redirects itself, so
|
||||
@@ -239,7 +240,7 @@ func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property strin
|
||||
seen := map[string]bool{queue[0]: true}
|
||||
add := func(u string) {
|
||||
n := normalize(u)
|
||||
if n == "" || seen[n] || len(seen) >= MaxAuditPages {
|
||||
if n == "" || seen[n] || len(seen) >= f.maxPages() {
|
||||
return
|
||||
}
|
||||
if p, err := url.Parse(n); err != nil || strings.TrimPrefix(p.Hostname(), "www.") != host {
|
||||
@@ -801,3 +802,10 @@ func LastDoneAudit(d *db.DB, site string) time.Time {
|
||||
t, _ := time.Parse(time.RFC3339, s.String)
|
||||
return t
|
||||
}
|
||||
|
||||
func (f *Fetcher) maxPages() int {
|
||||
if f.MaxPages > 0 {
|
||||
return f.MaxPages
|
||||
}
|
||||
return MaxAuditPages
|
||||
}
|
||||
|
||||
@@ -104,6 +104,9 @@ type Membership struct {
|
||||
User int64
|
||||
Role Role
|
||||
Modules map[string]Access // a member's; admins and owners have them all
|
||||
// Cap limits every role, admins too: a module missing from it can't be
|
||||
// reached, one at View only read (the team's plan). nil: no cap.
|
||||
Cap map[string]Access
|
||||
}
|
||||
|
||||
// Admin says whether the role runs the whole system.
|
||||
@@ -112,6 +115,12 @@ func (m Membership) Admin() bool { return m.Role == Owner || m.Role == Admin }
|
||||
// Can says whether the member may see a module (write false) or change
|
||||
// things in it (write true).
|
||||
func (m Membership) Can(module string, write bool) bool {
|
||||
if m.Cap != nil {
|
||||
c, ok := m.Cap[module]
|
||||
if !ok || (write && c != Edit) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if m.Admin() {
|
||||
return true
|
||||
}
|
||||
|
||||
+21
-1
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// Who may reach what. Every route belongs to an area: a module, Settings
|
||||
@@ -170,7 +172,25 @@ func (s *Server) allow(area string, next http.Handler) http.Handler {
|
||||
s.toSignIn(w, r)
|
||||
return
|
||||
}
|
||||
if !v.can(area, !safeMethod(r.Method)) {
|
||||
write := !safeMethod(r.Method)
|
||||
// A lapsed team changes nothing, but its billing, people's own
|
||||
// accounts, and switching teams.
|
||||
if v.ReadOnly && write && !strings.HasPrefix(r.URL.Path, "/settings/billing") &&
|
||||
!platformPath(r.URL.Path) && !strings.HasPrefix(r.URL.Path, "/teams/") {
|
||||
http.Error(w, sentence(errLapsed.Error())+".", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if !v.can(area, write) {
|
||||
// A module the team's plan has only to read: say so.
|
||||
if write && v.Member.Cap != nil && v.Member.Cap[area] == users.View && v.Member.Can(area, false) {
|
||||
if ts, err := s.teamServer(r); err == nil {
|
||||
if plan, _ := ts.teamPlan(); plan != nil {
|
||||
http.Error(w, fmt.Sprintf("The %s plan doesn't include %s: what's there stays, to read. The team's owner can move up a plan under Settings → Billing.",
|
||||
plan.Name, grantName(area)), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -56,6 +56,12 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
|
||||
if err != nil {
|
||||
return nil, users.ErrBadKey
|
||||
}
|
||||
if plan, ro := ts.teamPlan(); plan != nil {
|
||||
if ro {
|
||||
return nil, &mcpserver.Refusal{Status: http.StatusForbidden, Reason: sentence(errLapsed.Error()) + "."}
|
||||
}
|
||||
m = planned(m, plan, ro)
|
||||
}
|
||||
lim, err := users.LimitsOf(ts.DB, u.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -315,6 +321,9 @@ func (s *Server) agentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
f := agentForm{Name: strings.TrimSpace(r.PostFormValue("name")), Description: strings.TrimSpace(r.PostFormValue("description")),
|
||||
Expires: r.PostFormValue("expires"), Scopes: agentScopesFromForm(r)}
|
||||
expires, err := expiryFromForm(r, now)
|
||||
if err == nil {
|
||||
err = s.limitAgents()
|
||||
}
|
||||
switch {
|
||||
case f.Name == "":
|
||||
err = errors.New("give the agent a name")
|
||||
@@ -510,6 +519,10 @@ func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
case "enable":
|
||||
if lerr := s.limitAgents(); lerr != nil {
|
||||
s.renderAgent(w, r, u, sentence(lerr.Error())+".", http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
if err = users.SetStatus(s.DB, u.ID, users.Active); err == nil {
|
||||
s.audit(r, "enabled", u.Name, "an agent")
|
||||
redirect(w, r, back, "enabled")
|
||||
|
||||
@@ -690,6 +690,11 @@ func (s *Server) marketActTools(srv *mcp.Server, c *mcpserver.Caller) {
|
||||
e.ID, action = old.ID, "changed"
|
||||
}
|
||||
}
|
||||
if action == "added" {
|
||||
if err := s.limitSources(len(list)); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if err := inventory.Save(s.DB, &e); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ type viewer struct {
|
||||
|
||||
Platform bool // runs the multi-tenant platform (SUPERMARKET_PLATFORM_ADMINS)
|
||||
Viewing bool // a platform admin viewing a team, read-only
|
||||
ReadOnly bool // the team's subscription has lapsed: nothing may change
|
||||
}
|
||||
|
||||
// localOwner is the local edition's one user.
|
||||
@@ -166,7 +167,14 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &viewer{User: u, Member: m, Session: sess, Platform: pa}, nil
|
||||
v := &viewer{User: u, Member: m, Session: sess, Platform: pa}
|
||||
if s.billingOn() {
|
||||
if ts, err := s.forTeam(sess.Team); err == nil {
|
||||
plan, ro := ts.teamPlan()
|
||||
v.Member, v.ReadOnly = planned(m, plan, ro), ro
|
||||
}
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// toSignIn sends someone who isn't signed in to the sign-in page, and
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// newBilled is the multi-tenant edition with billing on.
|
||||
func newBilled(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
s, h := newMultiEdition(t)
|
||||
p, err := billing.Load("", "price_month", "price_year", "price_block")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Plans = p
|
||||
return s, h
|
||||
}
|
||||
|
||||
// signUp makes a team through the sign-up page (so it gets its trial).
|
||||
func signUp(t *testing.T, h http.Handler, email, company, site string) *http.Cookie {
|
||||
t.Helper()
|
||||
rec := postForm(h, "/signup", url.Values{"email": {email}, "password": {"a long enough one"}, "company": {company}, "website": {site}})
|
||||
c := cookieOf(rec, sessionCookie)
|
||||
if rec.Code != http.StatusSeeOther || c == nil {
|
||||
t.Fatalf("sign up: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// setAccount changes a team's billing, as Stripe's events would.
|
||||
func setAccount(t *testing.T, s *Server, team int64, fn func(a *billing.Account)) {
|
||||
t.Helper()
|
||||
a, err := billing.Get(s.platform(), team)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fn(a)
|
||||
if err := billing.Save(s.platform(), a, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlansLimitTeams(t *testing.T) {
|
||||
s, h := newBilled(t)
|
||||
c := signUp(t, h, "olu@acme.example", "Acme", "acme.example")
|
||||
u, _ := users.ByEmail(s.platform(), "olu@acme.example")
|
||||
list, _ := users.TeamsOf(s.platform(), u.ID)
|
||||
team := list[0].ID
|
||||
ts, _ := s.forTeam(team)
|
||||
|
||||
// A new team's trial: Paid, everything.
|
||||
a, _ := billing.Get(s.platform(), team)
|
||||
if a.Status != billing.Trialing || a.TrialEnds.Before(time.Now().Add(13*24*time.Hour)) {
|
||||
t.Fatalf("trial %+v", a)
|
||||
}
|
||||
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Lead Co"}, "website": {"https://lead.example"}}); rec.Code == http.StatusForbidden {
|
||||
t.Error("Prospects closed on the trial")
|
||||
}
|
||||
if !ts.jobAllowed("outreach") {
|
||||
t.Error("outreach job held on the trial")
|
||||
}
|
||||
if n, every := ts.crawlLimits(); n != 10000 || every != 24*time.Hour {
|
||||
t.Errorf("trial crawl %d %v", n, every)
|
||||
}
|
||||
|
||||
// The trial over, without a subscription: Free.
|
||||
setAccount(t, s, team, func(a *billing.Account) { a.TrialEnds = time.Now().Add(-time.Hour) })
|
||||
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Other"}, "website": {"https://other.example"}}); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Free plan") {
|
||||
t.Errorf("Prospects on Free: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := as(h, c, http.MethodGet, "/prospects", nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Lead Co") {
|
||||
t.Errorf("Prospects' data on Free: %d", rec.Code)
|
||||
}
|
||||
if ts.jobAllowed("outreach") || !ts.jobAllowed("seo") {
|
||||
t.Error("jobs on Free")
|
||||
}
|
||||
if n, every := ts.crawlLimits(); n != 500 || every != 7*24*time.Hour {
|
||||
t.Errorf("free crawl %d %v", n, every)
|
||||
}
|
||||
// One agent on Free.
|
||||
if rec := as(h, c, http.MethodPost, "/settings/agents", url.Values{"name": {"One"}, "scope:seo": {"read"}}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("first agent: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := as(h, c, http.MethodPost, "/settings/agents", url.Values{"name": {"Two"}, "scope:seo": {"read"}}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "1 agents") {
|
||||
t.Errorf("second agent on Free: %d", rec.Code)
|
||||
}
|
||||
// Ten Market entries on Free.
|
||||
for i := 0; i < 10; i++ {
|
||||
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Entry " + strconv.Itoa(i)}, "relationship": {"partner"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("entry %d: %d", i, rec.Code)
|
||||
}
|
||||
}
|
||||
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Eleven"}, "relationship": {"partner"}, "description": {"x"}}); rec.Code == http.StatusSeeOther {
|
||||
t.Error("an eleventh entry on Free")
|
||||
}
|
||||
|
||||
// Paid and active: everything again.
|
||||
setAccount(t, s, team, func(a *billing.Account) { a.Status = billing.Active })
|
||||
if rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Eleven"}, "relationship": {"partner"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Errorf("Paid: %d", rec.Code)
|
||||
}
|
||||
|
||||
// Past due for 15 days: read-only, for people and agents.
|
||||
setAccount(t, s, team, func(a *billing.Account) {
|
||||
a.Status, a.PastDueSince = billing.PastDue, time.Now().Add(-15*24*time.Hour)
|
||||
})
|
||||
rec := as(h, c, http.MethodPost, "/market/save", url.Values{"name": {"Twelve"}, "relationship": {"partner"}, "description": {"x"}})
|
||||
if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "lapsed") {
|
||||
t.Errorf("lapsed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := as(h, c, http.MethodGet, "/market", nil); rec.Code != http.StatusOK {
|
||||
t.Errorf("lapsed, reading: %d", rec.Code)
|
||||
}
|
||||
_, key := newAgentIn(t, ts, "Late", map[string]users.Access{"market": users.View})
|
||||
if code, _ := mcpTools(h, key); code != http.StatusForbidden {
|
||||
t.Errorf("agent of a lapsed team: %d", code)
|
||||
}
|
||||
if ts.jobAllowed("seo") || !ts.jobAllowed("accounts") {
|
||||
t.Error("jobs of a lapsed team")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoBillingNoLimits(t *testing.T) {
|
||||
s, h := newMultiEdition(t)
|
||||
c := signUp(t, h, "olu@acme.example", "Acme", "acme.example")
|
||||
if rec := as(h, c, http.MethodPost, "/prospects/new", url.Values{"company_name": {"Lead"}, "website": {"https://lead.example"}}); rec.Code == http.StatusForbidden {
|
||||
t.Error("limited without billing")
|
||||
}
|
||||
if a, _ := billing.Get(s.platform(), 1); a.Status != billing.Free || a.Customer != "" {
|
||||
t.Errorf("an account without billing: %+v", a)
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,11 @@ func (s *Server) inventorySave(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
e := entryFromForm(r)
|
||||
if err := inventory.Save(s.DB, e); err != nil {
|
||||
err := s.marketRoom(e)
|
||||
if err == nil {
|
||||
err = inventory.Save(s.DB, e)
|
||||
}
|
||||
if err != nil {
|
||||
title := e.Name
|
||||
if title == "" {
|
||||
title = "New entry"
|
||||
@@ -296,3 +300,20 @@ func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
|
||||
return info, nil
|
||||
}
|
||||
}
|
||||
|
||||
// marketRoom says why a new entry can't be added (the plan's limit), or nil.
|
||||
func (s *Server) marketRoom(e *inventory.Entry) error {
|
||||
if e.ID != 0 {
|
||||
return nil
|
||||
}
|
||||
list, err := inventory.List(s.DB, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, x := range list {
|
||||
if strings.EqualFold(x.Name, strings.TrimSpace(e.Name)) {
|
||||
return nil // the same name: Save says so
|
||||
}
|
||||
}
|
||||
return s.limitSources(len(list))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// What a team's plan allows (the multi-tenant edition, with billing on):
|
||||
// its modules (the others keep their data, read-only), its agents, its
|
||||
// sources, how much it crawls; and, when the subscription has lapsed too
|
||||
// long, nothing that changes anything.
|
||||
|
||||
// billingOn says whether teams are billed.
|
||||
func (s *Server) billingOn() bool { return s.multi() && s.Plans != nil }
|
||||
|
||||
// teamPlan is the team's plan now and whether it's read-only; nil when
|
||||
// there's no billing (everything allowed).
|
||||
func (s *Server) teamPlan() (*billing.Plan, bool) {
|
||||
if !s.billingOn() || s.team() == 0 {
|
||||
return nil, false
|
||||
}
|
||||
a, err := billing.Get(s.platform(), s.team())
|
||||
if err != nil {
|
||||
s.Log.Error("billing: reading the team's", "team", s.team(), "err", err)
|
||||
return nil, false
|
||||
}
|
||||
return a.Effective(s.Plans, time.Now())
|
||||
}
|
||||
|
||||
// errLapsed is what's said when a lapsed team tries to change something.
|
||||
var errLapsed = errors.New("the team's subscription has lapsed: its owner can renew it under Settings → Billing. Until then, nothing is fetched, sent or published")
|
||||
|
||||
// planned limits a membership to the plan: modules outside it, and every
|
||||
// module when the team is read-only, can only be viewed. Admins keep
|
||||
// Settings (but changes there are refused while read-only: allow).
|
||||
func planned(m users.Membership, plan *billing.Plan, readOnly bool) users.Membership {
|
||||
if plan == nil {
|
||||
return m
|
||||
}
|
||||
m.Cap = map[string]users.Access{}
|
||||
for _, g := range grants() {
|
||||
if plan.Includes(g.ID) && !readOnly {
|
||||
m.Cap[g.ID] = users.Edit
|
||||
} else {
|
||||
m.Cap[g.ID] = users.View
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// jobModule is the module a background job works for, if any.
|
||||
var jobModule = map[string]string{
|
||||
"scheduler": "content", "outreach": "prospects", "imports": "prospects", "discovery": "prospects",
|
||||
"tracking": "prospects", "seo": "seo", "metrics": "metrics",
|
||||
}
|
||||
|
||||
// jobAllowed says whether a team's background job may run: its module in
|
||||
// the plan, and the team not lapsed.
|
||||
func (s *Server) jobAllowed(name string) bool {
|
||||
plan, ro := s.teamPlan()
|
||||
if plan == nil {
|
||||
return true
|
||||
}
|
||||
if ro {
|
||||
return name == "accounts"
|
||||
}
|
||||
m, ok := jobModule[name]
|
||||
return !ok || plan.Includes(m)
|
||||
}
|
||||
|
||||
// limitAgents says why the team may not have another agent, or nil.
|
||||
func (s *Server) limitAgents() error {
|
||||
plan, ro := s.teamPlan()
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
if ro {
|
||||
return errLapsed
|
||||
}
|
||||
list, err := users.Members(s.platform(), s.team())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n := 0
|
||||
for _, m := range list {
|
||||
if m.Kind == users.Agent && m.Status == users.Active {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if plan.Agents > 0 && n >= plan.Agents {
|
||||
return fmt.Errorf("the %s plan has %d agents, and the team has them all: turn one off, or move up a plan", plan.Name, plan.Agents)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// limitSources says why the Market may not take another entry, or nil.
|
||||
func (s *Server) limitSources(existing int) error {
|
||||
plan, _ := s.teamPlan()
|
||||
if plan == nil || plan.Sources == 0 || existing < plan.Sources {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("the %s plan watches %d entries in the Market: remove one, or move up a plan", plan.Name, plan.Sources)
|
||||
}
|
||||
|
||||
// crawlLimits are how many pages an audit reads and how often (0: the
|
||||
// edition's own).
|
||||
func (s *Server) crawlLimits() (int, time.Duration) {
|
||||
plan, _ := s.teamPlan()
|
||||
if plan == nil {
|
||||
return 0, 7 * 24 * time.Hour
|
||||
}
|
||||
return plan.CrawlPages, plan.CrawlInterval()
|
||||
}
|
||||
+5
-2
@@ -617,7 +617,9 @@ func (s *Server) startAudit(site seoSite, speed bool) {
|
||||
defer release()
|
||||
ctx, cancel := context.WithTimeout(lctx, 45*time.Minute)
|
||||
defer cancel()
|
||||
a, err := seo.RunAudit(ctx, s.DB, seo.NewFetcher("Supermarket/"+s.Version+" (SEO audit)"), site.URL, site.Property)
|
||||
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO audit)")
|
||||
f.MaxPages, _ = s.crawlLimits()
|
||||
a, err := seo.RunAudit(ctx, s.DB, f, site.URL, site.Property)
|
||||
if err == nil && speed {
|
||||
for _, p := range busiest(a, 5) {
|
||||
a.Speed = append(a.Speed, seo.CheckSpeed(ctx, p, s.Secrets.Get(secrets.PageSpeedAPIKey)))
|
||||
@@ -682,8 +684,9 @@ func (s *Server) seoAuditStatus(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// weeklyAudits audits each website once a week.
|
||||
func (s *Server) weeklyAudits(now time.Time) {
|
||||
_, every := s.crawlLimits()
|
||||
for _, site := range s.seoSites() {
|
||||
if site.URL != "" && now.Sub(seo.LastDoneAudit(s.DB, site.URL)) > 7*24*time.Hour {
|
||||
if site.URL != "" && now.Sub(seo.LastDoneAudit(s.DB, site.URL)) > every {
|
||||
if a, _ := seo.LatestAudit(s.DB, site.URL); a != nil && a.Status == "failed" && now.Sub(a.StartedAt) < 24*time.Hour {
|
||||
continue // don't retry a failing site more than daily
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/core"
|
||||
"supermarket/internal/db"
|
||||
@@ -81,6 +82,9 @@ type Server struct {
|
||||
// Platform is the database every team shares: people, sessions, keys,
|
||||
// locks. On the local and server editions, DB itself.
|
||||
Platform *db.DB
|
||||
// Plans are the multi-tenant edition's billing; nil: no billing, every
|
||||
// team has everything.
|
||||
Plans *billing.Plans
|
||||
|
||||
testPublisher func(*posting.Account) content.Publisher // tests: posts nowhere
|
||||
|
||||
@@ -244,6 +248,9 @@ func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context
|
||||
if name == "seo" && !ts.domainProved() {
|
||||
return // nothing crawled or read before the domain is proved
|
||||
}
|
||||
if !ts.jobAllowed(name) {
|
||||
return // its module isn't in the team's plan, or the team has lapsed
|
||||
}
|
||||
if _, err := ts.jobs().Do(ctx, ts.lockName("job:"+name), func(c context.Context) { fn(c, ts) }); err != nil {
|
||||
ts.Log.Warn("jobs: taking the lock", "job", name, "team", ts.team(), "err", err)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/audit"
|
||||
"supermarket/internal/billing"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
@@ -182,6 +183,11 @@ func (s *Server) newTeam(owner *users.User, company, domain, site string, now ti
|
||||
if err := users.Join(s.platform(), team.ID, owner.ID, users.Owner, nil, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.billingOn() {
|
||||
if err := billing.StartTrial(s.platform(), team.ID, s.Plans, now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ts, err := s.forTeam(team.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
Reference in New Issue
Block a user