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 }