console: linked accounts skip billing and send notices to the platform
Platform accounts spec §8 (plan Task 13). A linked (customer) account's plan is its platform's: - it does not count towards anyone's free-account cap; - holdBilling refuses it with errBillingPlatform and takes no lock, so no door, pass, webhook or seat charge can give it a payment customer; billingOwner answers its billing doors with "Your plan is managed by <platform>." and the billing page redirect; - admitDomainBuy refuses it first with a 409 naming the platform; - its cap, grace and lapse notices go to the platform's owners only (planNoticeRecipients), with platformPlanNoticeEmail's copy, and a delivered notice counts for afterGraceDue as an owner's does. carlos accounts plan prints a platform-set plan's source with its reason. New copy rows are pending copy review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+480
−18
accounts_plan.go+2 −0accounts_plan_copy.go+2 −0accounts_plan_test.go+20 −0internal/console/billinghold.go+33 −3internal/console/billingpage_copy.go+5 −0internal/console/domainbuy.go+25 −0internal/console/domainbuy_copy.go+2 −0internal/console/plancaps.go+11 −2internal/console/plancaps_copy.go+7 −0internal/console/planexempt.go+5 −0internal/console/plangracepass.go+15 −11internal/console/platformlinked.go+57 −2internal/console/platformlinked_test.go+296 −0
diff --git a/accounts_plan.go b/accounts_plan.go| index 577de6317..3d0f8a5f7 100644 |
| --- a/accounts_plan.go |
| +++ b/accounts_plan.go |
| @@ -192,6 +192,8 @@ func printAccountPlan(w io.Writer, r accountPlanReply) { |
| fmt.Fprintf(w, cliPlanCopySourceSponsored+"\n", r.UpdatedBy, r.Reason) |
| case "billing": |
| fmt.Fprintln(w, cliPlanCopySourceBilling) |
| + case "platform": |
| + fmt.Fprintf(w, cliPlanCopySourcePlatform+"\n", r.Reason) |
| default: |
| fmt.Fprintln(w, cliPlanCopySourceDefault) |
| } |
diff --git a/accounts_plan_copy.go b/accounts_plan_copy.go| index 9873643cf..a39e66a84 100644 |
| --- a/accounts_plan_copy.go |
| +++ b/accounts_plan_copy.go |
| @@ -19,6 +19,8 @@ const ( |
| cliPlanCopySourceOperator = "set by %s: %s" |
| cliPlanCopySourceSponsored = "sponsored by %s: %s" |
| cliPlanCopySourceBilling = "set by its subscription" |
| + // Platform accounts slice 1 (plan "Copy table", pending copy review). |
| + cliPlanCopySourcePlatform = "set by its platform account: %s" |
| cliPlanCopyUnpublished = "the boxes do not have this change yet. it is retried every minute" |
| cliPlanCopyLimitsHeading = "limits" |
| cliPlanCopyLimitRunning = "apps and instances" |
diff --git a/accounts_plan_test.go b/accounts_plan_test.go| index 5463acbb3..ee1959406 100644 |
| --- a/accounts_plan_test.go |
| +++ b/accounts_plan_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "flag" |
| + "fmt" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| @@ -96,6 +97,25 @@ func TestAccountsPlanShowAndSet(t *testing.T) { |
| } |
| } |
| +// TestAccountsPlanPrintsThePlatformSource: a customer account's plan row |
| +// (source platform) names its platform account through the row's reason. |
| +func TestAccountsPlanPrintsThePlatformSource(t *testing.T) { |
| + reply := accountPlanReply{ |
| + Account: "bdf", Plan: "free", Source: "platform", Reason: "platform bcd", UpdatedBy: "service:bcd/cms", |
| + Revision: 1, PublishedRevision: 1, Limits: &plans.Limits{RunningThings: 3}, |
| + } |
| + ts, _, _ := planServer(t, reply) |
| + var out bytes.Buffer |
| + if err := runAccountsPlanWithSession(context.Background(), newTestSession(ts.URL), []string{"--account", "bdf"}, &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + lines := strings.Split(out.String(), "\n") |
| + want := fmt.Sprintf(cliPlanCopySourcePlatform, "platform bcd") |
| + if len(lines) < 2 || lines[1] != want { |
| + t.Fatalf("source line %q, want %q:\n%s", lines[min(1, len(lines)-1)], want, out.String()) |
| + } |
| +} |
| + |
| func TestAccountsPlanValidationStopsBeforeNetwork(t *testing.T) { |
| hits := 0 |
| ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hits++ })) |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| index 2fa3eed99..34fbd1dc2 100644 |
| --- a/internal/console/billinghold.go |
| +++ b/internal/console/billinghold.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "fmt" |
| + "log" |
| "net/http" |
| "time" |
| @@ -72,7 +73,9 @@ func (r billingRefusal) Error() string { return "billing: refused: " + r.Key } |
| // place the exempt ops account (planExempt) is refused billing: for it the |
| // answer is errBillingExempt, no lock and a release that does nothing, so |
| // no billing work (a door, a pass, a webhook sync, an invite's seat) can |
| -// act on it. Every function that acts on billing state takes the hold |
| +// act on it. A linked account (platform accounts spec §8) is refused the |
| +// same way with errBillingPlatform, so none of them can give it a payment |
| +// customer. Every function that acts on billing state takes the hold |
| // (TestBillingLockedHelpersNeverLock, TestBillingHoldMintedOnlyByHoldBilling). |
| // |
| // h, release, err := s.holdBilling(acct) |
| @@ -82,6 +85,14 @@ func (s *Server) holdBilling(acct *Account) (billingHold, func(), error) { |
| if s.store.planExempt(acct.ID) { |
| return billingHold{}, func() {}, errBillingExempt |
| } |
| + // No context reaches here: holdBilling's callers pass the account alone. |
| + platform, _, err := s.store.AccountPlatform(context.Background(), acct.ID) |
| + if err != nil { |
| + return billingHold{}, func() {}, err |
| + } |
| + if platform != "" { |
| + return billingHold{}, func() {}, errBillingPlatform |
| + } |
| // The lock-order events (lockEvent, lifetimes.go): the hold is last in |
| // the order platform lifecycle, account/plan, billing (applocks.go). |
| lockEvent("billing", acct.Sqid, lockWaiting) |
| @@ -97,8 +108,10 @@ func (s *Server) holdBilling(acct *Account) (billingHold, func(), error) { |
| // billingOwner is every billing door's entry (the routes under |
| // /a/{sqid}/billing/, TestBillingDoorsEnterThroughBillingOwner): billing |
| // off answers 404, then the owner gate, then the exempt ops account |
| -// (planExempt) goes back to its billing page with notice.exempt, before |
| -// any billing state is read or any form is looked at. |
| +// (planExempt) goes back to its billing page with notice.exempt, and a |
| +// linked account to its billing page with notice.platform naming the |
| +// platform that runs it (platform accounts spec §8), before any billing |
| +// state is read or any form is looked at. |
| func (s *Server) billingOwner(w http.ResponseWriter, r *http.Request) (addr, raw string, acct *Account, ok bool) { |
| if s.billing == nil { |
| http.NotFound(w, r) |
| @@ -113,6 +126,23 @@ func (s *Server) billingOwner(w http.ResponseWriter, r *http.Request) (addr, raw |
| http.Redirect(w, r, billingPagePath(acct.Sqid), http.StatusSeeOther) |
| return "", "", nil, false |
| } |
| + platform, err := s.linkedPlatform(r.Context(), acct) |
| + if err != nil { |
| + log.Printf("console: billing %s: platform link: %v", acct.Sqid, err) |
| + s.setFlash(w, "err", billingCopy["change.failed"]) |
| + http.Redirect(w, r, billingPagePath(acct.Sqid), http.StatusSeeOther) |
| + return "", "", nil, false |
| + } |
| + if platform != nil { |
| + // A link to a platform with no live row here has no name to show. |
| + notice := billingCopy[errBillingPlatform.Key] |
| + if platform.Name != "" { |
| + notice = fmt.Sprintf(billingCopy["notice.platform"], platform.Name) |
| + } |
| + s.setFlash(w, "err", notice) |
| + http.Redirect(w, r, billingPagePath(acct.Sqid), http.StatusSeeOther) |
| + return "", "", nil, false |
| + } |
| return addr, raw, acct, true |
| } |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index 72857b984..6faebab61 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -170,4 +170,9 @@ var billingCopy = map[string]string{ |
| "usage.label.email": "Email", |
| "usage.label.pdf": "PDFs", |
| "usage.label.bandwidth": "Bandwidth", |
| + |
| + // Platform accounts slice 1 (plan "Copy table", pending copy review): a |
| + // linked account's plan is its platform's, so it has nothing to buy. |
| + "notice.platform": "Your plan is managed by %s.", |
| + "notice.platform_generic": "This account’s plan is managed by the platform account that runs it.", |
| } |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 61e142e27..e25717cd3 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -36,7 +36,13 @@ func domainBuyUnavailable() *doorRefusal { |
| // Other holders may only produce the neutral refusal: |
| // name-only refusals and the shared budget come first, then registrar availability, |
| // then the claim/live checks, and finally premium and price checks. |
| +// Before all of them, a linked account is refused (platform accounts spec |
| +// §8): buying creates a payment customer, and a linked account never gets |
| +// one. Every caller has already answered 404 when buying is off. |
| func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string, country ...string) (domainreg.Quote, *doorRefusal) { |
| + if ref := s.linkedDomainBuyRefusal(ctx, acct); ref != nil { |
| + return domainreg.Quote{}, ref |
| + } |
| if !s.domainBuyReady() { |
| return domainreg.Quote{}, &doorRefusal{Status: http.StatusNotFound} |
| } |
| @@ -237,6 +243,25 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return purchase, link, nil, ref |
| } |
| +// linkedDomainBuyRefusal is the 409 for a linked account, naming the |
| +// platform that runs it (its sqid when this console has no live row for |
| +// it), or nil for an account that is not linked. |
| +func (s *Server) linkedDomainBuyRefusal(ctx context.Context, acct *Account) *doorRefusal { |
| + platform, err := s.linkedPlatform(ctx, acct) |
| + if err != nil { |
| + log.Printf("console: domain purchase: account=%s platform link: %v", acct.Sqid, err) |
| + return domainBuyUnavailable() |
| + } |
| + if platform == nil { |
| + return nil |
| + } |
| + name := platform.Name |
| + if name == "" { |
| + name = platform.Sqid |
| + } |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(domainBuyCopy["platform"], name)} |
| +} |
| + |
| func (s *Server) ownLiveDomainPurchase(ctx context.Context, account int64, name string) (*DomainPurchase, error) { |
| p, err := scanDomainPurchase(s.store.db.QueryRowContext(ctx, `SELECT `+domainPurchaseColumns+` FROM domain_purchases WHERE account_id=? AND domain=? AND `+liveDomainPurchaseSQL, account, name)) |
| if errors.Is(err, sql.ErrNoRows) { |
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go| index a7e8e3de6..8ab5ae28a 100644 |
| --- a/internal/console/domainbuy_copy.go |
| +++ b/internal/console/domainbuy_copy.go |
| @@ -21,6 +21,8 @@ var domainBuyCopy = map[string]string{ |
| // Approved by delegation (Luna), 2026-11-03: domain registration Plan 2, slice 1. |
| "billingSetup": "we could not set up billing for your account. try again later", |
| "currency": "we could not find a price for this domain in your account currency", |
| + // Platform accounts slice 1 (plan "Copy table", pending copy review). |
| + "platform": "buying a domain isn’t available on an account run by %s. attach a domain registered elsewhere instead", |
| "title": "Buy a domain", |
| "name": "Domain", |
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go| index 351bb39ce..7bcd385ae 100644 |
| --- a/internal/console/plancaps.go |
| +++ b/internal/console/plancaps.go |
| @@ -170,8 +170,9 @@ func (s *Server) checkSidecars(ctx context.Context, acct *Account, app string) e |
| // Owning the exempt account (planExempt) is not owning a free one, and its |
| // owners have no allowance at all (opsOwner): the platform owner makes |
| // accounts for the platform's own sites. Those accounts still start on the |
| -// default plan. Both doors that create an account (the CLI's and the |
| -// browser's) come here. |
| +// default plan. Owning a linked account is not owning a free one either: |
| +// its plan is its platform's (platform accounts spec §8). Both doors that |
| +// create an account (the CLI's and the browser's) come here. |
| func (s *Server) checkNewFreeAccount(addr string) error { |
| cat := s.cfg.PlanCatalog |
| if cat == nil || cat.FreeAccountsPerPerson <= 0 || s.opsOwner(addr) { |
| @@ -189,6 +190,14 @@ func (s *Server) checkNewFreeAccount(addr string) error { |
| if a.Role != RoleOwner || s.store.planExempt(a.ID) { |
| continue |
| } |
| + // No context reaches here (both create doors call with addr alone). |
| + platform, _, err := s.store.AccountPlatform(context.Background(), a.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if platform != "" { |
| + continue |
| + } |
| plan := cat.DefaultPlan |
| row, err := s.store.AccountPlan(a.ID) |
| if err != nil { |
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go| index a87ea8ac9..046463a59 100644 |
| --- a/internal/console/plancaps_copy.go |
| +++ b/internal/console/plancaps_copy.go |
| @@ -86,6 +86,13 @@ var planNoticeCopy = map[string]string{ |
| "cli.lapse_off": "turned off because this account's plan no longer covers them: %s. settings and data are kept. covered things come back within a few minutes. only owners can choose what stays", |
| "email.lapse_off": "- Turned off: %s. Settings and data are kept. Covered things come back within a few minutes.", |
| "email.lapse_off_list": "Turned off: %s.\n\nChoose what stays for apps, instances and workers:\n%s", |
| + // Platform accounts slice 1 (plan "Copy table", pending copy review): |
| + // a customer account's notices go to its platform's owners, who manage |
| + // it with carlos platform, not in the customer's settings. |
| + "email.platform.subject": "[carlos] Customer account %s (%s): plan usage", |
| + "email.platform.intro": "Customer account %s (%s), run by %s, is near or over its plan limits:", |
| + "email.platform.lapse_off_list": "Turned off: %s.", |
| + "email.platform.ways_out": "To stay within the plan, move the account to a bigger plan or clean it up.\n\nSee its usage:\n carlos platform customers show --platform %s --customer %s\n\nChange its plan:\n carlos platform customers update --platform %s --customer %s --plan <plan>", |
| } |
| // planKeepCopy holds the keep page's words (plans 4d): where an owner of a |
diff --git a/internal/console/planexempt.go b/internal/console/planexempt.go| index 42c2db509..7599eee18 100644 |
| --- a/internal/console/planexempt.go |
| +++ b/internal/console/planexempt.go |
| @@ -40,6 +40,11 @@ var errPlanExempt = errors.New("console: " + planCopyExempt) |
| // errBillingExempt refuses a billing door for the exempt account. |
| var errBillingExempt = billingRefusal{Key: "notice.exempt"} |
| +// errBillingPlatform refuses billing for a linked account (platform |
| +// accounts spec §8): its plan is its platform's, and it never gets a |
| +// payment customer (holdBilling). |
| +var errBillingPlatform = billingRefusal{Key: "notice.platform_generic"} |
| + |
| // settlePlanExempt is the one place that clears what a plan left on the |
| // exempt account before it was exempt. It runs once per console start, |
| // from the first limits pass, and is done only when both steps succeeded; |
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go| index 0b272cda9..7f3a4a7ba 100644 |
| --- a/internal/console/plangracepass.go |
| +++ b/internal/console/plangracepass.go |
| @@ -218,7 +218,9 @@ func noticeDue(st capState, now time.Time, stage string, lastOff time.Time) bool |
| // notifyPlanOwners sends one email per owner listing every cap that is |
| // due. Marks are set, and notice recorded, only when at least one owner's |
| -// delivery was accepted; otherwise the next pass tries again. |
| +// delivery was accepted; otherwise the next pass tries again. A linked |
| +// account's owners are its platform's (planNoticeRecipients), so their |
| +// notice counts for afterGraceDue as an owner's does. |
| func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []capState, now time.Time) error { |
| stage := s.planStage(ctx, acct, now) |
| lastOff := s.lapseLastOff(acct) |
| @@ -235,22 +237,24 @@ func (s *Server) notifyPlanOwners(ctx context.Context, acct *Account, states []c |
| if len(due) == 0 || (s.consoleMail == nil && s.sendFederated == nil) { |
| return nil |
| } |
| - members, err := s.store.Members(acct.ID) |
| - if err != nil { |
| + owners, platform, err := s.planNoticeRecipients(ctx, acct) |
| + if err != nil || len(owners) == 0 { |
| return err |
| } |
| - subject, body := s.planNoticeEmail(acct, due, stage) |
| + var subject, body string |
| + if platform != nil { |
| + subject, body = s.platformPlanNoticeEmail(acct, platform, due, stage) |
| + } else { |
| + subject, body = s.planNoticeEmail(acct, due, stage) |
| + } |
| delivered := false |
| - for _, m := range members { |
| - if m.Role != RoleOwner { |
| - continue |
| - } |
| + for _, to := range owners { |
| dctx, cancel := context.WithTimeout(ctx, planNoticeDeliveryTimeout) |
| - _, err := s.deliver(dctx, m.Name, subject, body, planNoticeDeliveryTimeout*4/5) |
| + _, err := s.deliver(dctx, to, subject, body, planNoticeDeliveryTimeout*4/5) |
| cancel() |
| if err != nil { |
| - log.Printf("console: plan grace %s: notice to %s: %v", acct.Sqid, m.Name, err) |
| - jobFailed(ctx, fmt.Errorf("plan grace %s: notice to %s: %w", acct.Sqid, m.Name, err)) |
| + log.Printf("console: plan grace %s: notice to %s: %v", acct.Sqid, to, err) |
| + jobFailed(ctx, fmt.Errorf("plan grace %s: notice to %s: %w", acct.Sqid, to, err)) |
| continue |
| } |
| delivered = true |
diff --git a/internal/console/platformlinked.go b/internal/console/platformlinked.go| index 24283d27c..53ccd0599 100644 |
| --- a/internal/console/platformlinked.go |
| +++ b/internal/console/platformlinked.go |
| @@ -4,9 +4,17 @@ package console |
| // the platform account it is linked to, and the console treats it |
| // differently where that matters. Until slice 2's leave, a linked account's |
| // end is its platform's door, never a person's Delete account (decision |
| -// D11). |
| +// D11). Its plan is its platform's: it never gets a payment customer |
| +// (holdBilling, admitDomainBuy), it is no one's free account |
| +// (checkNewFreeAccount), and its plan notices go to the platform's owners |
| +// (planNoticeRecipients). |
| -import "context" |
| +import ( |
| + "context" |
| + "fmt" |
| + "strings" |
| + "time" |
| +) |
| // linkedPlatform is the platform account that runs acct, or nil when acct |
| // is not linked. A link naming a platform this console has no live row for |
| @@ -26,3 +34,50 @@ func (s *Server) linkedPlatform(ctx context.Context, acct *Account) (*Account, e |
| } |
| return platform, nil |
| } |
| + |
| +// planNoticeRecipients is who hears acct's cap, grace and lapse notices: |
| +// its owners, or for a linked account its platform's owners alone, whether |
| +// or not the customer has been claimed (spec §8: the platform controls the |
| +// plan, so only it can act). platform is the linked platform, nil when acct |
| +// is not linked; a platform with no live row here has no owners. |
| +func (s *Server) planNoticeRecipients(ctx context.Context, acct *Account) (owners []string, platform *Account, err error) { |
| + platform, err = s.linkedPlatform(ctx, acct) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + of := acct |
| + if platform != nil { |
| + if platform.ID == 0 { |
| + return nil, platform, nil |
| + } |
| + of = platform |
| + } |
| + members, err := s.store.Members(of.ID) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + for _, m := range members { |
| + if m.Role == RoleOwner { |
| + owners = append(owners, m.Name) |
| + } |
| + } |
| + return owners, platform, nil |
| +} |
| + |
| +// platformPlanNoticeEmail is planNoticeEmail for a customer account's |
| +// notice to its platform's owners: the same per-cap lines, and ways out |
| +// through carlos platform instead of links into the customer account, |
| +// which the platform's staff cannot open. |
| +func (s *Server) platformPlanNoticeEmail(cust, platform *Account, due []capState, stage func(capState) string) (subject, body string) { |
| + lines := []string{fmt.Sprintf(planNoticeCopy["email.platform.intro"], cust.Name, cust.Sqid, platform.Name), ""} |
| + lapsed := false |
| + for _, n := range planNoticesOf(due, time.Now(), stage) { |
| + lines = append(lines, planNoticeText(n, "email")) |
| + lapsed = lapsed || n.Stage == "lapse_off" |
| + } |
| + if names := s.lapseOffNames(cust); lapsed && len(names) > 0 { |
| + lines = append(lines, "", fmt.Sprintf(planNoticeCopy["email.platform.lapse_off_list"], strings.Join(names, ", "))) |
| + } |
| + lines = append(lines, "", fmt.Sprintf(planNoticeCopy["email.platform.ways_out"], platform.Sqid, cust.Sqid, platform.Sqid, cust.Sqid)) |
| + return fmt.Sprintf(planNoticeCopy["email.platform.subject"], cust.Name, cust.Sqid), strings.Join(lines, "\n") + "\n" |
| +} |
diff --git a/internal/console/platformlinked_test.go b/internal/console/platformlinked_test.go| index 161d8c6e9..1f5a5a6f7 100644 |
| --- a/internal/console/platformlinked_test.go |
| +++ b/internal/console/platformlinked_test.go |
| @@ -9,6 +9,7 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "net/http" |
| "net/http/httptest" |
| @@ -644,3 +645,298 @@ func TestLockOrderLifecycleAccountBilling(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// ---- plans, billing and notices (spec §8, Task 13) --------------------------- |
| + |
| +// linkedShop is a platform account named studio (id 520, so the customer |
| +// the bucket mints next is clear of testAccountID's ids), its manifest in |
| +// the bucket and granted up to 5 customers on plans, and its customer shop, |
| +// made through the platform's create door. |
| +func linkedShop(t *testing.T, fx *consoleFixture, plans ...string) (studio, shop *Account) { |
| + t.Helper() |
| + ctx := context.Background() |
| + p := planAccount(t, fx, 520) |
| + if err := fx.st.RenameAccount(ctx, p.ID, "studio"); err != nil { |
| + t.Fatal(err) |
| + } |
| + studio, err := fx.st.AccountByID(p.ID) |
| + if err != nil || studio == nil { |
| + t.Fatal(studio, err) |
| + } |
| + if err := WriteAccountManifest(ctx, fx.rel, studio.ID, studio.Sqid, studio.Name, studio.CreatedAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + grantPlatformAccount(t, fx, studio.Sqid, 5, plans...) |
| + tok := platformToken(t, fx, studio.ID, "cms") |
| + status, out, raw := createCustomer(t, fx.ts.URL, studio.Sqid, tok, map[string]any{"name": "shop"}) |
| + if status != http.StatusCreated { |
| + t.Fatalf("create = %d %s", status, raw) |
| + } |
| + shop, err = fx.st.AccountBySqid(customerIn(t, out)["account"].(string)) |
| + if err != nil || shop == nil { |
| + t.Fatal(shop, err) |
| + } |
| + return studio, shop |
| +} |
| + |
| +func TestLinkedAccountsDoNotCountTowardsTheFreeCap(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + cat := examplePlanCatalog(t) |
| + cat.FreeAccountsPerPerson = 2 |
| + fx.srv.cfg.PlanCatalog = cat |
| + _, shop := linkedShop(t, fx, "free") |
| + if row, err := fx.st.AccountPlan(shop.ID); err != nil || row == nil || row.Plan != "free" || row.Source != PlanSourcePlatform { |
| + t.Fatalf("customer plan row = %+v %v, want free from its platform", row, err) |
| + } |
| + kim := "kim@example.com" |
| + mine := testAccountID() |
| + if err := fx.st.CreateAccount(mine, domains.Sqid(mine), "mine", kim, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(shop.ID, kim, RoleOwner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.checkNewFreeAccount(kim); err != nil { |
| + t.Fatalf("one free account and an owned linked one: %v, want a new one allowed", err) |
| + } |
| + // The cap still counts kim's own accounts. |
| + more := testAccountID() |
| + if err := fx.st.CreateAccount(more, domains.Sqid(more), "more", kim, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.srv.checkNewFreeAccount(kim); !isCap(err) { |
| + t.Fatalf("two free accounts and an owned linked one: %v, want the cap", err) |
| + } |
| +} |
| + |
| +func TestBillingHoldRefusesLinkedAccounts(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + studio, shop := linkedShop(t, bf.consoleFixture, "free") |
| + events := recordLocks(t, shop.Sqid) |
| + _, release, err := bf.srv.holdBilling(shop) |
| + release() |
| + if !errors.Is(err, errBillingPlatform) { |
| + t.Fatalf("holdBilling(customer) = %v, want errBillingPlatform", err) |
| + } |
| + select { |
| + case ev := <-events: |
| + t.Fatalf("the refused hold took a lock: %v", ev) |
| + default: |
| + } |
| + if b, err := bf.st.BillingAccount(shop.ID); err != nil || b != nil { |
| + t.Fatalf("customer billing row = %+v %v, want none", b, err) |
| + } |
| + // The platform account itself is billed as any account is. |
| + h, release, err := bf.srv.holdBilling(studio) |
| + defer release() |
| + if err != nil || h.sqid != studio.Sqid { |
| + t.Fatalf("holdBilling(platform) = %+v, %v", h, err) |
| + } |
| +} |
| + |
| +func TestBillingDoorsShowThePlatformNotice(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.srv.billing.ready.Store(true) |
| + _, shop := linkedShop(t, bf.consoleFixture, "free") |
| + if err := bf.st.AddMember(shop.ID, "claimer@example.com", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, csrf := freshOwner(t, bf.consoleFixture, "claimer@example.com", "code-billing-linked") |
| + want := fmt.Sprintf(billingCopy["notice.platform"], "studio") |
| + routes := billingDoorRoutes(t) |
| + if len(routes) < 8 { |
| + t.Fatalf("found %d billing doors, want at least 8: %v", len(routes), routes) |
| + } |
| + for pattern := range routes { |
| + method, path, _ := strings.Cut(pattern, " ") |
| + u := bf.ts.URL + strings.Replace(path, "{sqid}", shop.Sqid, 1) |
| + var status int |
| + var loc string |
| + if method == http.MethodPost { |
| + status, loc, _ = postForm(t, c, u, url.Values{"csrf": {csrf}, "plan": {"personal"}}) |
| + } else { |
| + status, loc, _ = get(t, c, u) |
| + } |
| + if status != http.StatusSeeOther || loc != billingPagePath(shop.Sqid) { |
| + t.Errorf("%s = %d -> %q, want the billing page", pattern, status, loc) |
| + continue |
| + } |
| + if kind, msg := inviteFlashAfter(t, c, bf.ts.URL); kind != "err" || msg != want { |
| + t.Errorf("%s flash %s:%q, want %q", pattern, kind, msg, want) |
| + } |
| + } |
| + if n := providerCalls(bf); n != 0 { |
| + t.Fatalf("the billing doors made %d provider requests for a customer account", n) |
| + } |
| + if b, err := bf.st.BillingAccount(shop.ID); err != nil || b != nil { |
| + t.Fatalf("customer billing row = %+v %v, want none", b, err) |
| + } |
| +} |
| + |
| +func TestDomainBuyRefusedOnLinkedAccounts(t *testing.T) { |
| + o := buyWorld(t) |
| + // On a paid plan with custom domains, so only the link refuses. |
| + _, shop := linkedShop(t, o.consoleFixture, "personal") |
| + ctx := context.Background() |
| + want := fmt.Sprintf(domainBuyCopy["platform"], "studio") |
| + before := providerCalls(o.billingFixture) |
| + if _, ref := o.srv.admitDomainBuy(ctx, shop, "shop.com"); ref == nil || ref.Status != http.StatusConflict || ref.Msg != want { |
| + t.Fatalf("admitDomainBuy(customer) = %+v, want 409 %q", ref, want) |
| + } |
| + if _, _, ref := startQuotedPurchase(o.srv, ctx, shop, "web", "shop.com", purchaseContact(), "buyer@example.test"); ref == nil || |
| + ref.Status != http.StatusConflict || ref.Msg != want { |
| + t.Fatalf("purchase for the customer = %+v, want 409 %q", ref, want) |
| + } |
| + if n := providerCalls(o.billingFixture); n != before { |
| + t.Fatalf("the refused purchase made %d provider requests", n-before) |
| + } |
| + if b, err := o.st.BillingAccount(shop.ID); err != nil || b != nil { |
| + t.Fatalf("customer billing row = %+v %v, want no payment customer", b, err) |
| + } |
| +} |
| + |
| +// noticeMail records each keymail delivery as to|subject|body. |
| +type noticeMail struct { |
| + mu sync.Mutex |
| + sent []string |
| +} |
| + |
| +func (m *noticeMail) send(_ context.Context, to, subject, body string) (string, error) { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.sent = append(m.sent, to+"|"+subject+"|"+body) |
| + return "", nil |
| +} |
| + |
| +func (m *noticeMail) sentCopy() []string { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return append([]string(nil), m.sent...) |
| +} |
| + |
| +// noticeWorld is plans on, the platform studio with its customer shop on |
| +// the free plan, and keymail delivery recorded. |
| +func noticeWorld(t *testing.T) (*consoleFixture, *Account, *Account, *noticeMail) { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + studio, shop := linkedShop(t, fx, "free") |
| + mail := ¬iceMail{} |
| + fx.srv.consoleMail, fx.srv.sendFederated = nil, mail.send |
| + return fx, studio, shop, mail |
| +} |
| + |
| +// storageOver stores and returns acct's storage cap row, over the limit |
| +// from now, as the grace pass leaves it. |
| +func storageOver(t *testing.T, fx *consoleFixture, acct *Account, now time.Time) capState { |
| + t.Helper() |
| + st := evaluateCap(nil, capStorage, 2<<30, 1<<30, now) |
| + st.AccountID = acct.ID |
| + if err := fx.st.PutCapState(st); err != nil { |
| + t.Fatal(err) |
| + } |
| + return st |
| +} |
| + |
| +func TestPlanNoticesForLinkedAccountsGoToPlatformOwners(t *testing.T) { |
| + fx, studio, shop, mail := noticeWorld(t) |
| + ctx := context.Background() |
| + // The customer is claimed, and the platform has a member who is not an |
| + // owner: neither hears. |
| + if err := fx.st.AddMember(shop.ID, "claimer@example.com", RoleOwner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(studio.ID, "kim@example.com", RoleMember, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + st := storageOver(t, fx, shop, planNow) |
| + if err := fx.srv.notifyPlanOwners(ctx, shop, []capState{st}, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := mail.sentCopy() |
| + if len(sent) != 1 { |
| + t.Fatalf("sent %d notices %v, want one, to the platform's owner", len(sent), sent) |
| + } |
| + parts := strings.SplitN(sent[0], "|", 3) |
| + to, subject, body := parts[0], parts[1], parts[2] |
| + if want := "owner" + studio.Sqid + "@example.com"; to != want { |
| + t.Fatalf("notice to %s, want the platform's owner %s", to, want) |
| + } |
| + if want := fmt.Sprintf(planNoticeCopy["email.platform.subject"], "shop", shop.Sqid); subject != want { |
| + t.Fatalf("subject %q, want %q", subject, want) |
| + } |
| + line := planNoticeText(planNoticesOf([]capState{st}, planNow, nil)[0], "email") |
| + for _, want := range []string{ |
| + fmt.Sprintf(planNoticeCopy["email.platform.intro"], "shop", shop.Sqid, "studio"), |
| + line, |
| + fmt.Sprintf(planNoticeCopy["email.platform.ways_out"], studio.Sqid, shop.Sqid, studio.Sqid, shop.Sqid), |
| + } { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("body lacks %q:\n%s", want, body) |
| + } |
| + } |
| + // No link into the customer account: the platform's staff can't open it. |
| + for _, never := range []string{"/a/" + shop.Sqid, "/settings", "/plan/keep"} { |
| + if strings.Contains(body, never) { |
| + t.Errorf("body links %q:\n%s", never, body) |
| + } |
| + } |
| + |
| + // The platform's own notices are as they were. |
| + own := storageOver(t, fx, studio, planNow) |
| + if err := fx.srv.notifyPlanOwners(ctx, studio, []capState{own}, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent = mail.sentCopy() |
| + if len(sent) != 2 { |
| + t.Fatalf("sent %v, want the platform's own notice too", sent) |
| + } |
| + parts = strings.SplitN(sent[1], "|", 3) |
| + if want := fmt.Sprintf(planNoticeCopy["email.subject"], studio.Sqid); parts[0] != "owner"+studio.Sqid+"@example.com" || parts[1] != want { |
| + t.Fatalf("platform's own notice %s %q, want its owner and %q", parts[0], parts[1], want) |
| + } |
| +} |
| + |
| +func TestPlatformOwnerNoticeCountsForAfterGraceDue(t *testing.T) { |
| + fx, _, shop, mail := noticeWorld(t) |
| + ctx := context.Background() |
| + st := storageOver(t, fx, shop, planNow) |
| + if err := fx.srv.notifyPlanOwners(ctx, shop, []capState{st}, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(mail.sentCopy()); n != 1 { |
| + t.Fatalf("sent %d notices, want one", n) |
| + } |
| + row, ok := capRow(t, fx, shop, capStorage) |
| + if !ok || !row.NoticeAt.Equal(planNow.UTC().Truncate(time.Second)) { |
| + t.Fatalf("row %+v %v, want NoticeAt at the delivery", row, ok) |
| + } |
| + if !afterGraceDue(row, row.GraceEnds.Add(72*time.Hour)) { |
| + t.Fatalf("after grace with the platform's owners told: not due (%+v)", row) |
| + } |
| + |
| + // A customer whose platform has no owners (no live row here): nobody |
| + // hears, not even the customer's own owner, so nothing counts. |
| + orphan := testAccountID() |
| + if _, err := fx.st.EnsureLinkedAccount(orphan, domains.Sqid(orphan), "orphan", "zzzz", "", strings.Repeat("ef", 16), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + o, err := fx.st.AccountBySqid(domains.Sqid(orphan)) |
| + if err != nil || o == nil { |
| + t.Fatal(o, err) |
| + } |
| + if err := fx.st.AddMember(o.ID, "claimer@example.com", RoleOwner, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + ost := storageOver(t, fx, o, planNow) |
| + if err := fx.srv.notifyPlanOwners(ctx, o, []capState{ost}, planNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(mail.sentCopy()); n != 1 { |
| + t.Fatalf("sent %v, want nothing more", mail.sentCopy()) |
| + } |
| + row, ok = capRow(t, fx, o, capStorage) |
| + if !ok || !row.NoticeAt.IsZero() || afterGraceDue(row, row.GraceEnds.Add(72*time.Hour)) { |
| + t.Fatalf("row %+v %v, want no notice and nothing due", row, ok) |
| + } |
| +} |