carlos / platform Public

console: team seats use present paid capacity first and never reduce at a join; revocation and resends share one outstanding predicate; drift observed and matched by owners (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev e5c1774973649309362fabcfcabcf8b195529e85 parent 873462c
14 files changed, +1,903 −61
  • internal/console/apibilling.go +18 −1
  • internal/console/apibilling_copy.go +2 −0
  • internal/console/billingops.go +1 −12
  • internal/console/billingpage_copy.go +10 −0
  • internal/console/billingpass.go +7 −2
  • internal/console/billingseats.go +706 −0
  • internal/console/billingseats_test.go +962 −0
  • internal/console/billingstore.go +14 −1
  • internal/console/claim_invariant_fixtures_test.go +3 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +32 −0
  • internal/console/ownership.go +31 −1
  • internal/console/server.go +105 −44
  • internal/console/store.go +11 −0
  • internal/console/testdata/claim-routes.txt +1 −0
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go
index c2d6916bb..93ee363ac 100644
--- a/internal/console/apibilling.go
+++ b/internal/console/apibilling.go
@@ -229,7 +229,10 @@ func (s *Server) closeOrphanBillingProblem(ctx context.Context, p *billingProble
// (Call 17) closes when the fresh read shows the operation's target (then
// applied), or on the operator's note saying what the Dashboard request log
// shows: executed without the target visible is a 409; not-executed records
-// the operation abandoned. It answers the HTTP status and, for a refusal,
+// the operation abandoned. A seats_unpaid problem (plans 6b) closes only
+// when a fresh read shows the members within the paid seats
+// (closeSeatsUnpaidLocked), else 409. It answers the HTTP status and, for a
+// refusal,
// the door copy.
func (s *Server) closeBillingProblemLocked(h billingHold, ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) {
var acct *Account
@@ -252,6 +255,20 @@ func (s *Server) closeBillingProblemLocked(h billingHold, ctx context.Context, p
if !cur.ClosedAt.IsZero() {
return http.StatusConflict, billingCopyClosed
}
+ if cur.Reason == problemSeatsUnpaid && acct != nil {
+ // Plans 6b: closes only when a fresh read shows the members within
+ // the period's paid seats; the account's open seats_unpaid problems
+ // close together.
+ closed, err := s.closeSeatsUnpaidLocked(h, s.billingClock(ctx), acct, addr, note, now)
+ switch {
+ case err != nil:
+ log.Printf("console: api billing close %d: seats: %v", p.ID, err)
+ return http.StatusServiceUnavailable, billingCopyProviderDown
+ case !closed:
+ return http.StatusConflict, billingCopySeatsStillOver
+ }
+ return http.StatusOK, ""
+ }
if cur.Subscription != "" {
ctx = s.billingClock(ctx)
sub, err := s.billing.cfg.Provider.Subscription(ctx, cur.Subscription)
diff --git a/internal/console/apibilling_copy.go b/internal/console/apibilling_copy.go
index 6fee55f80..8b8bec397 100644
--- a/internal/console/apibilling_copy.go
+++ b/internal/console/apibilling_copy.go
@@ -14,4 +14,6 @@ const (
// pass replaces them.
billingCopyOpEvidence = "start -note with executed or not-executed, from the request log in the stripe dashboard"
billingCopyOpExecutedUnseen = "the request log says it executed, but the subscription does not show it. put the subscription right in stripe first, then close"
+ // Plans 6b draft (Task 11), for the seats_unpaid close.
+ billingCopySeatsStillOver = "the account still has more members than paid seats. remove members first"
)
diff --git a/internal/console/billingops.go b/internal/console/billingops.go
index b3f54fd70..e2ff43631 100644
--- a/internal/console/billingops.go
+++ b/internal/console/billingops.go
@@ -303,7 +303,7 @@ func (s *Store) MarkOpApplied(opID string, provedPeriodEnd, now time.Time) error
return err
}
if authorisedBy != "" {
- if err := consumeSeatAuthorisationTx(tx, authorisedBy); err != nil {
+ if err := consumeSeatAuthorisationTx(tx, authorisedBy, now); err != nil {
return err
}
}
@@ -314,17 +314,6 @@ func (s *Store) MarkOpApplied(opID string, provedPeriodEnd, now time.Time) error
return tx.Commit()
}
-// consumeSeatAuthorisationTx spends the invite's seat authorisation in the
-// transaction that applies the operation it authorised (Invariant 2: single
-// use). Seat authorisations are recorded on invites by the membership
-// billing work (Task 11), which fills this in; until then there is none to
-// consume.
-func consumeSeatAuthorisationTx(tx *sql.Tx, token string) error {
- _ = tx
- _ = token
- return nil
-}
-
// PutBillingOpState moves an outstanding operation to state (never applied:
// that is MarkOpApplied), recording whether the outcome is indeterminate
// and, for a terminal state, when it settled. A terminal operation is left
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 59bcb66fe..c2e287d46 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -29,6 +29,16 @@ var billingCopy = map[string]string{
"renewal.stopped": "Renewal stopped. Your plan ends on %s.",
"renewal.resumed": "Renewal is back on.",
+ // Team seats (Task 11).
+ "seats.invite_line": "When %s joins, the account pays about %s now for the rest of the year, plus any tax.",
+ "seats.join_wait_title": "Not yet",
+ "seats.join_wait": "This account can't add you yet because its payment didn't go through. Its owners can see this on their billing page. Try the link again later.",
+ "seats.join_consent": "This invitation doesn't cover a new paid seat. Ask an owner to invite you again.",
+ "seats.join_busy": "This account is in the middle of another change. Try the link again in a minute.",
+ "seats.join_uncertain": "We couldn't confirm the account's payment for your seat. Try the link again in a few minutes.",
+ "seats.join_near_renewal": "This account renews within a day. Try the link again after it renews.",
+ "seats.revoke_wait": "This person's payment is still going through. Try again in a minute.",
+
// Checkout (Task 9).
"checkout.already": "This account already has a paid plan, or a payment is finishing. Check back in a minute.",
"checkout.failed": "We couldn't start the payment. Try again in a minute.",
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go
index 6c388b661..b67f3c4bf 100644
--- a/internal/console/billingpass.go
+++ b/internal/console/billingpass.go
@@ -100,8 +100,10 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) {
}
// billingSyncPass re-reads every live subscription, serially, paging by
-// account id, then observes outstanding operations and open restore
-// obligations (plans 6b) and runs discovery. One account's error never
+// account id, observing each team account's seats after its read
+// (observeSeats: drift and seats_unpaid, local writes only), then observes
+// outstanding operations and open restore obligations (plans 6b) and runs
+// discovery. One account's error never
// stops the others. The round shares one provider-time recorder: an
// observation at most observationMaxAge old serves every decision in the
// round, and a decision reached after it expires probes again. The pass
@@ -125,6 +127,9 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) {
log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err)
} else {
synced[b.Subscription] = true
+ // Plans 6b: the seats the read just stored, against the
+ // members now: drift and seats_unpaid, observed.
+ s.observeSeats(b.AccountID, now)
}
}
if len(page) < billingSyncBatch {
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go
new file mode 100644
index 000000000..af707d87a
--- /dev/null
+++ b/internal/console/billingseats.go
@@ -0,0 +1,706 @@
+package console
+
+import (
+ "context"
+ "crypto/subtle"
+ "database/sql"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "slices"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// Team seats (plans 6b, Calls 6, 11 to 13; Invariants 2, 4 and 7).
+//
+// A team plan's subscription carries one plan item whose quantity is the
+// billed seats. Paid capacity is decided at admission, every time, under the
+// account's member lock and then its billing hold (lock order: member, then
+// billing):
+//
+// - a join uses capacity already paid for first: a seat the plan item
+// already has is free and writes nothing; a seat paid for earlier in the
+// period but since reduced is a free restore (ProrateNone), kept away from
+// the renewal (Invariant 4); only beyond the period's paid seats is a seat
+// charged (ProrateNow), and only when the invite carries an unconsumed
+// seat authorisation that still matches the subscription;
+// - a join never reduces anything;
+// - an applied charge is a credit for the next admission: its authorisation
+// is consumed in the transaction that records the charge applied
+// (Store.MarkOpApplied), whatever happens to the membership write after;
+// - a removal and the owner's Match seats reduce the plan item to the
+// members billed (ProrateNone: it takes effect at renewal, Call 12);
+// - the hourly pass only observes: drift (a quantity above the members
+// billed) and seats_unpaid (more members than paid seats).
+//
+// A seat authorisation is what the owner agreed to when inviting someone who
+// will need a new paid seat (the confirm page with a local estimate, then a
+// fresh sign-in proof): the plan, book, currency and per-seat price at the
+// time. It is single use.
+
+// seatRecheck is how often the pass reconsiders an open seats_unpaid
+// problem: a console-local timer from seats_checked_at (Invariant 9).
+const seatRecheck = 24 * time.Hour
+
+// seatAuthorisation is an invite's agreement to pay for one new seat.
+// ConsumedAt is zero until the charge it authorised applied.
+type seatAuthorisation struct {
+ Plan, Book, Currency string
+ PriceMinor int64
+ By string
+ At, ConsumedAt time.Time
+}
+
+// SetInviteSeatAuthorisation records a on the invite. An invite already
+// carrying an authorisation keeps its own (single use: it is never renewed in
+// place).
+func (s *Store) SetInviteSeatAuthorisation(token string, a seatAuthorisation) error {
+ if token == "" || a.Plan == "" || a.Book == "" || a.Currency == "" {
+ return errors.New("billing: a seat authorisation needs an invite, a plan, a book and a currency")
+ }
+ res, err := s.db.Exec(`UPDATE invites SET seat_plan = ?, seat_book = ?, seat_currency = ?, seat_price_minor = ?,
+ seat_authorised_by = ?, seat_authorised_at = ?, seat_consumed_at = 0 WHERE token = ? AND seat_plan = ''`,
+ a.Plan, a.Book, a.Currency, a.PriceMinor, a.By, unixOrZero(a.At), token)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil || n == 1 {
+ return err
+ }
+ return fmt.Errorf("billing: invite has no room for a seat authorisation")
+}
+
+// InviteSeatAuthorisation is the invite's seat authorisation, nil when it
+// carries none (or the invite is gone).
+func (s *Store) InviteSeatAuthorisation(token string) (*seatAuthorisation, error) {
+ var a seatAuthorisation
+ var at, consumed int64
+ err := s.db.QueryRow(`SELECT seat_plan, seat_book, seat_currency, seat_price_minor, seat_authorised_by, seat_authorised_at, seat_consumed_at
+ FROM invites WHERE token = ?`, token).Scan(&a.Plan, &a.Book, &a.Currency, &a.PriceMinor, &a.By, &at, &consumed)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if a.Plan == "" {
+ return nil, nil
+ }
+ a.At, a.ConsumedAt = timeOrZero(at), timeOrZero(consumed)
+ return &a, nil
+}
+
+// seatCovered is an authorisation that covers a new seat on the account's
+// subscription now: unconsumed, for the same plan, book and currency, at a
+// price not above what the owner agreed. The price is checked when the
+// console holds the authorised book; a book version never changes its
+// prices (ErrPriceBookEdited), so the same book is the same price.
+func seatCovered(a *seatAuthorisation, row *billingAccount, book *plans.PriceBook) bool {
+ if a == nil || row == nil || !a.ConsumedAt.IsZero() {
+ return false
+ }
+ if a.Plan != row.Plan || a.Book != row.Book || a.Currency != row.Currency {
+ return false
+ }
+ if book != nil && book.Version == a.Book {
+ price, ok := book.PlanPrice(a.Plan, a.Currency)
+ if !ok || price > a.PriceMinor {
+ return false
+ }
+ }
+ return true
+}
+
+// consumeSeatAuthorisationTx spends the invite's seat authorisation in the
+// transaction that records the charge it authorised applied (Invariant 2:
+// single use, atomic with applied). An invite since revoked has nothing left
+// to spend.
+func consumeSeatAuthorisationTx(tx *sql.Tx, token string, now time.Time) error {
+ _, err := tx.Exec(`UPDATE invites SET seat_consumed_at = ? WHERE token = ? AND seat_plan != '' AND seat_consumed_at = 0`, now.Unix(), token)
+ return err
+}
+
+// PutSeatObservation records what a seat check saw on the account's billing
+// row: the drift mark (zero for none) with the members it counted, and when
+// seats_unpaid was last decided. Callers hold the account's billing hold,
+// since every sync writes these columns back from the row it read (Task 6).
+func (s *Store) PutSeatObservation(accountID int64, driftAt time.Time, driftMembers int, checkedAt time.Time) error {
+ _, err := s.db.Exec(`UPDATE billing_accounts SET seat_drift_at = ?, seat_drift_members = ?, seats_checked_at = ? WHERE account_id = ?`,
+ unixOrZero(driftAt), driftMembers, unixOrZero(checkedAt), accountID)
+ return err
+}
+
+// billingTeam is the account's team block when billing is configured and the
+// account's plan row is a team plan billing owns, else nil: only such an
+// account's membership is billed.
+func (s *Server) billingTeam(acct *Account) (*plans.Team, error) {
+ cat := s.cfg.PlanCatalog
+ if s.billing == nil || cat == nil {
+ return nil, nil
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil || row == nil || row.Source != PlanSourceBilling {
+ return nil, err
+ }
+ p, ok := cat.Plans[row.Plan]
+ if !ok {
+ return nil, nil
+ }
+ return p.Team, nil
+}
+
+// seatProblemLocked is the controller's ruling for Task 11: a problem
+// discovered by the request's own reads stops it. It runs after the finish
+// and allowance reads and before any seat operation is prepared or any seat
+// authorisation recorded, refusing with notice.problem. (Task 10's fix round
+// adds the same check as refuseOnProblemLocked; the controller merges the
+// two.)
+func (s *Server) seatProblemLocked(h billingHold, acct *Account) error {
+ _ = h
+ problems, err := s.store.OpenBillingProblemReasons(acct.ID)
+ if err != nil {
+ return err
+ }
+ if len(problems) > 0 {
+ return errCheckoutProblem
+ }
+ return nil
+}
+
+// sendSeatOpLocked prepares one change of the plan item to qty, its
+// proration timestamp the request's provider time, and sends it through
+// sendOpLocked. invite is the join it is for ("" for a reduction) and
+// authorisedBy the invite whose seat authorisation a charge consumes ("" for
+// a restore or a reduction). The start quantity is the item's, from the read
+// the change was computed from (ruling a).
+func (s *Server) sendSeatOpLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, kind string,
+ item billing.Item, qty int64, proration billing.Proration, invite, authorisedBy string, now time.Time) (opOutcome, *billing.Subscription, error) {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return opOutcome{}, nil, errNoProviderTimeRefusal
+ }
+ id := newOpID()
+ p, err := s.billing.cfg.Provider.PrepareChange(billing.ChangeRequest{Subscription: sub.ID,
+ Items: []billing.ItemChange{{ItemID: item.ItemID, Quantity: qty}},
+ Proration: proration, ProrationDate: pnow, IdempotencyKey: "op:" + id})
+ if err != nil {
+ return opOutcome{}, nil, err
+ }
+ op := billingOp{ID: id, AccountID: acct.ID, Subscription: sub.ID, Kind: kind, PeriodEnd: sub.PeriodEnd,
+ Target: opTarget{Quantities: map[string]int64{item.PriceID: qty}}, Prepared: p,
+ InviteToken: invite, AuthorisedBy: authorisedBy, StartQuantity: knownStart(item.Quantity)}
+ return s.sendOpLocked(h, ctx, op, now)
+}
+
+// ---- admission ---------------------------------------------------------------
+
+// admitOutcome is what an accept came to.
+type admitOutcome int
+
+const (
+ admitJoined admitOutcome = iota // a member now
+ admitWaitPayment // this invite's seat is waiting for payment, or was declined
+ admitNeedsConsent // a new paid seat the invite does not cover
+ admitOutstanding // another change is outstanding on the subscription, or a problem is open
+ admitUncertain // the seat's payment has no definite outcome yet, or the read failed
+ admitNearRenewal // a restore would be needed inside the renewal margin
+ admitRefused // the invite is gone, the cap is reached, or the account is retiring
+)
+
+// errAdmitRead is an accept that could not read what it needed.
+var errAdmitRead = errors.New("console: accept: read failed")
+
+// admitMember is one accept of an invite (Invariant 2), under the account's
+// member lock: the invite, the membership and the member cap are checked
+// again there; an account that is not a billing team joins through the
+// membership transition; a billing team's join is admitted under the billing
+// hold (admitSeatLocked). The error accompanies the outcome: a refusal's
+// reason (a billingRefusal or a planCapError) with admitRefused, otherwise
+// what to log.
+func (s *Server) admitMember(ctx context.Context, acct *Account, token, addr string, now time.Time) (admitOutcome, error) {
+ defer s.lockMembers(acct.Sqid)()
+ inv, err := s.store.PendingInviteFor(token, addr, now)
+ if err != nil || inv.AccountID != acct.ID {
+ return admitRefused, nil
+ }
+ role, err := s.store.Role(acct.ID, addr)
+ if err != nil {
+ return admitRefused, fmt.Errorf("%w: role: %w", errAdmitRead, err)
+ }
+ join := func() error {
+ return s.membershipTransition(ctx, acct, now, func(tx *sql.Tx) error {
+ _, err := acceptInviteTx(tx, token, addr, now)
+ return err
+ })
+ }
+ if role != "" {
+ // Already a member: the invite is spent and no seat is involved.
+ if err := join(); err != nil {
+ return admitRefused, err
+ }
+ return admitJoined, nil
+ }
+ if err := s.checkMemberCap(acct, 1); err != nil {
+ if isPlanCap(err) {
+ return admitRefused, err
+ }
+ return admitRefused, fmt.Errorf("%w: member cap: %w", errAdmitRead, err)
+ }
+ team, err := s.billingTeam(acct)
+ if err != nil {
+ return admitRefused, fmt.Errorf("%w: plan: %w", errAdmitRead, err)
+ }
+ if team == nil {
+ if err := join(); err != nil {
+ return admitRefused, err
+ }
+ return admitJoined, nil
+ }
+ ctx = s.billingClock(ctx)
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ return s.admitSeatLocked(h, ctx, acct, token, now, join)
+}
+
+// admitSeatLocked is a billing team's join under the hold. In order: refused
+// while retiring; the subscription's outstanding operation is finished (a
+// pending one refreshed); still outstanding is admitWaitPayment for this
+// invite's pending or declined seat, admitUncertain for this invite's seat
+// with no answer yet, and admitOutstanding for anything else; then the
+// allowance read, and capacity: need is the billed seats with one more
+// member, cur the plan item's quantity, paid the period's paid seats.
+//
+// - need <= cur: free, no write (a seat an earlier charge left, even inside
+// the renewal margin);
+// - cur < need <= paid: a restore to need, only outside the margin;
+// - need > paid: covered by the invite's authorisation or admitNeedsConsent;
+// then a restore to paid if paid > cur (margin rules), and the charge to
+// need only after a definite restore applied in the same period.
+//
+// An open problem refuses before anything is prepared. After a send the
+// membership is written, then the subscription refreshed; then the seat
+// observation runs on members+1, never reducing.
+func (s *Server) admitSeatLocked(h billingHold, ctx context.Context, acct *Account, token string, now time.Time, join func() error) (admitOutcome, error) {
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return admitUncertain, err
+ } else if retiring {
+ return admitRefused, errBillingRetiring
+ }
+ if out, err := s.finishSeatOpsLocked(h, ctx, acct, token, now); err != nil || out != admitJoined {
+ return out, err
+ }
+ b, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
+ if err != nil {
+ return admitUncertain, err
+ }
+ cfg, cat := s.billing.cfg, s.cfg.PlanCatalog
+ team := cat.Plans[purchase.Plan].Team
+ item, ok := billing.FindItem(sub, cfg.Prices, billing.KindPlan, purchase.Plan)
+ if team == nil || !ok {
+ return admitUncertain, errAllowanceMismatch
+ }
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return admitUncertain, err
+ }
+ need, cur, paid := int64(team.Billed(members+1)), item.Quantity, int64(b.PaidSeats)
+ if need <= cur {
+ if err := join(); err != nil {
+ return admitUncertain, err
+ }
+ return admitJoined, s.observeSeatsLocked(h, acct, members+1, false, now)
+ }
+ restoreTo, chargeTo := quantityPlan(cur, need, paid)
+ if chargeTo > 0 {
+ a, err := s.store.InviteSeatAuthorisation(token)
+ if err != nil {
+ return admitUncertain, err
+ }
+ if !seatCovered(a, b, cfg.Book) {
+ return admitNeedsConsent, nil
+ }
+ }
+ if restoreTo > 0 {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return admitUncertain, errNoProviderTimeRefusal
+ }
+ if sub.PeriodEnd.Sub(pnow) <= restoreMargin {
+ return admitNearRenewal, nil
+ }
+ }
+ if err := s.seatProblemLocked(h, acct); err != nil {
+ return admitOutstanding, err
+ }
+
+ if restoreTo > 0 {
+ out, rsub, err := s.sendSeatOpLocked(h, ctx, acct, sub, opRestore, item, restoreTo, billing.ProrateNone, token, "", now)
+ if err != nil {
+ return seatSendRefusal(err), err
+ }
+ if out.State != opApplied || rsub == nil || !rsub.PeriodEnd.Equal(sub.PeriodEnd) {
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitUncertain, nil
+ }
+ if chargeTo == 0 {
+ return s.joinAfterSendLocked(h, ctx, acct, members, now, join)
+ }
+ it, ok := itemOfPrice(rsub, item.PriceID)
+ if !ok {
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitUncertain, nil
+ }
+ item, sub = it, rsub
+ }
+ out, _, err := s.sendSeatOpLocked(h, ctx, acct, sub, opSeat, item, chargeTo, billing.ProrateNow, token, token, now)
+ if err != nil {
+ return seatSendRefusal(err), err
+ }
+ switch out.State {
+ case opApplied:
+ return s.joinAfterSendLocked(h, ctx, acct, members, now, join)
+ case opPending, opFailed:
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitWaitPayment, nil
+ }
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitUncertain, nil
+}
+
+// finishSeatOpsLocked finishes the operation outstanding on the account's
+// subscription, if any, and answers admitJoined when nothing is outstanding
+// afterwards (admission goes on), or the outcome that refuses it.
+func (s *Server) finishSeatOpsLocked(h billingHold, ctx context.Context, acct *Account, token string, now time.Time) (admitOutcome, error) {
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil || b == nil || b.Subscription == "" {
+ return admitJoined, err
+ }
+ op, err := s.store.OutstandingOp(b.Subscription)
+ if err != nil || op == nil {
+ return admitJoined, err
+ }
+ if op.State == opPending {
+ _, _, err = s.refreshLocked(h, ctx, acct, now)
+ } else {
+ _, err = s.finishOpLocked(h, ctx, acct, op, now)
+ }
+ if err != nil {
+ return admitUncertain, err
+ }
+ if op, err = s.store.OutstandingOp(b.Subscription); err != nil {
+ return admitUncertain, err
+ }
+ switch {
+ case op == nil:
+ return admitJoined, nil
+ case op.InviteToken == token && op.State == opPending:
+ return admitWaitPayment, nil
+ case op.InviteToken == token:
+ return admitUncertain, nil
+ }
+ return admitOutstanding, nil
+}
+
+// seatSendRefusal is the outcome for an error sendOpLocked returned before
+// anything was sent.
+func seatSendRefusal(err error) admitOutcome {
+ switch {
+ case errors.Is(err, errRestoreNearRenewal):
+ return admitNearRenewal
+ case errors.Is(err, ErrOpOutstanding):
+ return admitOutstanding
+ }
+ return admitUncertain
+}
+
+// joinAfterSendLocked writes the membership a definite seat paid for, then
+// refreshes the subscription and observes the seats at members+1.
+func (s *Server) joinAfterSendLocked(h billingHold, ctx context.Context, acct *Account, members int, now time.Time, join func() error) (admitOutcome, error) {
+ if err := join(); err != nil {
+ // The seat stays paid for: a credit for the next admission.
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitUncertain, err
+ }
+ s.settleSeatsLocked(h, ctx, acct, now)
+ return admitJoined, s.observeSeatsLocked(h, acct, members+1, false, now)
+}
+
+// settleSeatsLocked refreshes the subscription after a seat send, so the
+// stored row shows what the provider holds. A failed refresh only defers
+// that to the next read: the outcome is recorded.
+func (s *Server) settleSeatsLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) {
+ if _, _, err := s.refreshLocked(h, ctx, acct, now); err != nil {
+ log.Printf("console: billing seats %s: refresh after the send: %v", acct.Sqid, err)
+ }
+}
+
+// ---- observation, reduction and the seats_unpaid close ----------------------
+
+// observeSeatsLocked records what the stored billing row says about the
+// account's seats at members, with no provider request and no reduction:
+// drift when the plan item's quantity is above the members billed, and
+// seats_unpaid opened when the members billed exceed the period's paid seats
+// and closed when they no longer do. daily is the pass: an open seats_unpaid
+// is reconsidered at most every seatRecheck (from seats_checked_at).
+func (s *Server) observeSeatsLocked(h billingHold, acct *Account, members int, daily bool, now time.Time) error {
+ _ = h
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil || b == nil || !b.Live || b.State != billing.StatePaid {
+ return err
+ }
+ p, ok := s.cfg.PlanCatalog.Plans[b.Plan]
+ if !ok || p.Team == nil {
+ return nil
+ }
+ billed := p.Team.Billed(members)
+ driftAt, driftMembers := time.Time{}, 0
+ if b.Seats > billed {
+ driftAt, driftMembers = b.SeatDriftAt, members
+ if driftAt.IsZero() {
+ driftAt = now
+ }
+ }
+ reasons, err := s.store.OpenBillingProblemReasons(acct.ID)
+ if err != nil {
+ return err
+ }
+ open := slices.Contains(reasons, problemSeatsUnpaid)
+ checked := b.SeatsCheckedAt
+ if !daily || !open || now.Sub(checked) >= seatRecheck {
+ checked = now
+ switch {
+ case billed > b.PaidSeats:
+ if err := s.openBillingProblem(acct.ID, acct.Sqid, b.Subscription, problemSeatsUnpaid,
+ fmt.Sprintf("%d members, %d paid seats", members, b.PaidSeats), now); err != nil {
+ return err
+ }
+ case open:
+ if _, err := s.store.CloseBillingProblemsByReason(acct.ID, problemSeatsUnpaid, planBilling,
+ fmt.Sprintf("%d members, %d paid seats", members, b.PaidSeats), now); err != nil {
+ return err
+ }
+ }
+ }
+ return s.store.PutSeatObservation(acct.ID, driftAt, driftMembers, checked)
+}
+
+// reconcileSeatsLocked matches the plan item to members, for a removal and
+// the owner's Match seats: refused while retiring; the outstanding operation
+// finished (still outstanding refuses); the allowance read; then, when the
+// item's quantity is above the members billed, one ProrateNone reduction
+// (Call 12: it takes effect at renewal; the period's paid seats stay), and
+// the refresh after it; then the seat observation. It answers the
+// reduction's outcome, with a zero State when nothing was sent.
+func (s *Server) reconcileSeatsLocked(h billingHold, ctx context.Context, acct *Account, members int, now time.Time) (opOutcome, error) {
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return opOutcome{}, err
+ } else if retiring {
+ return opOutcome{}, errBillingRetiring
+ }
+ if err := s.finishOutstandingLocked(h, ctx, acct, now); err != nil {
+ return opOutcome{}, err
+ }
+ _, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
+ if err != nil {
+ return opOutcome{}, err
+ }
+ team := s.cfg.PlanCatalog.Plans[purchase.Plan].Team
+ if team == nil {
+ return opOutcome{}, nil
+ }
+ item, ok := billing.FindItem(sub, s.billing.cfg.Prices, billing.KindPlan, purchase.Plan)
+ if !ok {
+ return opOutcome{}, errAllowanceMismatch
+ }
+ var out opOutcome
+ if want := int64(team.Billed(members)); item.Quantity > want {
+ if err := s.seatProblemLocked(h, acct); err != nil {
+ return opOutcome{}, err
+ }
+ if out, _, err = s.sendSeatOpLocked(h, ctx, acct, sub, opSeat, item, want, billing.ProrateNone, "", "", now); err != nil {
+ return opOutcome{}, err
+ }
+ s.settleSeatsLocked(h, ctx, acct, now)
+ }
+ return out, s.observeSeatsLocked(h, acct, members, false, now)
+}
+
+// closeSeatsUnpaidLocked is the seats_unpaid close under the hold: a fresh
+// read of the subscription, then the account's open seats_unpaid problems
+// close only when the members billed are within the period's paid seats.
+// It answers whether they closed.
+func (s *Server) closeSeatsUnpaidLocked(h billingHold, ctx context.Context, acct *Account, by, note string, now time.Time) (bool, error) {
+ b, _, err := s.refreshLocked(h, ctx, acct, now)
+ if err != nil {
+ return false, err
+ }
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return false, err
+ }
+ if b != nil {
+ if p, ok := s.cfg.PlanCatalog.Plans[b.Plan]; ok && p.Team != nil && p.Team.Billed(members) > b.PaidSeats {
+ return false, nil
+ }
+ }
+ _, err = s.store.CloseBillingProblemsByReason(acct.ID, problemSeatsUnpaid, by, note, now)
+ return err == nil, err
+}
+
+// observeSeats is the pass's seat observation for one account, after its
+// sync: under the hold, the stored row against the members counted now.
+// Reads and local writes only.
+func (s *Server) observeSeats(accountID int64, now time.Time) {
+ acct, err := s.store.AccountByID(accountID)
+ if err != nil || acct == nil {
+ return
+ }
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ members, err := s.store.MemberCount(acct.ID)
+ if err == nil {
+ err = s.observeSeatsLocked(h, acct, members, true, now)
+ }
+ if err != nil {
+ log.Printf("console: billing seats pass: account %d: %v", accountID, err)
+ }
+}
+
+// ---- the invite's seat step -----------------------------------------------
+
+// seatQuote is the invite confirm page's estimate for a new paid seat.
+type seatQuote struct {
+ To, Currency string
+ Estimate int64
+ Known bool
+}
+
+// inviteSeatLocked is the billing step of an invite on a billing team (Calls
+// 6 and 11), under the member lock and the hold: the allowance read; with
+// the members, the pending invites and this one billed above the plan
+// item's quantity and the period's paid seats, the invite needs a new paid
+// seat. Unconfirmed, that is a quote; confirmed (after a fresh sign-in
+// proof), the seat authorisation to record: the subscription's plan, book,
+// currency and per-seat price now. No seat needed is neither.
+func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Account, pending int, to, by string, confirmed bool, now time.Time) (*seatQuote, *seatAuthorisation, error) {
+ b, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
+ if err != nil {
+ return nil, nil, err
+ }
+ cfg := s.billing.cfg
+ team := s.cfg.PlanCatalog.Plans[purchase.Plan].Team
+ item, ok := billing.FindItem(sub, cfg.Prices, billing.KindPlan, purchase.Plan)
+ if team == nil || !ok {
+ return nil, nil, errAllowanceMismatch
+ }
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return nil, nil, err
+ }
+ if int64(team.Billed(members+pending+1)) <= max(item.Quantity, int64(b.PaidSeats)) {
+ return nil, nil, nil
+ }
+ if err := s.seatProblemLocked(h, acct); err != nil {
+ return nil, nil, err
+ }
+ price, known := s.configuredPrice(purchase.Book, billing.KindPlan, purchase.Plan, sub.Currency)
+ if !confirmed {
+ q := &seatQuote{To: to, Currency: sub.Currency}
+ if known {
+ if pnow, err := s.providerNow(ctx); err == nil {
+ q.Estimate, q.Known = prorateEstimate(price, 1, pnow, sub.PeriodEnd), true
+ }
+ }
+ return q, nil, nil
+ }
+ return nil, &seatAuthorisation{Plan: purchase.Plan, Book: purchase.Book, Currency: sub.Currency, PriceMinor: price, By: by, At: now}, nil
+}
+
+// renderInviteConfirm is the invite's confirm page for a new paid seat: the
+// estimate, and a form posting the same invite with confirmed=1.
+func (s *Server) renderInviteConfirm(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, q seatQuote) {
+ line := billingCopy["change.no_estimate"]
+ if q.Known {
+ line = fmt.Sprintf(billingCopy["seats.invite_line"], q.To, plans.FormatMinor(q.Currency, q.Estimate))
+ }
+ p := s.accountPage(w, r, addr, raw, acct, RoleOwner)
+ p.Title = billingCopy["confirm.title"]
+ p.AppName = acct.Name
+ p.ActiveNav = "team"
+ p.Confirm = &ConfirmView{
+ Title: billingCopy["confirm.title"],
+ Lines: []string{line},
+ Action: "/a/" + acct.Sqid + "/invite",
+ Fields: [][2]string{{"csrf", raw}, {"address", q.To}},
+ Button: billingCopy["confirm.button"],
+ CancelURL: "/a/" + acct.Sqid + "/team",
+ }
+ s.render(w, http.StatusOK, "confirm_action", p)
+}
+
+// ---- Match seats -------------------------------------------------------------
+
+// handleBillingSeats is POST /a/{sqid}/billing/seats: an owner's Match seats
+// to members. Billing off answers 404, a member the owner gate's 404, no
+// CSRF 403. A reduction charges nothing, so no sign-in proof (Call 6). Under
+// the member lock and the hold, the plan item is reduced to the members
+// billed (reconcileSeatsLocked); the flash is the reduction's outcome.
+func (s *Server) handleBillingSeats(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ _, raw, acct, ok := s.owner(w, r)
+ if !ok {
+ return
+ }
+ if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return
+ }
+ back := billingPagePath(acct.Sqid)
+ if !s.billing.ready.Load() {
+ s.setFlash(w, "err", billingCopy["change.failed"])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ unlock := s.lockMembers(acct.Sqid)
+ h, release := s.holdBilling(acct.Sqid)
+ members, err := s.store.MemberCount(acct.ID)
+ var out opOutcome
+ if err == nil {
+ out, err = s.reconcileSeatsLocked(h, ctx, acct, members, now)
+ }
+ release()
+ unlock()
+ switch {
+ case err != nil:
+ s.setFlash(w, "err", changeText(acct.Sqid, err))
+ case out.State != "":
+ kind, key := outcomeCopy(out)
+ s.setFlash(w, kind, billingCopy[key])
+ }
+ http.Redirect(w, r, back, http.StatusSeeOther)
+}
+
+// admitText is the accept page's message for an outcome other than joined
+// or refused.
+func admitText(out admitOutcome) string {
+ switch out {
+ case admitWaitPayment:
+ return billingCopy["seats.join_wait"]
+ case admitNeedsConsent:
+ return billingCopy["seats.join_consent"]
+ case admitOutstanding:
+ return billingCopy["seats.join_busy"]
+ case admitNearRenewal:
+ return billingCopy["seats.join_near_renewal"]
+ }
+ return billingCopy["seats.join_uncertain"]
+}
diff --git a/internal/console/billingseats_test.go b/internal/console/billingseats_test.go
new file mode 100644
index 000000000..3cc3ab321
--- /dev/null
+++ b/internal/console/billingseats_test.go
@@ -0,0 +1,962 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "html"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/billing/billingtest"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// ---- fixture -----------------------------------------------------------------
+
+// newSeatsFixture is an ops fixture whose account is on a Community
+// subscription with seats on its plan item, members people in the account
+// (the owner included), synced, the owner signed in with no fresh sign-in
+// proof, counters reset.
+func newSeatsFixture(t *testing.T, members int, seats int64) *opsFixture {
+ t.Helper()
+ bf := newBillingFixture(t)
+ bf.srv.billing.ready.Store(true)
+ o := &opsFixture{billingFixture: bf}
+ o.wire()
+ fillMembers(t, bf.consoleFixture, bf.acct.ID, members)
+ bf.put(bf.teamSub("sub_1", "community", "active", seats))
+ if err := bf.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.signInOwner(t)
+ if err := o.st.ClearStepUp(o.csrf); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ return o
+}
+
+func communityPrice() string { return testPriceID("example-v1/community/usd") }
+
+func (o *opsFixture) ownerAddr() string { return "owner" + o.acct.Sqid + "@example.com" }
+
+// seatQty is the plan item's quantity at the provider.
+func (o *opsFixture) seatQty(t *testing.T) int64 {
+ t.Helper()
+ for _, it := range o.sub("sub_1").Items {
+ if it.PriceID == communityPrice() {
+ return it.Quantity
+ }
+ }
+ t.Fatal("no plan item")
+ return 0
+}
+
+// setSeats moves the plan item at the provider (a change the console did not
+// make) and syncs it, so the period's paid seats keep their highest.
+func (o *opsFixture) setSeats(t *testing.T, q int64) {
+ t.Helper()
+ o.setQuantity("sub_1", communityPrice(), q)
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+}
+
+func (o *opsFixture) billingRow(t *testing.T) *billingAccount {
+ t.Helper()
+ b, err := o.st.BillingAccount(o.acct.ID)
+ if err != nil || b == nil {
+ t.Fatalf("billing row %+v: %v", b, err)
+ }
+ return b
+}
+
+func (o *opsFixture) members(t *testing.T) int { return memberCount(t, o.consoleFixture, o.acct.ID) }
+
+type invitee struct {
+ c *http.Client
+ csrf, addr string
+}
+
+// invitee signs addr in with a browser of its own.
+func (o *opsFixture) invitee(t *testing.T, addr string) invitee {
+ t.Helper()
+ o.setUser(addr)
+ c := newBrowser(t)
+ signUp(t, o.consoleFixture, c, "code-"+addr)
+ in := invitee{c: c, csrf: sessionToken(t, o.consoleFixture, c), addr: addr}
+ o.setUser(o.ownerAddr())
+ return in
+}
+
+// plainInvite is an invite with no seat authorisation.
+func (o *opsFixture) plainInvite(t *testing.T, addr string) string {
+ t.Helper()
+ tok, err := o.st.CreateInvite(o.acct.ID, addr, o.ownerAddr(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tok
+}
+
+// authorisedInvite is an invite carrying the owner's authorisation for a
+// Community seat at the configured book's price.
+func (o *opsFixture) authorisedInvite(t *testing.T, addr string) string {
+ t.Helper()
+ tok := o.plainInvite(t, addr)
+ book := o.srv.billing.cfg.Book
+ price, _ := book.PlanPrice("community", "usd")
+ if err := o.st.SetInviteSeatAuthorisation(tok, seatAuthorisation{Plan: "community", Book: book.Version, Currency: "usd",
+ PriceMinor: price, By: o.ownerAddr(), At: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ return tok
+}
+
+func (o *opsFixture) authorisation(t *testing.T, tok string) *seatAuthorisation {
+ t.Helper()
+ a, err := o.st.InviteSeatAuthorisation(tok)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return a
+}
+
+// accept is in's Join button for tok, served by the current server.
+func (o *opsFixture) accept(in invitee, tok string) billingReply {
+ form := url.Values{"csrf": {in.csrf}}
+ req := httptest.NewRequest(http.MethodPost, o.ts.URL+"/invite/"+url.PathEscape(tok), strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ u, _ := url.Parse(o.ts.URL)
+ for _, ck := range in.c.Jar.Cookies(u) {
+ if ck.Name != flashCookie {
+ req.AddCookie(ck)
+ }
+ }
+ rr := httptest.NewRecorder()
+ o.srv.ServeHTTP(rr, req)
+ return billingReply{Status: rr.Code, Loc: rr.Header().Get("Location"), Body: rr.Body.String()}
+}
+
+func (o *opsFixture) wantJoined(t *testing.T, r billingReply) {
+ t.Helper()
+ if r.Status != http.StatusSeeOther || r.Loc != "/a/"+o.acct.Sqid+"/" {
+ t.Fatalf("accept = %d %q, want joined\n%s", r.Status, r.Loc, r.Body)
+ }
+}
+
+func wantAdmit(t *testing.T, r billingReply, key string) {
+ t.Helper()
+ if r.Status != http.StatusConflict || !strings.Contains(r.Body, html.EscapeString(billingCopy[key])) {
+ t.Fatalf("accept = %d %q, want 409 with %s\n%s", r.Status, r.Loc, key, r.Body)
+ }
+}
+
+func (o *opsFixture) teamPath(op string) string { return "/a/" + o.acct.Sqid + op }
+
+func (o *opsFixture) removeMember(t *testing.T, addr string) billingReply {
+ t.Helper()
+ o.stepUp(t)
+ return o.request(t, http.MethodPost, o.teamPath("/members/remove"), url.Values{"address": {addr}})
+}
+
+func (o *opsFixture) revoke(t *testing.T, tok string) billingReply {
+ t.Helper()
+ return o.request(t, http.MethodPost, o.teamPath("/invite/revoke"), url.Values{"token": {tok}})
+}
+
+func (o *opsFixture) pendingInvite(t *testing.T, tok string) bool {
+ t.Helper()
+ _, ok := o.st.PendingInviteAddress(tok, time.Now())
+ return ok
+}
+
+func (o *opsFixture) seatsUnpaidOpen(t *testing.T) bool {
+ t.Helper()
+ for _, r := range o.openProblems(t) {
+ if r == problemSeatsUnpaid {
+ return true
+ }
+ }
+ return false
+}
+
+// ---- invites ---------------------------------------------------------------------
+
+func TestInviteRecordsSeatAuthorisation(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ to := "new@example.com"
+ invite := func(confirmed bool) billingReply {
+ form := url.Values{"address": {to}}
+ if confirmed {
+ form.Set("confirmed", "1")
+ }
+ return o.request(t, http.MethodPost, o.teamPath("/invite"), form)
+ }
+
+ // A new paid seat: the confirm page with the per-seat estimate, and no
+ // invite yet. One read.
+ r := invite(false)
+ price, _ := o.srv.billing.cfg.Book.PlanPrice("community", "usd")
+ if r.Status != http.StatusOK || !strings.Contains(r.Body, `name="confirmed" value="1"`) || !strings.Contains(r.Body, `value="`+to+`"`) {
+ t.Fatalf("unconfirmed invite = %d %q\n%s", r.Status, r.Loc, r.Body)
+ }
+ want := prorateEstimate(price, 1, o.providerClock(), periodEnd)
+ if est := fmt.Sprintf(billingCopy["seats.invite_line"], to, plans.FormatMinor("usd", want)); !strings.Contains(r.Body, html.EscapeString(est)) {
+ t.Fatalf("the confirm page lacks the estimate %q\n%s", est, r.Body)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if inv, _ := o.st.PendingInvites(o.acct.ID); len(inv) != 0 {
+ t.Fatalf("an unconfirmed paid seat created an invite: %+v", inv)
+ }
+
+ // Confirmed without a fresh sign-in proof: no invite.
+ if r := invite(true); r.Status == http.StatusSeeOther && r.Loc == o.teamPath("/team") {
+ t.Fatalf("a confirmed invite went through without a fresh proof: %+v", r)
+ }
+ if inv, _ := o.st.PendingInvites(o.acct.ID); len(inv) != 0 {
+ t.Fatalf("an invite without a fresh proof: %+v", inv)
+ }
+
+ // Confirmed with one: the invite and its authorisation.
+ o.stepUp(t)
+ if r := invite(true); r.Status != http.StatusSeeOther || r.Loc != o.teamPath("/team") {
+ t.Fatalf("confirmed invite = %+v", r)
+ }
+ inv, _ := o.st.PendingInvites(o.acct.ID)
+ if len(inv) != 1 || inv[0].Address != to {
+ t.Fatalf("invites = %+v", inv)
+ }
+ a := o.authorisation(t, inv[0].Token)
+ if a == nil || a.Plan != "community" || a.Book != o.srv.billing.cfg.Book.Version || a.Currency != "usd" || a.PriceMinor != price ||
+ a.By != o.ownerAddr() || a.At.IsZero() || !a.ConsumedAt.IsZero() {
+ t.Fatalf("authorisation = %+v", a)
+ }
+
+ // With a seat to spare (12 seats, 10 members, and that invite pending),
+ // an invite needs no confirmation and carries no authorisation.
+ o.setSeats(t, 12)
+ r = o.request(t, http.MethodPost, o.teamPath("/invite"), url.Values{"address": {"spare@example.com"}})
+ if r.Status != http.StatusSeeOther || r.Loc != o.teamPath("/team") {
+ t.Fatalf("spare-seat invite = %+v", r)
+ }
+ inv, _ = o.st.PendingInvites(o.acct.ID)
+ for _, i := range inv {
+ if i.Address == "spare@example.com" && o.authorisation(t, i.Token) != nil {
+ t.Fatal("a spare seat's invite carries an authorisation")
+ }
+ }
+}
+
+// ---- admission -------------------------------------------------------------------
+
+func TestJoinChargesAuthorisedSeat(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.reset()
+ o.wantJoined(t, o.accept(in, tok))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ if o.members(t) != 11 || o.seatQty(t) != 11 {
+ t.Fatalf("members %d seats %d, want 11 and 11", o.members(t), o.seatQty(t))
+ }
+ op := o.lastOp(t)
+ if op.Kind != opSeat || op.State != opApplied || op.InviteToken != tok || op.AuthorisedBy != tok ||
+ op.StartQuantity == nil || *op.StartQuantity != 10 || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNow {
+ t.Fatalf("op = %+v", op)
+ }
+ if a := o.authorisation(t, tok); a == nil || a.ConsumedAt.IsZero() {
+ t.Fatalf("authorisation not consumed: %+v", a)
+ }
+ if b := o.billingRow(t); b.PaidSeats != 11 || b.Seats != 11 {
+ t.Fatalf("billing row seats %d paid %d", b.Seats, b.PaidSeats)
+ }
+}
+
+func TestJoinWaitsForPayment(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.FailPayment = 1
+ o.fake.Unlock()
+ wantAdmit(t, o.accept(in, tok), "seats.join_wait")
+ if o.members(t) != 10 || !o.pendingInvite(t, tok) || o.lastOp(t).State != opPending {
+ t.Fatalf("members %d invite pending %v op %+v", o.members(t), o.pendingInvite(t, tok), o.lastOp(t))
+ }
+ // Still waiting: the same answer, nothing sent.
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "seats.join_wait")
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ // Paid later: the next accept settles it and joins with no new charge.
+ if err := o.fake.PayPending("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.wantJoined(t, o.accept(in, tok))
+ if c := o.counts(); c["Send"] != 0 || o.members(t) != 11 {
+ t.Fatalf("after payment: counts %v members %d", c, o.members(t))
+ }
+ if a := o.authorisation(t, tok); a.ConsumedAt.IsZero() {
+ t.Fatal("the paid seat did not consume its authorisation")
+ }
+}
+
+func TestJoinNeedsConsentWithoutAuthorisation(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.plainInvite(t, in.addr)
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "seats.join_consent")
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if o.members(t) != 10 || len(o.ops(t)) != 0 || !o.pendingInvite(t, tok) {
+ t.Fatalf("members %d ops %d", o.members(t), len(o.ops(t)))
+ }
+}
+
+func TestJoinNeedsConsentAfterPlanSwitch(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ // The account moves to Business after the invite was authorised.
+ o.put(o.teamSub("sub_1", "business", "active", 10))
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "seats.join_consent")
+ if c := o.counts(); c["Send"] != 0 || o.members(t) != 10 {
+ t.Fatalf("counts %v members %d", c, o.members(t))
+ }
+}
+
+func TestConcurrentJoinsShareNoSeat(t *testing.T) {
+ o := newSeatsFixture(t, 10, 11) // one paid seat to spare
+ a, b := o.invitee(t, "a@example.com"), o.invitee(t, "b@example.com")
+ ta, tb := o.plainInvite(t, a.addr), o.plainInvite(t, b.addr)
+ o.reset()
+ var wg sync.WaitGroup
+ replies := make([]billingReply, 2)
+ for i, p := range []struct {
+ in invitee
+ tok string
+ }{{a, ta}, {b, tb}} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ replies[i] = o.accept(p.in, p.tok)
+ }()
+ }
+ wg.Wait()
+ joined, consent := 0, 0
+ for _, r := range replies {
+ switch {
+ case r.Status == http.StatusSeeOther:
+ joined++
+ case r.Status == http.StatusConflict && strings.Contains(r.Body, html.EscapeString(billingCopy["seats.join_consent"])):
+ consent++
+ }
+ }
+ if joined != 1 || consent != 1 || o.members(t) != 11 || o.counts()["Send"] != 0 {
+ t.Fatalf("joined %d consent %d members %d counts %v", joined, consent, o.members(t), o.counts())
+ }
+}
+
+// failJoins makes every membership insert fail until the returned func
+// drops the trigger.
+func (o *opsFixture) failJoins(t *testing.T) func() {
+ t.Helper()
+ if _, err := o.st.db.Exec(`CREATE TRIGGER fail_join BEFORE INSERT ON memberships BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ return func() {
+ if _, err := o.st.db.Exec(`DROP TRIGGER fail_join`); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestAppliedInviteChargeIsACreditNotAPass(t *testing.T) { appliedChargeIsACredit(t, nil) }
+
+// appliedChargeIsACredit: A's charge applies on the definite path, then A's
+// membership write fails; B joins on that seat with no write (at provider
+// time beforeB, when set); A's retry needs consent. One Send in all.
+func appliedChargeIsACredit(t *testing.T, beforeB func(o *opsFixture)) {
+ o := newSeatsFixture(t, 10, 10)
+ a, b := o.invitee(t, "a@example.com"), o.invitee(t, "b@example.com")
+ ta, tb := o.authorisedInvite(t, a.addr), o.plainInvite(t, b.addr)
+ o.reset()
+ restore := o.failJoins(t)
+ wantAdmit(t, o.accept(a, ta), "seats.join_uncertain")
+ restore()
+ if o.members(t) != 10 || o.seatQty(t) != 11 || o.lastOp(t).State != opApplied {
+ t.Fatalf("after A: members %d seats %d op %+v", o.members(t), o.seatQty(t), o.lastOp(t))
+ }
+ if au := o.authorisation(t, ta); au.ConsumedAt.IsZero() {
+ t.Fatal("A's applied charge did not consume its authorisation")
+ }
+ if beforeB != nil {
+ beforeB(o)
+ }
+ o.wantJoined(t, o.accept(b, tb))
+ wantAdmit(t, o.accept(a, ta), "seats.join_consent")
+ if o.members(t) != 11 || o.billingRow(t).PaidSeats != 11 || o.seatQty(t) != 11 {
+ t.Fatalf("members %d paid %d seats %d", o.members(t), o.billingRow(t).PaidSeats, o.seatQty(t))
+ }
+ if n := o.counts()["Send"]; n != 1 {
+ t.Fatalf("Send = %d in total, want 1", n)
+ }
+}
+
+func TestJoinUsesPresentPaidSeatInsideMargin(t *testing.T) {
+ appliedChargeIsACredit(t, func(o *opsFixture) {
+ // B accepts a day before the renewal, in provider time.
+ o.fake.SetProviderClock(periodEnd.Add(-24 * time.Hour))
+ })
+}
+
+func TestJoinNeverReduces(t *testing.T) {
+ o := newSeatsFixture(t, 10, 13)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.plainInvite(t, in.addr)
+ o.reset()
+ before := o.fake.Writes()
+ o.wantJoined(t, o.accept(in, tok))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if o.fake.Writes() != before || o.seatQty(t) != 13 || o.members(t) != 11 {
+ t.Fatalf("writes %d->%d seats %d members %d", before, o.fake.Writes(), o.seatQty(t), o.members(t))
+ }
+ b := o.billingRow(t)
+ if b.SeatDriftAt.IsZero() || b.SeatDriftMembers != 11 {
+ t.Fatalf("drift not recorded: %+v", b)
+ }
+ page := o.request(t, http.MethodGet, o.billingBase(), nil)
+ if notice := fmt.Sprintf(billingCopy["notice.seat_drift"], 13, 11); !strings.Contains(page.Body, html.EscapeString(notice)) {
+ t.Fatalf("the page does not show the drift %q", notice)
+ }
+}
+
+func TestConsumptionIsAtomicWithApplied(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ tok := o.authorisedInvite(t, "kim@example.com")
+ op := billingOp{ID: "op_seat", AccountID: o.acct.ID, Subscription: "sub_1", Kind: opSeat, PeriodEnd: periodEnd,
+ Target: opTarget{Quantities: map[string]int64{communityPrice(): 11}}, Prepared: billing.Prepared{Key: "op:op_seat"},
+ InviteToken: tok, AuthorisedBy: tok, StartQuantity: knownStart(10), CreatedAt: billingNow}
+ o.unresolved(t, op)
+ // The consumption fails: the operation is not applied either.
+ if _, err := o.st.db.Exec(`CREATE TRIGGER fail_consume BEFORE UPDATE OF seat_consumed_at ON invites BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.st.MarkOpApplied("op_seat", periodEnd, billingNow); err == nil {
+ t.Fatal("applied without consuming the authorisation")
+ }
+ if got := o.op(t, "op_seat"); got.State != opUnresolved {
+ t.Fatalf("op = %+v, want unresolved", got)
+ }
+ if a := o.authorisation(t, tok); !a.ConsumedAt.IsZero() {
+ t.Fatal("consumed without applying")
+ }
+ if _, err := o.st.db.Exec(`DROP TRIGGER fail_consume`); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.st.MarkOpApplied("op_seat", periodEnd, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if got, a := o.op(t, "op_seat"), o.authorisation(t, tok); got.State != opApplied || !a.ConsumedAt.Equal(time.Unix(billingNow.Unix(), 0)) {
+ t.Fatalf("op %+v authorisation %+v", got, a)
+ }
+ // Single use: a second application consumes nothing more and an
+ // authorisation is never renewed in place.
+ if err := o.st.SetInviteSeatAuthorisation(tok, seatAuthorisation{Plan: "community", Book: "example-v1", Currency: "usd", PriceMinor: 1}); err == nil {
+ t.Fatal("a consumed authorisation was replaced")
+ }
+}
+
+// unresolvedSeat is A's authorised accept whose charge never reaches the
+// provider (every handler retry lost): the op is left unresolved.
+func (o *opsFixture) unresolvedSeat(t *testing.T, in invitee) string {
+ t.Helper()
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = handlerRetries + 1
+ o.fake.Unlock()
+ wantAdmit(t, o.accept(in, tok), "seats.join_uncertain")
+ if op := o.lastOp(t); op.State != opUnresolved || op.InviteToken != tok {
+ t.Fatalf("op = %+v, want this invite's unresolved seat", op)
+ }
+ return tok
+}
+
+func TestRevokeRefusedWhileUnresolved(t *testing.T) {
+ wantRevokeWait := func(t *testing.T, o *opsFixture, tok string) {
+ t.Helper()
+ r := o.revoke(t, tok)
+ if r.Status != http.StatusSeeOther || r.Flash != "err" || r.FlashMsg != billingCopy["seats.revoke_wait"] || !o.pendingInvite(t, tok) {
+ t.Fatalf("revoke = %+v pending %v", r, o.pendingInvite(t, tok))
+ }
+ }
+ t.Run("unresolved", func(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ tok := o.unresolvedSeat(t, o.invitee(t, "kim@example.com"))
+ wantRevokeWait(t, o, tok)
+ })
+ t.Run("pending", func(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.FailPayment = 1
+ o.fake.Unlock()
+ wantAdmit(t, o.accept(in, tok), "seats.join_wait")
+ wantRevokeWait(t, o, tok)
+ })
+ t.Run("sending", func(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ tok := o.authorisedInvite(t, "kim@example.com")
+ if err := o.st.BeginBillingOp(billingOp{ID: "op_s", AccountID: o.acct.ID, Subscription: "sub_1", Kind: opSeat, PeriodEnd: periodEnd,
+ Target: opTarget{Quantities: map[string]int64{communityPrice(): 11}}, Prepared: billing.Prepared{Key: "op:op_s"},
+ InviteToken: tok, AuthorisedBy: tok, StartQuantity: knownStart(10), CreatedAt: billingNow}); err != nil {
+ t.Fatal(err)
+ }
+ wantRevokeWait(t, o, tok)
+ })
+ t.Run("settled", func(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.DeclineHard = 1
+ o.fake.Unlock()
+ wantAdmit(t, o.accept(in, tok), "seats.join_wait")
+ if r := o.revoke(t, tok); r.Flash != "ok" || o.pendingInvite(t, tok) {
+ t.Fatalf("a declined seat's invite was not revoked: %+v", r)
+ }
+ })
+}
+
+func TestConfirmNeverSendsForAGoneInvite(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ tok := o.unresolvedSeat(t, o.invitee(t, "kim@example.com"))
+ opID := o.lastOp(t).ID
+ // The invite expires.
+ if _, err := o.st.db.Exec(`UPDATE invites SET expires_at = 1 WHERE token = ?`, tok); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ other := o.invitee(t, "lee@example.com")
+ wantAdmit(t, o.accept(other, o.authorisedInvite(t, other.addr)), "seats.join_busy")
+ if c := o.counts(); c["Send"] != 0 {
+ t.Fatalf("a gone invite's request was sent: %v", c)
+ }
+ if op := o.op(t, opID); op.State != opUnresolved {
+ t.Fatalf("op = %+v, want still unresolved", op)
+ }
+ // A positive read still settles it.
+ o.setQuantity("sub_1", communityPrice(), 11)
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ if op := o.op(t, opID); op.State != opApplied {
+ t.Fatalf("op = %+v, want applied by the read", op)
+ }
+ if c := o.counts(); c["Send"] != 0 {
+ t.Fatalf("counts = %v", c)
+ }
+}
+
+func TestJoinUnresolvedFinishedOnRetry(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.unresolvedSeat(t, in)
+ o.reset()
+ o.wantJoined(t, o.accept(in, tok))
+ // F (one read, one resend of the stored bytes), then the allowance read:
+ // the seat is now there, so the join writes nothing more.
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ if o.members(t) != 11 || o.seatQty(t) != 11 || o.lastOp(t).State != opApplied || len(o.ops(t)) != 1 {
+ t.Fatalf("members %d seats %d ops %+v", o.members(t), o.seatQty(t), o.ops(t))
+ }
+}
+
+func TestJoinFailBeforeDeliveryResent(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 1
+ o.fake.Unlock()
+ o.reset()
+ o.wantJoined(t, o.accept(in, tok))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 2})
+ sent := o.sent()
+ if len(sent) != 2 || sent[0].Key != sent[1].Key || string(sent[0].Body) != string(sent[1].Body) {
+ t.Fatalf("resend not verbatim: %+v", sent)
+ }
+ if o.members(t) != 11 || o.seatQty(t) != 11 {
+ t.Fatalf("members %d seats %d", o.members(t), o.seatQty(t))
+ }
+}
+
+func TestSeatRestoreRefusedNearRenewal(t *testing.T) {
+ o := newSeatsFixture(t, 10, 11)
+ o.setSeats(t, 10) // paid 11, the plan item at 10
+ in := o.invitee(t, "kim@example.com")
+ tok := o.plainInvite(t, in.addr)
+ o.fake.SetProviderClock(periodEnd.Add(-24 * time.Hour))
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "seats.join_near_renewal")
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if len(o.ops(t)) != 0 || o.members(t) != 10 {
+ t.Fatalf("ops %+v members %d", o.ops(t), o.members(t))
+ }
+ // Outside the margin it is a free restore.
+ o.fake.SetProviderClock(periodEnd.Add(-26 * time.Hour))
+ o.wantJoined(t, o.accept(in, tok))
+ if op := o.lastOp(t); op.Kind != opRestore || o.seatQty(t) != 11 || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNone {
+ t.Fatalf("op = %+v seats %d", op, o.seatQty(t))
+ }
+}
+
+func TestRevokedInviteStartsNoPurchase(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ if r := o.revoke(t, tok); r.Flash != "ok" {
+ t.Fatalf("revoke = %+v", r)
+ }
+ o.reset()
+ if r := o.accept(in, tok); r.Status != http.StatusGone {
+ t.Fatalf("accept of a revoked invite = %d", r.Status)
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+ if o.members(t) != 10 || len(o.ops(t)) != 0 {
+ t.Fatalf("members %d ops %d", o.members(t), len(o.ops(t)))
+ }
+}
+
+func TestJoinAfterDelayedRenewal(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ // The subscription renews; the console has not seen it.
+ if err := o.fake.Renew("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.wantJoined(t, o.accept(in, tok))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ renewed := periodEnd.AddDate(1, 0, 0)
+ if op := o.lastOp(t); op.Kind != opSeat || !op.PeriodEnd.Equal(renewed) || op.State != opApplied {
+ t.Fatalf("op = %+v, want a charge in the renewed period", op)
+ }
+ if b := o.billingRow(t); !b.PaidPeriodEnd.Equal(renewed) || b.PaidSeats != 11 {
+ t.Fatalf("billing row = %+v", b)
+ }
+}
+
+func TestRejoinRestoresBeforeAdmission(t *testing.T) {
+ o := newSeatsFixture(t, 11, 11)
+ if r := o.removeMember(t, "m100@example.com"); r.Status != http.StatusSeeOther {
+ t.Fatalf("remove = %+v", r)
+ }
+ if o.seatQty(t) != 10 || o.billingRow(t).PaidSeats != 11 || o.members(t) != 10 {
+ t.Fatalf("after leaving: seats %d paid %d members %d", o.seatQty(t), o.billingRow(t).PaidSeats, o.members(t))
+ }
+ // The rejoin's invite needs no confirmation: the seat is paid for.
+ r := o.request(t, http.MethodPost, o.teamPath("/invite"), url.Values{"address": {"m100@example.com"}})
+ if r.Status != http.StatusSeeOther || r.Loc != o.teamPath("/team") {
+ t.Fatalf("invite = %+v", r)
+ }
+ inv, _ := o.st.PendingInvites(o.acct.ID)
+ if len(inv) != 1 || o.authorisation(t, inv[0].Token) != nil {
+ t.Fatalf("invites = %+v", inv)
+ }
+ in := o.invitee(t, "m100@example.com")
+ o.reset()
+ o.wantJoined(t, o.accept(in, inv[0].Token))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if op.Kind != opRestore || op.InviteToken != inv[0].Token || op.AuthorisedBy != "" || op.State != opApplied ||
+ changeBodyOf(t, op.Prepared).Proration != billing.ProrateNone || o.seatQty(t) != 11 || o.members(t) != 11 {
+ t.Fatalf("op %+v seats %d members %d", op, o.seatQty(t), o.members(t))
+ }
+}
+
+// ---- leaving, drift and Match seats ------------------------------------------
+
+func TestLeaveReducesAtRenewal(t *testing.T) {
+ o := newSeatsFixture(t, 11, 11)
+ if r := o.removeMember(t, "m100@example.com"); r.Status != http.StatusSeeOther || r.Flash != "ok" {
+ t.Fatalf("remove = %+v", r)
+ }
+ op := o.lastOp(t)
+ if op.Kind != opSeat || op.InviteToken != "" || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNone || o.seatQty(t) != 10 {
+ t.Fatalf("op %+v seats %d", op, o.seatQty(t))
+ }
+ // The period keeps its paid seats; the plan row too.
+ if b, row := o.billingRow(t), o.planRow(t); b.PaidSeats != 11 || row.Seats != 11 {
+ t.Fatalf("paid %d row seats %d, want 11 until renewal", b.PaidSeats, row.Seats)
+ }
+ if err := o.fake.Renew("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if b, row := o.billingRow(t), o.planRow(t); b.PaidSeats != 10 || row.Seats != 10 {
+ t.Fatalf("after renewal: paid %d row seats %d, want 10", b.PaidSeats, row.Seats)
+ }
+ o.fake.Lock()
+ defer o.fake.Unlock()
+ for _, inv := range o.fake.Invoices {
+ if inv.Reason == billingtest.ReasonCycle {
+ for _, l := range inv.Lines {
+ if l.PriceID == communityPrice() && l.Quantity != 10 {
+ t.Fatalf("the renewal billed %d seats, want 10", l.Quantity)
+ }
+ }
+ }
+ }
+}
+
+func TestDriftPassOnlyObserves(t *testing.T) {
+ o := newSeatsFixture(t, 10, 13)
+ before := o.fake.Writes()
+ t0 := time.Now()
+ o.pass(t0)
+ b := o.billingRow(t)
+ if b.SeatDriftAt.Unix() != t0.Unix() || b.SeatDriftMembers != 10 {
+ t.Fatalf("drift = %v %d", b.SeatDriftAt, b.SeatDriftMembers)
+ }
+ o.pass(t0.Add(time.Hour))
+ if b := o.billingRow(t); b.SeatDriftAt.Unix() != t0.Unix() {
+ t.Fatalf("the drift mark moved: %v", b.SeatDriftAt)
+ }
+ if o.fake.Writes() != before || o.seatQty(t) != 13 || o.seatsUnpaidOpen(t) {
+ t.Fatalf("writes %d->%d seats %d problems %v", before, o.fake.Writes(), o.seatQty(t), o.openProblems(t))
+ }
+}
+
+func TestMatchSeatsReduces(t *testing.T) {
+ o := newSeatsFixture(t, 10, 13)
+ o.pass(time.Now())
+ o.reset()
+ r := o.request(t, http.MethodPost, o.billingBase()+"/seats", nil)
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if o.seatQty(t) != 10 || op.Kind != opSeat || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNone {
+ t.Fatalf("seats %d op %+v", o.seatQty(t), op)
+ }
+ if b := o.billingRow(t); !b.SeatDriftAt.IsZero() || b.PaidSeats != 13 {
+ t.Fatalf("billing row = %+v", b)
+ }
+ // Nothing left to match: one read, no flash.
+ o.reset()
+ r = o.request(t, http.MethodPost, o.billingBase()+"/seats", nil)
+ if r.Status != http.StatusSeeOther || r.Flash != "" {
+ t.Fatalf("second match = %+v", r)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ // The doors: no CSRF 403; billing off 404.
+ form := url.Values{"csrf": {"wrong"}}
+ req := httptest.NewRequest(http.MethodPost, o.ts.URL+o.billingBase()+"/seats", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ u, _ := url.Parse(o.ts.URL)
+ for _, ck := range o.owner.Jar.Cookies(u) {
+ req.AddCookie(ck)
+ }
+ rr := httptest.NewRecorder()
+ o.srv.ServeHTTP(rr, req)
+ if rr.Code != http.StatusForbidden {
+ t.Fatalf("no csrf = %d", rr.Code)
+ }
+ rt := o.srv.billing
+ o.srv.billing = nil
+ if r := o.request(t, http.MethodPost, o.billingBase()+"/seats", nil); r.Status != http.StatusNotFound {
+ t.Fatalf("billing off = %d", r.Status)
+ }
+ o.srv.billing = rt
+}
+
+func TestMatchSeatsRefusedByAProblemItsReadOpens(t *testing.T) {
+ o := newSeatsFixture(t, 10, 13)
+ if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemRestoreAfterRenewal, "test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ r := o.request(t, http.MethodPost, o.billingBase()+"/seats", nil)
+ o.wantFlash(t, r, "err", billingCopy[errCheckoutProblem.Key])
+ if c := o.counts(); c["Send"] != 0 || o.seatQty(t) != 13 {
+ t.Fatalf("counts %v seats %d", c, o.seatQty(t))
+ }
+}
+
+// ---- seats_unpaid ----------------------------------------------------------------
+
+func TestPassOpensAndClosesSeatsUnpaid(t *testing.T) {
+ o := newSeatsFixture(t, 11, 11)
+ // An operator adds a member: never charged.
+ addMembers(t, o.consoleFixture, o.acct.ID, 200, 1)
+ before := o.fake.Writes()
+ t0 := time.Now()
+ o.pass(t0)
+ if !o.seatsUnpaidOpen(t) {
+ t.Fatalf("problems = %v, want seats_unpaid", o.openProblems(t))
+ }
+ if err := o.st.RemoveMember(o.acct.ID, "m200@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ o.pass(t0.Add(25 * time.Hour))
+ if o.seatsUnpaidOpen(t) {
+ t.Fatalf("problems = %v, want seats_unpaid closed", o.openProblems(t))
+ }
+ if o.fake.Writes() != before {
+ t.Fatal("the pass wrote to the provider")
+ }
+ page := o.request(t, http.MethodGet, o.billingBase(), nil)
+ if strings.Contains(page.Body, html.EscapeString(billingCopy["notice.seats_unpaid"])) {
+ t.Fatal("the page still shows seats_unpaid")
+ }
+}
+
+func TestSeatsUnpaidRecheckedDaily(t *testing.T) {
+ o := newSeatsFixture(t, 11, 11)
+ addMembers(t, o.consoleFixture, o.acct.ID, 200, 1)
+ t0 := time.Now()
+ o.pass(t0)
+ if !o.seatsUnpaidOpen(t) {
+ t.Fatal("not opened")
+ }
+ if err := o.st.RemoveMember(o.acct.ID, "m200@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ o.pass(t0.Add(time.Hour))
+ if !o.seatsUnpaidOpen(t) {
+ t.Fatal("closed within the day")
+ }
+ o.pass(t0.Add(24 * time.Hour))
+ if o.seatsUnpaidOpen(t) {
+ t.Fatal("not closed after a day")
+ }
+}
+
+func TestSeatsUnpaidCloseDoor(t *testing.T) {
+ o := newSeatsFixture(t, 11, 11)
+ addMembers(t, o.consoleFixture, o.acct.ID, 200, 1)
+ o.pass(time.Now())
+ open, _ := o.st.BillingProblems(false)
+ if len(open) != 1 || open[0].Reason != problemSeatsUnpaid {
+ t.Fatalf("problems = %+v", open)
+ }
+ op := planOperatorToken(t, o.consoleFixture, "ops@keymail.dev", "code-seats-close")
+ note := map[string]any{"note": "checked the members"}
+ if status, out := postJSON(t, billingCloseURL(o.consoleFixture, open[0].ID), note, op); status != http.StatusConflict || out["error"] != billingCopySeatsStillOver {
+ t.Fatalf("over: %d %v", status, out)
+ }
+ if err := o.st.RemoveMember(o.acct.ID, "m200@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if status, out := postJSON(t, billingCloseURL(o.consoleFixture, open[0].ID), note, op); status != http.StatusOK || out["closed_by"] != "ops@keymail.dev" {
+ t.Fatalf("within: %d %v", status, out)
+ }
+ if o.seatsUnpaidOpen(t) {
+ t.Fatal("still open")
+ }
+ // Other reasons keep their gates: subscription_missing still refuses
+ // while the subscription is live.
+ if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemSubscriptionMissing, "test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ open, _ = o.st.BillingProblems(false)
+ if status, out := postJSON(t, billingCloseURL(o.consoleFixture, open[0].ID), note, op); status != http.StatusConflict || out["error"] != billingCopyStillLive {
+ t.Fatalf("subscription_missing while live: %d %v", status, out)
+ }
+}
+
+// ---- timeouts --------------------------------------------------------------------
+
+func TestAcceptAndRemoveReturnUnderTimeout(t *testing.T) {
+ within := func(t *testing.T, what string, f func()) {
+ t.Helper()
+ done := make(chan struct{})
+ go func() { defer close(done); f() }()
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ t.Fatalf("%s did not return", what)
+ }
+ }
+ t.Run("accept", func(t *testing.T) {
+ t.Parallel()
+ o := newSeatsFixture(t, 10, 10)
+ o.srv.billing.wait = nil // the real backoff
+ in := o.invitee(t, "kim@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 100
+ o.fake.Unlock()
+ var r billingReply
+ within(t, "accept", func() { r = o.accept(in, tok) })
+ wantAdmit(t, r, "seats.join_uncertain")
+ })
+ t.Run("remove", func(t *testing.T) {
+ t.Parallel()
+ o := newSeatsFixture(t, 11, 11)
+ o.srv.billing.wait = nil
+ o.stepUp(t)
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 100
+ o.fake.Unlock()
+ var r billingReply
+ within(t, "remove", func() {
+ r = o.request(t, http.MethodPost, o.teamPath("/members/remove"), url.Values{"address": {"m100@example.com"}})
+ })
+ if r.Status != http.StatusSeeOther || o.members(t) != 10 {
+ t.Fatalf("remove = %+v members %d", r, o.members(t))
+ }
+ })
+}
+
+// ---- unit --------------------------------------------------------------------------
+
+func TestSeatCovered(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ book := o.srv.billing.cfg.Book
+ price, _ := book.PlanPrice("community", "usd")
+ row := &billingAccount{Plan: "community", Book: book.Version, Currency: "usd"}
+ good := seatAuthorisation{Plan: "community", Book: book.Version, Currency: "usd", PriceMinor: price}
+ for _, c := range []struct {
+ name string
+ edit func(a *seatAuthorisation)
+ want bool
+ }{
+ {"matching", func(a *seatAuthorisation) {}, true},
+ {"consumed", func(a *seatAuthorisation) { a.ConsumedAt = billingNow }, false},
+ {"other plan", func(a *seatAuthorisation) { a.Plan = "business" }, false},
+ {"other book", func(a *seatAuthorisation) { a.Book = "example-v0" }, false},
+ {"other currency", func(a *seatAuthorisation) { a.Currency = "eur" }, false},
+ {"price above what was agreed", func(a *seatAuthorisation) { a.PriceMinor = price - 1 }, false},
+ {"agreed above the price", func(a *seatAuthorisation) { a.PriceMinor = price + 1 }, true},
+ } {
+ a := good
+ c.edit(&a)
+ if got := seatCovered(&a, row, book); got != c.want {
+ t.Errorf("%s: seatCovered = %v, want %v", c.name, got, c.want)
+ }
+ }
+ if seatCovered(nil, row, book) {
+ t.Error("no authorisation covered a seat")
+ }
+}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 5173fdc07..51fe29544 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -80,7 +80,7 @@ const (
// are closed only once the subscription has ended there.
func problemClosableWhileLive(reason string) bool {
switch reason {
- case problemOperationUnresolved, problemRestoreAfterRenewal, problemRestoreCheckStalled:
+ case problemOperationUnresolved, problemRestoreAfterRenewal, problemRestoreCheckStalled, problemSeatsUnpaid:
return true
}
return false
@@ -542,6 +542,19 @@ func (s *Store) BillingProblem(id int64) (*billingProblem, error) {
return p, err
}
+// CloseBillingProblemsByReason closes every open problem of the account
+// with reason, recording who closed them and their note, and reports how
+// many it closed.
+func (s *Store) CloseBillingProblemsByReason(accountID int64, reason, by, note string, now time.Time) (int, error) {
+ res, err := s.db.Exec(`UPDATE billing_problems SET closed_at = ?, closed_by = ?, note = ?
+ WHERE account_id = ? AND reason = ? AND closed_at = 0`, now.Unix(), by, note, accountID, reason)
+ if err != nil {
+ return 0, err
+ }
+ n, err := res.RowsAffected()
+ return int(n), err
+}
+
// errBillingProblemClosed refuses closing a problem twice.
var errBillingProblemClosed = errors.New("billing problem already closed")
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index a8d78d96f..244b2e9d4 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1319,6 +1319,9 @@ var claimFixtures = map[string]claimFixture{
// subscription.
"route POST /a/{sqid}/billing/change": claimNonApp("finishes the account's outstanding billing operation, then prepares and sends a pack change or plan upgrade as billing operations under the billing hold, writing the operations, restore obligations, billing state, the plan row and billing problems; names no app"),
"route POST /a/{sqid}/billing/renewal": claimNonApp("finishes the account's outstanding billing operation, then prepares and sends a renewal stop or resume as a billing operation under the billing hold, writing the operation, billing state, the plan row and billing problems; names no app"),
+ // Plans 6b Match seats: under the member lock and the billing hold, the
+ // team plan item is reduced to the members billed.
+ "route POST /a/{sqid}/billing/seats": claimNonApp("finishes the account's outstanding billing operation, then prepares and sends a seat reduction to the members billed as a billing operation under the member lock and billing hold, writing the operation, billing state, the seat observation, the plan row and billing problems; names no app"),
// ---- POST: CLI, account and deployment level ----
"route POST /accounts/new": claimNonApp("creates an account and its owner membership"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 4d58321a7..469b10f43 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -773,6 +773,26 @@ var claimNonAppProbes = map[string]claimProbe{
return claimBillingPlanIs(t, cx, "personal")
},
},
+ "route POST /a/{sqid}/billing/seats": {
+ setup: claimSeatsWorld,
+ do: claimFormReply("/a/bab/billing/seats"),
+ status: http.StatusSeeOther, loc: "/a/bab/billing",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ var q int64
+ for _, it := range fake.Subs["sub_claim"].Items {
+ if it.PriceID == testPriceID("example-v1/community/usd") {
+ q = it.Quantity
+ }
+ }
+ fake.Unlock()
+ if q != 10 {
+ return fmt.Sprintf("bab's seats are at %d at the provider, want 10", q)
+ }
+ return claimBillingPlanIs(t, cx, "community")
+ },
+ },
"route POST /api/cli/billing/problems/{id}/close": {
setup: claimBillingProblemWorld,
do: func(t *testing.T, cx *claimCase) claimReply {
@@ -1086,6 +1106,18 @@ func claimChangeWorld(t *testing.T, cx *claimCase) {
fake.Unlock()
}
+// claimSeatsWorld is claimBillingWorld on a Community subscription with 13
+// seats, more than bab's members bill (the minimum of 10): Match seats
+// reduces it to 10.
+func claimSeatsWorld(t *testing.T, cx *claimCase) {
+ t.Helper()
+ claimBillingWorld(t, cx)
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ fake.Subs["sub_claim"] = testTeamSub("sub_claim", "cus_claim", "bab", "community", "active", 13)
+ fake.Unlock()
+}
+
// claimCheckoutWorld switches billing on with a Fake provider and binds bab
// to customer cus_claim, with no subscription: a first purchase.
func claimCheckoutWorld(t *testing.T, cx *claimCase) {
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 7fb9ad5c4..c475fc27d 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -50,9 +50,13 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
// Under the member lock and through the membership transition (plans
// 6b): a team account's limits follow the removal at once.
unlock := s.lockMembers(acct.Sqid)
- err := s.membershipTransition(r.Context(), acct, time.Now(), func(tx *sql.Tx) error {
+ now := time.Now()
+ err := s.membershipTransition(r.Context(), acct, now, func(tx *sql.Tx) error {
return removeMemberTx(tx, acct.ID, target)
})
+ if err == nil {
+ s.removalSeats(r.Context(), acct, now)
+ }
unlock()
if err != nil {
log.Printf("console: remove member: %v", err)
@@ -63,6 +67,32 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+acct.Sqid+"/team", http.StatusSeeOther)
}
+// removalSeats is a removal's billing step (plans 6b, Call 12), under the
+// member lock the removal holds: on a billing team, under the billing hold,
+// the plan item comes down to the members billed with no proration
+// (reconcileSeatsLocked), and seats_unpaid follows. The membership is
+// already gone; a failure here is logged and left to the owner's Match
+// seats, the drift the pass records showing them it is due.
+func (s *Server) removalSeats(ctx context.Context, acct *Account, now time.Time) {
+ team, err := s.billingTeam(acct)
+ if err != nil || team == nil {
+ if err != nil {
+ log.Printf("console: remove member: billing plan: %v", err)
+ }
+ return
+ }
+ ctx = s.billingClock(ctx)
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ members, err := s.store.MemberCount(acct.ID)
+ if err == nil {
+ _, err = s.reconcileSeatsLocked(h, ctx, acct, members, now)
+ }
+ if err != nil {
+ log.Printf("console: remove member: seats for %s: %v", acct.Sqid, err)
+ }
+}
+
// handleTransferOwnership hands the account to another member and steps the
// current owner down to member — one transaction, so there is no instant with
// two owners by accident or none by failure.
diff --git a/internal/console/server.go b/internal/console/server.go
index 99cafb73a..cfb988d31 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -10,7 +10,6 @@ import (
"crypto/ed25519"
"crypto/subtle"
"crypto/x509"
- "database/sql"
"embed"
"encoding/json"
"errors"
@@ -1577,6 +1576,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// resuming renewal (billingchange.go). 404 with billing off.
s.registerRoute("POST /a/{sqid}/billing/change", s.handleBillingChange)
s.registerRoute("POST /a/{sqid}/billing/renewal", s.handleBillingRenewal)
+ // Plans 6b: an owner's Match seats to members (billingseats.go). 404
+ // with billing off.
+ s.registerRoute("POST /a/{sqid}/billing/seats", s.handleBillingSeats)
// The billing page (billingpage.go): member-readable, its forms the
// owner's. 404 with billing off.
s.registerRoute("GET /a/{sqid}/billing", s.handleBilling)
@@ -2713,7 +2715,17 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
back("err", copyText("team.bad_address"))
return
}
- tok, ok := s.createInviteLocked(acct, addr, to, back)
+ // Plans 6b (Call 6): a confirmed invite on a billing team records a seat
+ // authorisation, so it needs a fresh sign-in proof first.
+ conf := s.billing != nil && confirmed(r)
+ if conf && !s.requireFreshAuth(w, r, addr, raw) {
+ return
+ }
+ tok, quote, ok := s.createInviteLocked(r.Context(), acct, addr, to, conf, back)
+ if quote != nil {
+ s.renderInviteConfirm(w, r, addr, raw, acct, *quote)
+ return
+ }
if !ok {
return
}
@@ -2737,14 +2749,19 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
// member cap (the pending invites plus this one) and the row, so two
// invites at once cannot both fit under the cap. Delivery happens after,
// outside the lock. A refusal is answered through back.
-func (s *Server) createInviteLocked(acct *Account, addr, to string, back func(kind, msg string)) (string, bool) {
+//
+// On a billing team (billingTeam) the billing hold is taken too, and an
+// invite that will need a new paid seat (inviteSeatLocked) answers a quote
+// for the confirm page unless confirmed; a confirmed one is created with
+// its seat authorisation, under both locks.
+func (s *Server) createInviteLocked(ctx context.Context, acct *Account, addr, to string, confirmed bool, back func(kind, msg string)) (string, *seatQuote, bool) {
defer s.lockMembers(acct.Sqid)()
if role, err := s.store.Role(acct.ID, to); err != nil {
back("err", "Could not check that address. Please try again.")
- return "", false
+ return "", nil, false
} else if role != "" {
back("err", to+" is already a member of this account.")
- return "", false
+ return "", nil, false
}
// Volume limits (each invite is a send as the platform): first the
// account's waiting invites, then its last hour. Both refuse before a row
@@ -2753,34 +2770,66 @@ func (s *Server) createInviteLocked(acct *Account, addr, to string, back func(ki
if err != nil {
log.Printf("console: count pending invites: %v", err)
back("err", "Could not create the invitation. Please try again.")
- return "", false
+ return "", nil, false
}
if n >= maxPendingInvites {
back("err", inviteFlashTooManyPending())
- return "", false
+ return "", nil, false
}
if err := s.checkMemberCap(acct, n+1); err != nil {
var planCap *planCapError
if errors.As(err, &planCap) {
back("err", planCap.Browser())
- return "", false
+ return "", nil, false
}
log.Printf("console: invite: member cap: %v", err)
back("err", "Could not create the invitation. Please try again.")
- return "", false
+ return "", nil, false
+ }
+ team, err := s.billingTeam(acct)
+ if err != nil {
+ log.Printf("console: invite: plan: %v", err)
+ back("err", "Could not create the invitation. Please try again.")
+ return "", nil, false
+ }
+ var auth *seatAuthorisation
+ if team != nil {
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ q, a, err := s.inviteSeatLocked(h, s.billingClock(ctx), acct, n, to, addr, confirmed, time.Now())
+ if err != nil {
+ back("err", changeText(acct.Sqid, err))
+ return "", nil, false
+ }
+ if q != nil {
+ return "", q, false
+ }
+ auth = a
}
if !s.inviteRate.take(acct.ID) {
back("err", inviteFlashTooManyPerHour())
- return "", false
+ return "", nil, false
}
tok, err := s.store.CreateInvite(acct.ID, to, addr, time.Now())
if err != nil {
s.inviteRate.giveBack(acct.ID)
log.Printf("console: create invite: %v", err)
back("err", "Could not create the invitation. Please try again.")
- return "", false
+ return "", nil, false
}
- return tok, true
+ if auth != nil {
+ if err := s.store.SetInviteSeatAuthorisation(tok, *auth); err != nil {
+ // No invite without the authorisation the owner agreed to.
+ if rerr := s.store.RevokeInvite(tok); rerr != nil {
+ log.Printf("console: invite: withdrawing %s after a failed seat authorisation: %v", to, rerr)
+ }
+ s.inviteRate.giveBack(acct.ID)
+ log.Printf("console: invite: seat authorisation: %v", err)
+ back("err", "Could not create the invitation. Please try again.")
+ return "", nil, false
+ }
+ }
+ return tok, nil, true
}
// inviteMessage is the subject and body for an invitation, whichever channel
@@ -2877,6 +2926,23 @@ func (s *Server) handleRevokeInvite(w http.ResponseWriter, r *http.Request) {
// same invite are one after the other: the accept re-checks the invite
// inside the lock.
defer s.lockMembers(acct.Sqid)()
+ // With billing configured, under the billing hold too (Invariant 7): an
+ // invite whose seat operation is outstanding (sending, unresolved or
+ // pending) is not revoked until that settles.
+ if s.billing != nil {
+ _, release := s.holdBilling(acct.Sqid)
+ defer release()
+ op, err := s.store.LatestOpForInvite(tok)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitations.")
+ return
+ }
+ if op != nil && opOutstanding(op.State) {
+ s.setFlash(w, "err", billingCopy["seats.revoke_wait"])
+ http.Redirect(w, r, "/a/"+url.PathEscape(acct.Sqid)+"/team", http.StatusSeeOther)
+ return
+ }
+ }
// Scoped to THIS account: an owner of one account must not be able to
// revoke another account's invite by pasting its token.
pending, err := s.store.PendingInvites(acct.ID)
@@ -2995,46 +3061,41 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+url.PathEscape(a.Sqid)+"/", http.StatusSeeOther)
}
-// acceptInviteLocked joins addr to a under the account's member lock
-// (plans 6b): inside it the invite is checked again (a revoke may have
-// landed while this waited), and a person not yet a member must fit under
-// the plan's member cap. The join goes through the membership transition,
+// acceptInviteLocked joins addr to a through admitMember, under the
+// account's member lock (plans 6b): inside it the invite is checked again (a
+// revoke may have landed while this waited), a person not yet a member must
+// fit under the plan's member cap, and a billing team's seat is admitted
+// under the billing hold. The join goes through the membership transition,
// so a team account's limits follow at once. A refusal leaves the invite
// pending and is answered here.
func (s *Server) acceptInviteLocked(w http.ResponseWriter, r *http.Request, a *Account, token, addr string, now time.Time) bool {
- defer s.lockMembers(a.Sqid)()
- inv, err := s.store.PendingInviteFor(token, addr, now)
- if err != nil || inv.AccountID != a.ID {
+ out, err := s.admitMember(r.Context(), a, token, addr, now)
+ var refusal billingRefusal
+ switch {
+ case out == admitJoined:
+ if err != nil {
+ log.Printf("console: accept invite: after joining: %v", err)
+ }
+ return true
+ case out != admitRefused:
+ if err != nil {
+ log.Printf("console: accept invite %s: %v", a.Sqid, err)
+ }
+ s.renderMessage(w, r, http.StatusConflict, billingCopy["seats.join_wait_title"], admitText(out))
+ case err == nil:
s.invitationGone(w, r)
- return false
- }
- role, err := s.store.Role(a.ID, addr)
- if err != nil {
- log.Printf("console: accept invite: role: %v", err)
+ case isPlanCap(err):
+ s.renderMessage(w, r, http.StatusConflict, "Refused", capMessage("browser.cap.members_join"))
+ case errors.As(err, &refusal):
+ s.renderMessage(w, r, http.StatusConflict, billingCopy["seats.join_wait_title"], billingCopy[refusal.Key])
+ case errors.Is(err, errAdmitRead):
+ log.Printf("console: accept invite: %v", err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitation. Try again.")
- return false
- }
- if role == "" {
- if err := s.checkMemberCap(a, 1); err != nil {
- if isPlanCap(err) {
- s.renderMessage(w, r, http.StatusConflict, "Refused", capMessage("browser.cap.members_join"))
- return false
- }
- log.Printf("console: accept invite: member cap: %v", err)
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitation. Try again.")
- return false
- }
- }
- err = s.membershipTransition(r.Context(), a, now, func(tx *sql.Tx) error {
- _, err := acceptInviteTx(tx, token, addr, now)
- return err
- })
- if err != nil {
+ default:
log.Printf("console: accept invite: %v", err)
s.invitationGone(w, r)
- return false
}
- return true
+ return false
}
// handleContinue is the front page's one form (spec 4): it finds the door
diff --git a/internal/console/store.go b/internal/console/store.go
index e8693c6f9..ddecce570 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -566,6 +566,17 @@ func (s *Store) migrate() error {
// that predates the column was made through Keymail, so the default
// is the backfill.
`ALTER TABLE sessions ADD COLUMN method TEXT NOT NULL DEFAULT 'keymail';`,
+ // A team invite's seat authorisation (plans 6b, Call 11): what the
+ // owner agreed a new paid seat would cost when they invited, and when
+ // the charge it authorised applied (single use, Invariant 2). An
+ // empty seat_plan is no authorisation.
+ `ALTER TABLE invites ADD COLUMN seat_plan TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE invites ADD COLUMN seat_book TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE invites ADD COLUMN seat_currency TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE invites ADD COLUMN seat_price_minor INTEGER NOT NULL DEFAULT 0;`,
+ `ALTER TABLE invites ADD COLUMN seat_authorised_by TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE invites ADD COLUMN seat_authorised_at INTEGER NOT NULL DEFAULT 0;`,
+ `ALTER TABLE invites ADD COLUMN seat_consumed_at INTEGER NOT NULL DEFAULT 0;`,
} {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 78d64fb50..8adce85ce 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -158,6 +158,7 @@ route POST /a/{sqid}/billing/change
route POST /a/{sqid}/billing/checkout
route POST /a/{sqid}/billing/confirm
route POST /a/{sqid}/billing/renewal
+route POST /a/{sqid}/billing/seats
route POST /a/{sqid}/delete
route POST /a/{sqid}/errors/level
route POST /a/{sqid}/fleets/{fleet}/detach