Move the displacement rule into the entitlements package
The OpenSpec change grant-pauses-subscription-billing (#269, #270, #277, #278) is added: while an operator's grant holds a ladder against an organization's own subscription, the console pauses the subscription's payment collection at Stripe and resumes it when the grant ends; the ending act delivers the subscription's tier again; no second subscription is sold on a ladder a subscription pays for; the paused subscription can be switched to the granted tier or above, or resumed when the grant ranks below it. First section: the rule that decides which of a subscription's products the reconcile leaves alone while another plan holds their ladder moves from internal/fulfillment to internal/entitlements/displacement.go (Rung, RungsByProduct, Displacement, DisplacementsFromRows, DisplacedProducts, ChooseTiers, Outrank), with bodies unchanged, so the acts that end a grant can apply it in later sections. The reconcile, the organization page and the subscriptions list call it there; nothing behaves differently. TestDisplacedProducts and TestChooseTiers move with their rows unchanged. Review: one major, a break no row could fail (dropping the first-rung break); replaced by reading a bundle by its first rung only, which the bundle row catches. A test row type keeps its unexported name; two doc comments rewritten. Breaks: 2 of 2 caught (a bundle read by its first rung only; a tie broken by the higher product id). Full suite on reset databases: 4731 pass, 14 skip.
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Rung is one ladder a product is a tier of, with the tier's rank.
|
||||
type Rung struct {
|
||||
LadderID string
|
||||
Rank int32
|
||||
}
|
||||
|
||||
// RungsByProduct groups the conferral shapes' rows by product, each product's
|
||||
// rungs in the rows' order (ladder id order, as ListConferralShapes returns
|
||||
// them). It reads no row, and it is exported because the reconcile, the
|
||||
// organization page and the operator's subscriptions list apply the same rule
|
||||
// to a subscription's current products; the ending acts in this package call
|
||||
// it too.
|
||||
func RungsByProduct(rows []ListConferralShapesRow) map[string][]Rung {
|
||||
rungs := make(map[string][]Rung)
|
||||
for _, r := range rows {
|
||||
if !r.PlanLadderID.Valid {
|
||||
continue
|
||||
}
|
||||
rungs[r.ProductID] = append(rungs[r.ProductID], Rung{
|
||||
LadderID: r.PlanLadderID.UUID.String(),
|
||||
Rank: r.Rank.Int32,
|
||||
})
|
||||
}
|
||||
return rungs
|
||||
}
|
||||
|
||||
// Displacement is a ladder on which a subscription is displaced and another
|
||||
// plan holds the ladder (core.subscription_displacements): the displaced
|
||||
// product, and the holder's provision and source.
|
||||
type Displacement struct {
|
||||
LadderID string
|
||||
LadderName string
|
||||
DisplacedProductID string
|
||||
HolderProvisionID string
|
||||
HolderSource string
|
||||
}
|
||||
|
||||
// DisplacementsFromRows turns the displacement query's rows into
|
||||
// Displacements, in the rows' order.
|
||||
func DisplacementsFromRows(rows []ListSubscriptionDisplacementsRow) []Displacement {
|
||||
out := make([]Displacement, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, Displacement{
|
||||
LadderID: r.PlanLadderID,
|
||||
LadderName: r.LadderName,
|
||||
DisplacedProductID: r.DisplacedProductID,
|
||||
HolderProvisionID: r.HolderProvisionID,
|
||||
HolderSource: r.HolderSource,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DisplacedProducts maps each missing product the reconcile leaves alone to
|
||||
// the displacement that decides it: the first of its rungs, in rung order,
|
||||
// whose ladder the subscription is displaced on. The check is per ladder, so
|
||||
// another product of a displaced ladder is left alone too. It indexes the
|
||||
// displacements by ladder, keeping the first row of each, and reads no row:
|
||||
// the reconcile enforces the rule, and the organization page and the
|
||||
// subscriptions list read it too, so neither the card nor the list marks a
|
||||
// subscription Not delivering on a ladder the reconcile would confer. The
|
||||
// ending acts in this package call it too.
|
||||
func DisplacedProducts(missing []string, rungs map[string][]Rung, displacements []Displacement) map[string]Displacement {
|
||||
byLadder := make(map[string]Displacement, len(displacements))
|
||||
for _, d := range displacements {
|
||||
if _, seen := byLadder[d.LadderID]; !seen {
|
||||
byLadder[d.LadderID] = d
|
||||
}
|
||||
}
|
||||
left := make(map[string]Displacement)
|
||||
for _, p := range missing {
|
||||
for _, r := range rungs[p] {
|
||||
if d, ok := byLadder[r.LadderID]; ok {
|
||||
left[p] = d
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return left
|
||||
}
|
||||
|
||||
// Outrank is the product that outranked another and the ladder they share.
|
||||
type Outrank struct {
|
||||
ByProductID string
|
||||
LadderID string
|
||||
}
|
||||
|
||||
// candidate is a product in ChooseTiers' walk: its id, its highest rank on any
|
||||
// of its ladders (-1 for a product on none) and its rungs.
|
||||
type candidate struct {
|
||||
id string
|
||||
top int32
|
||||
rungs []Rung
|
||||
}
|
||||
|
||||
// shared returns the first ladder of c's rungs that a kept product holds, or
|
||||
// "" when c shares none.
|
||||
func shared(c candidate, held map[string]string) string {
|
||||
for _, r := range c.rungs {
|
||||
if _, ok := held[r.LadderID]; ok {
|
||||
return r.LadderID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ChooseTiers keeps, of products that share a ladder, the one with the highest
|
||||
// rank on any of its ladders, then the lower product id, and records the
|
||||
// shared ladder and the product that outranked each one it leaves out. A
|
||||
// product on no ladder is always kept. It returns kept in the order of
|
||||
// products and reads no row.
|
||||
func ChooseTiers(products []string, rungs map[string][]Rung) (kept []string, outranked map[string]Outrank) {
|
||||
cands := make([]candidate, 0, len(products))
|
||||
for _, id := range products {
|
||||
c := candidate{id: id, top: -1, rungs: rungs[id]}
|
||||
for _, r := range c.rungs {
|
||||
c.top = max(c.top, r.Rank)
|
||||
}
|
||||
cands = append(cands, c)
|
||||
}
|
||||
slices.SortStableFunc(cands, func(a, b candidate) int {
|
||||
if c := cmp.Compare(b.top, a.top); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.id, b.id)
|
||||
})
|
||||
outranked = make(map[string]Outrank)
|
||||
held := make(map[string]string)
|
||||
keep := make(map[string]bool, len(cands))
|
||||
for _, c := range cands {
|
||||
if taken := shared(c, held); taken != "" {
|
||||
outranked[c.id] = Outrank{ByProductID: held[taken], LadderID: taken}
|
||||
continue
|
||||
}
|
||||
keep[c.id] = true
|
||||
for _, r := range c.rungs {
|
||||
held[r.LadderID] = c.id
|
||||
}
|
||||
}
|
||||
for _, id := range products {
|
||||
if keep[id] {
|
||||
kept = append(kept, id)
|
||||
}
|
||||
}
|
||||
return kept, outranked
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// displacedProductsRow is one case of DisplacedProducts: the missing products,
|
||||
// their rungs, the subscription's displacements and the products left out.
|
||||
type displacedProductsRow struct {
|
||||
name string
|
||||
missing []string
|
||||
rungs map[string][]Rung
|
||||
displacements []Displacement
|
||||
want map[string]Displacement
|
||||
}
|
||||
|
||||
// checkDisplacedProducts runs one row.
|
||||
func checkDisplacedProducts(t *testing.T, row displacedProductsRow) {
|
||||
t.Helper()
|
||||
if got := DisplacedProducts(row.missing, row.rungs, row.displacements); !maps.Equal(got, row.want) {
|
||||
t.Errorf("DisplacedProducts(%s) = %v, want %v", row.name, got, row.want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDisplacedProducts pins which missing products the reconcile leaves
|
||||
// alone: those with a rung on a ladder the subscription is displaced on.
|
||||
func TestDisplacedProducts(t *testing.T) {
|
||||
onL1 := Displacement{LadderID: "L1", DisplacedProductID: "A", HolderProvisionID: "H"}
|
||||
for _, row := range []displacedProductsRow{
|
||||
{
|
||||
name: "a missing product on a displaced ladder is left out",
|
||||
missing: []string{"A"},
|
||||
rungs: map[string][]Rung{"A": {{LadderID: "L1", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"A": onL1},
|
||||
},
|
||||
{
|
||||
name: "a missing product on another ladder is kept",
|
||||
missing: []string{"A"},
|
||||
rungs: map[string][]Rung{"A": {{LadderID: "L2", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{},
|
||||
},
|
||||
{
|
||||
name: "a lower tier of the displaced ladder is left out",
|
||||
missing: []string{"B"},
|
||||
rungs: map[string][]Rung{"B": {{LadderID: "L1", Rank: 0}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"B": onL1},
|
||||
},
|
||||
{
|
||||
name: "a bundle whose second rung is displaced is left out",
|
||||
missing: []string{"C"},
|
||||
rungs: map[string][]Rung{"C": {{LadderID: "L0", Rank: 1}, {LadderID: "L1", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"C": onL1},
|
||||
},
|
||||
{
|
||||
name: "an add-on is kept",
|
||||
missing: []string{"D"},
|
||||
rungs: map[string][]Rung{},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{},
|
||||
},
|
||||
} {
|
||||
checkDisplacedProducts(t, row)
|
||||
}
|
||||
}
|
||||
|
||||
// chooseTiersRow is one case of ChooseTiers: the products' rungs, the products
|
||||
// kept and the products left out with what outranked each.
|
||||
type chooseTiersRow struct {
|
||||
name string
|
||||
products []string
|
||||
rungs map[string][]Rung
|
||||
kept []string
|
||||
outranked map[string]Outrank
|
||||
}
|
||||
|
||||
// checkChooseTiers runs one row with its products in the given order and
|
||||
// reversed; kept is wanted in the order of the products given.
|
||||
func checkChooseTiers(t *testing.T, row chooseTiersRow) {
|
||||
t.Helper()
|
||||
reversed := slices.Clone(row.products)
|
||||
slices.Reverse(reversed)
|
||||
for _, order := range [][]string{row.products, reversed} {
|
||||
gotKept, gotOut := ChooseTiers(order, row.rungs)
|
||||
var wantKept []string
|
||||
for _, p := range order {
|
||||
if slices.Contains(row.kept, p) {
|
||||
wantKept = append(wantKept, p)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(gotKept, wantKept) {
|
||||
t.Errorf("ChooseTiers(%s) kept %v, want %v, products in the order %v", row.name, gotKept, wantKept, order)
|
||||
}
|
||||
if !maps.Equal(gotOut, row.outranked) {
|
||||
t.Errorf("ChooseTiers(%s) outranked %v, want %v, products in the order %v", row.name, gotOut, row.outranked, order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChooseTiers pins which of the products that share a ladder the
|
||||
// subscription confers: the highest rank on any ladder, then the lower id.
|
||||
func TestChooseTiers(t *testing.T) {
|
||||
for _, row := range []chooseTiersRow{
|
||||
{
|
||||
name: "two tiers of one ladder keep the higher",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 0}}, "Q": {{"L1", 1}}},
|
||||
kept: []string{"Q"},
|
||||
outranked: map[string]Outrank{"P": {ByProductID: "Q", LadderID: "L1"}},
|
||||
},
|
||||
{
|
||||
name: "tiers of two ladders are both kept",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 1}}, "Q": {{"L2", 1}}},
|
||||
kept: []string{"P", "Q"},
|
||||
},
|
||||
{
|
||||
name: "a bundle outranks a tier on one of its ladders",
|
||||
products: []string{"X", "Y"},
|
||||
rungs: map[string][]Rung{"X": {{"L1", 3}, {"L2", 1}}, "Y": {{"L2", 2}}},
|
||||
kept: []string{"X"},
|
||||
outranked: map[string]Outrank{"Y": {ByProductID: "X", LadderID: "L2"}},
|
||||
},
|
||||
{
|
||||
name: "a higher tier takes a shared ladder from a lower bundle",
|
||||
products: []string{"Y", "Z"},
|
||||
rungs: map[string][]Rung{"Y": {{"L2", 2}}, "Z": {{"L2", 1}, {"L3", 1}}},
|
||||
kept: []string{"Y"},
|
||||
outranked: map[string]Outrank{"Z": {ByProductID: "Y", LadderID: "L2"}},
|
||||
},
|
||||
{
|
||||
name: "an add-on is always kept",
|
||||
products: []string{"A", "Q"},
|
||||
rungs: map[string][]Rung{"Q": {{"L1", 0}}},
|
||||
kept: []string{"A", "Q"},
|
||||
},
|
||||
{
|
||||
name: "equal ranks keep the lower product id",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 1}}, "Q": {{"L1", 1}}},
|
||||
kept: []string{"P"},
|
||||
outranked: map[string]Outrank{"Q": {ByProductID: "P", LadderID: "L1"}},
|
||||
},
|
||||
} {
|
||||
checkChooseTiers(t, row)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@
|
||||
package fulfillment
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
@@ -23,7 +22,6 @@ import (
|
||||
"log/slog"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
@@ -667,93 +665,14 @@ func sortedProducts(desired map[string]int32) []string {
|
||||
return slices.Sorted(maps.Keys(desired))
|
||||
}
|
||||
|
||||
// Rung is one ladder a product is a tier of, with the tier's rank.
|
||||
type Rung struct {
|
||||
LadderID string
|
||||
Rank int32
|
||||
}
|
||||
|
||||
// RungsByProduct groups the conferral shapes' rows by product, each product's
|
||||
// rungs in the rows' order (ladder id order, as ListConferralShapes returns
|
||||
// them). It reads no row, and it is exported because the organization page
|
||||
// and the operator's subscriptions list apply the same rule to a
|
||||
// subscription's current products.
|
||||
func RungsByProduct(rows []entitlements.ListConferralShapesRow) map[string][]Rung {
|
||||
rungs := make(map[string][]Rung)
|
||||
for _, r := range rows {
|
||||
if !r.PlanLadderID.Valid {
|
||||
continue
|
||||
}
|
||||
rungs[r.ProductID] = append(rungs[r.ProductID], Rung{
|
||||
LadderID: r.PlanLadderID.UUID.String(),
|
||||
Rank: r.Rank.Int32,
|
||||
})
|
||||
}
|
||||
return rungs
|
||||
}
|
||||
|
||||
// conferralRungs reads the ladders and ranks of the products' current shapes,
|
||||
// once, and groups them by product.
|
||||
func conferralRungs(ctx context.Context, entQ *entitlements.Queries, products []string) (map[string][]Rung, error) {
|
||||
func conferralRungs(ctx context.Context, entQ *entitlements.Queries, products []string) (map[string][]entitlements.Rung, error) {
|
||||
rows, err := entQ.ListConferralShapes(ctx, products)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reconcile: list conferral shapes: %w", err)
|
||||
}
|
||||
return RungsByProduct(rows), nil
|
||||
}
|
||||
|
||||
// Displacement is a ladder on which a subscription is displaced and another
|
||||
// plan holds the ladder (core.subscription_displacements): the displaced
|
||||
// product, and the holder's provision and source.
|
||||
type Displacement struct {
|
||||
LadderID string
|
||||
LadderName string
|
||||
DisplacedProductID string
|
||||
HolderProvisionID string
|
||||
HolderSource string
|
||||
}
|
||||
|
||||
// displacementsFromRows turns the displacement query's rows into
|
||||
// Displacements, in the rows' order.
|
||||
func displacementsFromRows(rows []entitlements.ListSubscriptionDisplacementsRow) []Displacement {
|
||||
out := make([]Displacement, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, Displacement{
|
||||
LadderID: r.PlanLadderID,
|
||||
LadderName: r.LadderName,
|
||||
DisplacedProductID: r.DisplacedProductID,
|
||||
HolderProvisionID: r.HolderProvisionID,
|
||||
HolderSource: r.HolderSource,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DisplacedProducts maps each missing product the reconcile leaves alone to
|
||||
// the displacement that decides it: the first of its rungs, in rung order,
|
||||
// whose ladder the subscription is displaced on. The check is per ladder, so
|
||||
// another product of a displaced ladder is left alone too. It indexes the
|
||||
// displacements by ladder, keeping the first row of each, and reads no row:
|
||||
// the reconcile enforces the rule and the organization page and the
|
||||
// subscriptions list read it too, so neither the card nor the list marks a
|
||||
// subscription Not delivering on a ladder the reconcile would confer.
|
||||
func DisplacedProducts(missing []string, rungs map[string][]Rung, displacements []Displacement) map[string]Displacement {
|
||||
byLadder := make(map[string]Displacement, len(displacements))
|
||||
for _, d := range displacements {
|
||||
if _, seen := byLadder[d.LadderID]; !seen {
|
||||
byLadder[d.LadderID] = d
|
||||
}
|
||||
}
|
||||
left := make(map[string]Displacement)
|
||||
for _, p := range missing {
|
||||
for _, r := range rungs[p] {
|
||||
if d, ok := byLadder[r.LadderID]; ok {
|
||||
left[p] = d
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return left
|
||||
return entitlements.RungsByProduct(rows), nil
|
||||
}
|
||||
|
||||
// convergeConferrals brings the subscription's live provisions to desired:
|
||||
@@ -761,8 +680,8 @@ func DisplacedProducts(missing []string, rungs map[string][]Rung, displacements
|
||||
// and a provision no longer desired is ended. A missing product whose ladder
|
||||
// another plan took from the subscription and holds is left alone
|
||||
// (core.subscription_displacements), and of two products that share a ladder
|
||||
// only the higher-ranked is conferred (chooseTiers). It reports whether it
|
||||
// wrote anything.
|
||||
// only the higher-ranked is conferred (entitlements.ChooseTiers). It reports
|
||||
// whether it wrote anything.
|
||||
func convergeConferrals(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
@@ -797,7 +716,7 @@ func convergeConferrals(
|
||||
remaining = append(remaining, productID)
|
||||
}
|
||||
}
|
||||
kept, outranked := chooseTiers(remaining, rungs)
|
||||
kept, outranked := entitlements.ChooseTiers(remaining, rungs)
|
||||
for _, productID := range remaining {
|
||||
o, out := outranked[productID]
|
||||
if !out {
|
||||
@@ -806,8 +725,8 @@ func convergeConferrals(
|
||||
logger.Warn("reconcile: product not conferred; a higher tier of the subscription holds its ladder",
|
||||
slog.String("subscription_id", subUUID.String()),
|
||||
slog.String("product_id", productID),
|
||||
slog.String("plan_ladder_id", o.ladderID),
|
||||
slog.String("outranked_by_product_id", o.byProductID))
|
||||
slog.String("plan_ladder_id", o.LadderID),
|
||||
slog.String("outranked_by_product_id", o.ByProductID))
|
||||
}
|
||||
|
||||
// Missing product -> confer; quantity-only delta -> update_conferral_bounds.
|
||||
@@ -825,19 +744,19 @@ func convergeConferrals(
|
||||
}
|
||||
|
||||
// productsLeftAlone reads the subscription's displacements, takes as missing
|
||||
// the products with no live provision, and returns those DisplacedProducts
|
||||
// leaves alone, logging each in order once. The read runs under the pool row
|
||||
// the caller holds.
|
||||
// the products with no live provision, and returns those
|
||||
// entitlements.DisplacedProducts leaves alone, logging each in order once.
|
||||
// The read runs under the pool row the caller holds.
|
||||
func productsLeftAlone(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
entQ *entitlements.Queries,
|
||||
order []string,
|
||||
rungs map[string][]Rung,
|
||||
rungs map[string][]entitlements.Rung,
|
||||
liveByProduct map[string]entitlements.PoolProvision,
|
||||
subUUID uuid.UUID,
|
||||
poolID string,
|
||||
) (map[string]Displacement, error) {
|
||||
) (map[string]entitlements.Displacement, error) {
|
||||
rows, err := entQ.ListSubscriptionDisplacements(ctx, entitlements.ListSubscriptionDisplacementsParams{
|
||||
SubscriptionID: subUUID.String(),
|
||||
PoolID: poolID,
|
||||
@@ -851,7 +770,7 @@ func productsLeftAlone(
|
||||
missing = append(missing, productID)
|
||||
}
|
||||
}
|
||||
left := DisplacedProducts(missing, rungs, displacementsFromRows(rows))
|
||||
left := entitlements.DisplacedProducts(missing, rungs, entitlements.DisplacementsFromRows(rows))
|
||||
for _, productID := range order {
|
||||
d, out := left[productID]
|
||||
if !out {
|
||||
@@ -866,72 +785,6 @@ func productsLeftAlone(
|
||||
return left, nil
|
||||
}
|
||||
|
||||
// outrank is the product that outranked another and the ladder they share.
|
||||
type outrank struct {
|
||||
byProductID string
|
||||
ladderID string
|
||||
}
|
||||
|
||||
// candidate is a product in chooseTiers' walk: its id, its highest rank on any
|
||||
// of its ladders (-1 for a product on none) and its rungs.
|
||||
type candidate struct {
|
||||
id string
|
||||
top int32
|
||||
rungs []Rung
|
||||
}
|
||||
|
||||
// shared returns the first ladder of c's rungs that a kept product holds, or
|
||||
// "" when c shares none.
|
||||
func shared(c candidate, held map[string]string) string {
|
||||
for _, r := range c.rungs {
|
||||
if _, ok := held[r.LadderID]; ok {
|
||||
return r.LadderID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// chooseTiers keeps, of products that share a ladder, the one with the highest
|
||||
// rank on any of its ladders, then the lower product id, and records the
|
||||
// shared ladder and the product that outranked each one it leaves out. A
|
||||
// product on no ladder is always kept. It returns kept in the order of
|
||||
// products and reads no row.
|
||||
func chooseTiers(products []string, rungs map[string][]Rung) (kept []string, outranked map[string]outrank) {
|
||||
cands := make([]candidate, 0, len(products))
|
||||
for _, id := range products {
|
||||
c := candidate{id: id, top: -1, rungs: rungs[id]}
|
||||
for _, r := range c.rungs {
|
||||
c.top = max(c.top, r.Rank)
|
||||
}
|
||||
cands = append(cands, c)
|
||||
}
|
||||
slices.SortStableFunc(cands, func(a, b candidate) int {
|
||||
if c := cmp.Compare(b.top, a.top); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.id, b.id)
|
||||
})
|
||||
outranked = make(map[string]outrank)
|
||||
held := make(map[string]string)
|
||||
keep := make(map[string]bool, len(cands))
|
||||
for _, c := range cands {
|
||||
if taken := shared(c, held); taken != "" {
|
||||
outranked[c.id] = outrank{byProductID: held[taken], ladderID: taken}
|
||||
continue
|
||||
}
|
||||
keep[c.id] = true
|
||||
for _, r := range c.rungs {
|
||||
held[r.LadderID] = c.id
|
||||
}
|
||||
}
|
||||
for _, id := range products {
|
||||
if keep[id] {
|
||||
kept = append(kept, id)
|
||||
}
|
||||
}
|
||||
return kept, outranked
|
||||
}
|
||||
|
||||
// conferOrBound confers productID from the subscription when it has no live
|
||||
// provision, or updates the live provision's bounds when only its quantity
|
||||
// differs. It reports whether it wrote anything.
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
package fulfillment
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
@@ -43,148 +42,3 @@ func TestSortedProducts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// displacedProductsRow is one case of DisplacedProducts: the missing products,
|
||||
// their rungs, the subscription's displacements and the products left out.
|
||||
type displacedProductsRow struct {
|
||||
name string
|
||||
missing []string
|
||||
rungs map[string][]Rung
|
||||
displacements []Displacement
|
||||
want map[string]Displacement
|
||||
}
|
||||
|
||||
// checkDisplacedProducts runs one row.
|
||||
func checkDisplacedProducts(t *testing.T, row displacedProductsRow) {
|
||||
t.Helper()
|
||||
if got := DisplacedProducts(row.missing, row.rungs, row.displacements); !maps.Equal(got, row.want) {
|
||||
t.Errorf("DisplacedProducts(%s) = %v, want %v", row.name, got, row.want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDisplacedProducts pins which missing products the reconcile leaves
|
||||
// alone: those with a rung on a ladder the subscription is displaced on.
|
||||
func TestDisplacedProducts(t *testing.T) {
|
||||
onL1 := Displacement{LadderID: "L1", DisplacedProductID: "A", HolderProvisionID: "H"}
|
||||
for _, row := range []displacedProductsRow{
|
||||
{
|
||||
name: "a missing product on a displaced ladder is left out",
|
||||
missing: []string{"A"},
|
||||
rungs: map[string][]Rung{"A": {{LadderID: "L1", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"A": onL1},
|
||||
},
|
||||
{
|
||||
name: "a missing product on another ladder is kept",
|
||||
missing: []string{"A"},
|
||||
rungs: map[string][]Rung{"A": {{LadderID: "L2", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{},
|
||||
},
|
||||
{
|
||||
name: "a lower tier of the displaced ladder is left out",
|
||||
missing: []string{"B"},
|
||||
rungs: map[string][]Rung{"B": {{LadderID: "L1", Rank: 0}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"B": onL1},
|
||||
},
|
||||
{
|
||||
name: "a bundle whose second rung is displaced is left out",
|
||||
missing: []string{"C"},
|
||||
rungs: map[string][]Rung{"C": {{LadderID: "L0", Rank: 1}, {LadderID: "L1", Rank: 1}}},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{"C": onL1},
|
||||
},
|
||||
{
|
||||
name: "an add-on is kept",
|
||||
missing: []string{"D"},
|
||||
rungs: map[string][]Rung{},
|
||||
displacements: []Displacement{onL1},
|
||||
want: map[string]Displacement{},
|
||||
},
|
||||
} {
|
||||
checkDisplacedProducts(t, row)
|
||||
}
|
||||
}
|
||||
|
||||
// chooseTiersRow is one case of chooseTiers: the products' rungs, the products
|
||||
// kept and the products left out with what outranked each.
|
||||
type chooseTiersRow struct {
|
||||
name string
|
||||
products []string
|
||||
rungs map[string][]Rung
|
||||
kept []string
|
||||
outranked map[string]outrank
|
||||
}
|
||||
|
||||
// checkChooseTiers runs one row with its products in the given order and
|
||||
// reversed; kept is wanted in the order of the products given.
|
||||
func checkChooseTiers(t *testing.T, row chooseTiersRow) {
|
||||
t.Helper()
|
||||
reversed := slices.Clone(row.products)
|
||||
slices.Reverse(reversed)
|
||||
for _, order := range [][]string{row.products, reversed} {
|
||||
gotKept, gotOut := chooseTiers(order, row.rungs)
|
||||
var wantKept []string
|
||||
for _, p := range order {
|
||||
if slices.Contains(row.kept, p) {
|
||||
wantKept = append(wantKept, p)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(gotKept, wantKept) {
|
||||
t.Errorf("chooseTiers(%s) kept %v, want %v, products in the order %v", row.name, gotKept, wantKept, order)
|
||||
}
|
||||
if !maps.Equal(gotOut, row.outranked) {
|
||||
t.Errorf("chooseTiers(%s) outranked %v, want %v, products in the order %v", row.name, gotOut, row.outranked, order)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestChooseTiers pins which of the products that share a ladder the
|
||||
// subscription confers: the highest rank on any ladder, then the lower id.
|
||||
func TestChooseTiers(t *testing.T) {
|
||||
for _, row := range []chooseTiersRow{
|
||||
{
|
||||
name: "two tiers of one ladder keep the higher",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 0}}, "Q": {{"L1", 1}}},
|
||||
kept: []string{"Q"},
|
||||
outranked: map[string]outrank{"P": {byProductID: "Q", ladderID: "L1"}},
|
||||
},
|
||||
{
|
||||
name: "tiers of two ladders are both kept",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 1}}, "Q": {{"L2", 1}}},
|
||||
kept: []string{"P", "Q"},
|
||||
},
|
||||
{
|
||||
name: "a bundle outranks a tier on one of its ladders",
|
||||
products: []string{"X", "Y"},
|
||||
rungs: map[string][]Rung{"X": {{"L1", 3}, {"L2", 1}}, "Y": {{"L2", 2}}},
|
||||
kept: []string{"X"},
|
||||
outranked: map[string]outrank{"Y": {byProductID: "X", ladderID: "L2"}},
|
||||
},
|
||||
{
|
||||
name: "a higher tier takes a shared ladder from a lower bundle",
|
||||
products: []string{"Y", "Z"},
|
||||
rungs: map[string][]Rung{"Y": {{"L2", 2}}, "Z": {{"L2", 1}, {"L3", 1}}},
|
||||
kept: []string{"Y"},
|
||||
outranked: map[string]outrank{"Z": {byProductID: "Y", ladderID: "L2"}},
|
||||
},
|
||||
{
|
||||
name: "an add-on is always kept",
|
||||
products: []string{"A", "Q"},
|
||||
rungs: map[string][]Rung{"Q": {{"L1", 0}}},
|
||||
kept: []string{"A", "Q"},
|
||||
},
|
||||
{
|
||||
name: "equal ranks keep the lower product id",
|
||||
products: []string{"P", "Q"},
|
||||
rungs: map[string][]Rung{"P": {{"L1", 1}}, "Q": {{"L1", 1}}},
|
||||
kept: []string{"P"},
|
||||
outranked: map[string]outrank{"Q": {byProductID: "P", ladderID: "L1"}},
|
||||
},
|
||||
} {
|
||||
checkChooseTiers(t, row)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/catalogsync"
|
||||
stripedb "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
@@ -649,7 +648,7 @@ func subscriptionTitlesFor(subs []billing.ListSubscriptionsPageRow, items []bill
|
||||
for i, r := range rows {
|
||||
converted[i] = entitlements.ListAccountSubscriptionDisplacementsRow(r)
|
||||
}
|
||||
byID := displacedByID(refs, productsBySubscription(items), fulfillment.RungsByProduct(shapes), displacementsBySubscription(converted))
|
||||
byID := displacedByID(refs, productsBySubscription(items), entitlements.RungsByProduct(shapes), displacementsBySubscription(converted))
|
||||
titles := make(map[string]string, len(byID))
|
||||
for id, d := range byID {
|
||||
titles[id] = displacementTitle(1, []displacedSubscription{d})
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
wf "git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/queues"
|
||||
@@ -492,8 +491,8 @@ type displacedSubscription struct {
|
||||
// provision is on no displaced ladder, design D2), and the ladder of each
|
||||
// displacement the rule picks is named. A displacement whose ladder no
|
||||
// current product names produces nothing. It reads no row.
|
||||
func displacedOnPage(products []string, rungs map[string][]fulfillment.Rung, displacements []fulfillment.Displacement) displacedSubscription {
|
||||
left := fulfillment.DisplacedProducts(products, rungs, displacements)
|
||||
func displacedOnPage(products []string, rungs map[string][]entitlements.Rung, displacements []entitlements.Displacement) displacedSubscription {
|
||||
left := entitlements.DisplacedProducts(products, rungs, displacements)
|
||||
var out displacedSubscription
|
||||
for _, p := range products {
|
||||
d, ok := left[p]
|
||||
@@ -1809,7 +1808,7 @@ type subscriptionRef struct {
|
||||
// rungs and its displacements. A subscription with no displaced ladder has no
|
||||
// entry. The Billing card and the subscriptions list group by subscription
|
||||
// here. It reads no row.
|
||||
func displacedByID(subs []subscriptionRef, products map[string][]string, rungs map[string][]fulfillment.Rung, displacements map[string][]fulfillment.Displacement) map[string]displacedSubscription {
|
||||
func displacedByID(subs []subscriptionRef, products map[string][]string, rungs map[string][]entitlements.Rung, displacements map[string][]entitlements.Displacement) map[string]displacedSubscription {
|
||||
out := make(map[string]displacedSubscription)
|
||||
for _, s := range subs {
|
||||
if !subscriptionMayBeDisplaced(s.Status) {
|
||||
@@ -1823,12 +1822,12 @@ func displacedByID(subs []subscriptionRef, products map[string][]string, rungs m
|
||||
}
|
||||
|
||||
// displacementsBySubscription is the one mapping of a displacement row's
|
||||
// fields to fulfillment.Displacement, grouped by subscription. It reads no
|
||||
// fields to entitlements.Displacement, grouped by subscription. It reads no
|
||||
// row.
|
||||
func displacementsBySubscription(rows []entitlements.ListAccountSubscriptionDisplacementsRow) map[string][]fulfillment.Displacement {
|
||||
by := make(map[string][]fulfillment.Displacement)
|
||||
func displacementsBySubscription(rows []entitlements.ListAccountSubscriptionDisplacementsRow) map[string][]entitlements.Displacement {
|
||||
by := make(map[string][]entitlements.Displacement)
|
||||
for _, d := range rows {
|
||||
by[d.SubscriptionID] = append(by[d.SubscriptionID], fulfillment.Displacement{
|
||||
by[d.SubscriptionID] = append(by[d.SubscriptionID], entitlements.Displacement{
|
||||
LadderID: d.PlanLadderID,
|
||||
LadderName: d.LadderName,
|
||||
DisplacedProductID: d.DisplacedProductID,
|
||||
@@ -1863,7 +1862,7 @@ func displacementTitleFor(subs []billing.Subscription, items []billing.ListCurre
|
||||
for i, s := range subs {
|
||||
refs[i] = subscriptionRef{ID: s.SubscriptionID, Status: s.Status}
|
||||
}
|
||||
byID := displacedByID(refs, productsBySubscription(items), fulfillment.RungsByProduct(shapes), displacementsBySubscription(rows))
|
||||
byID := displacedByID(refs, productsBySubscription(items), entitlements.RungsByProduct(shapes), displacementsBySubscription(rows))
|
||||
var displaced []displacedSubscription
|
||||
for _, ref := range refs {
|
||||
if d, ok := byID[ref.ID]; ok {
|
||||
|
||||
@@ -21,7 +21,6 @@ import (
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/forms"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/web"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -1345,33 +1344,33 @@ func TestDisplacementTitle(t *testing.T) {
|
||||
type displacedOnPageRow struct {
|
||||
name string
|
||||
products []string
|
||||
rungs map[string][]fulfillment.Rung
|
||||
displacements []fulfillment.Displacement
|
||||
rungs map[string][]entitlements.Rung
|
||||
displacements []entitlements.Displacement
|
||||
want displacedSubscription
|
||||
}
|
||||
|
||||
func displacedOnPageRows() []displacedOnPageRow {
|
||||
held := func(ladder, name string) fulfillment.Displacement {
|
||||
return fulfillment.Displacement{LadderID: ladder, LadderName: name, HolderProvisionID: "p-grant", HolderSource: "grant"}
|
||||
held := func(ladder, name string) entitlements.Displacement {
|
||||
return entitlements.Displacement{LadderID: ladder, LadderName: name, HolderProvisionID: "p-grant", HolderSource: "grant"}
|
||||
}
|
||||
hosting := displacedLadder{ID: "l-hosting", Name: "Hosting"}
|
||||
grant := displacedHolder{ProvisionID: "p-grant", Source: "grant"}
|
||||
return []displacedOnPageRow{
|
||||
{"a displacement on a ladder a current product names",
|
||||
[]string{"tier"}, map[string][]fulfillment.Rung{"tier": {{LadderID: "l-hosting", Rank: 1}}},
|
||||
[]fulfillment.Displacement{held("l-hosting", "Hosting")},
|
||||
[]string{"tier"}, map[string][]entitlements.Rung{"tier": {{LadderID: "l-hosting", Rank: 1}}},
|
||||
[]entitlements.Displacement{held("l-hosting", "Hosting")},
|
||||
displacedSubscription{Ladders: []displacedLadder{hosting}, Holders: []displacedHolder{grant}}},
|
||||
{"the item moved off the ladder",
|
||||
[]string{"other"}, map[string][]fulfillment.Rung{"other": {{LadderID: "l-support", Rank: 1}}},
|
||||
[]fulfillment.Displacement{held("l-hosting", "Hosting")},
|
||||
[]string{"other"}, map[string][]entitlements.Rung{"other": {{LadderID: "l-support", Rank: 1}}},
|
||||
[]entitlements.Displacement{held("l-hosting", "Hosting")},
|
||||
displacedSubscription{}},
|
||||
{"the item removed",
|
||||
nil, map[string][]fulfillment.Rung{"tier": {{LadderID: "l-hosting", Rank: 1}}},
|
||||
[]fulfillment.Displacement{held("l-hosting", "Hosting")},
|
||||
nil, map[string][]entitlements.Rung{"tier": {{LadderID: "l-hosting", Rank: 1}}},
|
||||
[]entitlements.Displacement{held("l-hosting", "Hosting")},
|
||||
displacedSubscription{}},
|
||||
{"a bundle displaced on one ladder",
|
||||
[]string{"bundle"}, map[string][]fulfillment.Rung{"bundle": {{LadderID: "l-hosting", Rank: 1}, {LadderID: "l-support", Rank: 1}}},
|
||||
[]fulfillment.Displacement{held("l-support", "Support")},
|
||||
[]string{"bundle"}, map[string][]entitlements.Rung{"bundle": {{LadderID: "l-hosting", Rank: 1}, {LadderID: "l-support", Rank: 1}}},
|
||||
[]entitlements.Displacement{held("l-support", "Support")},
|
||||
displacedSubscription{Ladders: []displacedLadder{{ID: "l-support", Name: "Support"}}, Holders: []displacedHolder{grant}}},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-10-27
|
||||
@@ -0,0 +1,618 @@
|
||||
## Context
|
||||
|
||||
Line numbers are at HEAD `a4c31607`.
|
||||
|
||||
**The displaced subscription today.** An operator's grant over a tier a subscription pays for supersedes the subscription's position inside `core.confer`. The subscription's reconcile then leaves the ladder alone: `convergeConferrals` (`internal/fulfillment/reconcile.go:766-825`) reads the live provisions, the shapes of the desired products (`conferralRungs`, `:697-703`) and the subscription's displacements (`productsLeftAlone`, `:831-867`, reading `ListSubscriptionDisplacements` over `core.subscription_displacements`, `internal/db/migrations/00034_subscription_displacements.sql`), and `DisplacedProducts` (`:740-757`) maps each missing product with a rung on a displaced ladder to its displacement. Those products are logged and not conferred; `chooseTiers` (`:899-933`) decides the rest. Nothing is sent to Stripe, so the subscription keeps billing. The pure rule is exported because the organization page (`displacedOnPage`, `internal/server/operator_enrollment.go:495-509`) and the subscriptions list (`subscriptionTitlesFor`, `internal/server/operator_billing.go:643`) call it too.
|
||||
|
||||
**The member's side.** Every plan move resolves its subscription through the position on the ladder: `resolveLadderSubscription` (`internal/fulfillment/plan_change.go:770-850`) reads the position and refuses one no subscription backs (`:801-804`); `SwitchPlan` (`:196`), `KeepCurrentPlan` (`:474`), `PreviewSwitch` (`:554`), `CancelSubscription` (`:619`) and `SubscriptionBacksLadder` (`:755`) call it. The Products page builds each ladder's `plans.Position` in `onLadder` (`internal/server/plan_offer.go:133-156`), which sets `Subscribed` only when the held position names a subscription (`:142-145`). A grant-held ladder therefore reads like a plain grant: rule 12 of `plans.Offer` offers nothing below it and rule 13 sells Checkout above it (`internal/plans/offer.go:160-229`, route at `:277-291`). Checkout asks the same decision (`checkoutOffer`, `internal/server/billing.go:263-291`, refusing at `:81-86`). The current card draws a price line and Cancel plan only when `resolveCurrentPlanBilling` finds a subscription behind the held position (`internal/server/member_plans.go:443-470`, `:759-787`), whose comment says a grant-held tier "genuinely" has no billing (`:750-758`). The paid tier's own card is an ordinary lower or higher tier. Pay invoice on a card goes to `GET /billing/plans/{ladderID}/unpaid-invoice` (`GetPlanUnpaidInvoice`, `internal/server/member_hosted_invoice.go:177-197`), which reads the position and answers 404 for one no subscription backs (`planPosition`, `:206-245`), then the subscription's `latest_invoice` (`unpaidInvoicePage`, `:247`).
|
||||
|
||||
**The acts that end a holder.** `RevokeGrantTx` (`internal/entitlements/grant_acts.go:242-321`) and `ExpireGrantTx` (`:339-400`) lock the pool, end the grant's conferral, resume the marked grants it replaced when they ended something (`:298-303`, `:382-387`), restore the floor (`ReapplyDefaultsIfVacant`, `internal/entitlements/reapply_defaults.go:97-114`; `:309-314`, `:388-393`) and materialize. `reconcileEnded` (`reconcile.go:213-278`) does the same for an ending subscription, and `endSurplusConferrals` (`:979-1009`) ends a provision whose item left the subscription, with no floor. None of them confers the subscription the holder displaced; it delivers at its next reconcile, which for a subscription nobody edits is the renewal's `customer.subscription.updated` (`internal/integrations/stripe/workflows/webhook_subscription.go:72-104`). `ResumeReplacedGrantsTx` (`internal/entitlements/grant_resumption.go:85-140`) confers each resumable grant under its own savepoint (`resumeInSavepoint`, `:146-171`), the pattern a second delivery step follows.
|
||||
|
||||
**No trigger after an act.** No grant act writes an outbox entry or starts a reconcile. The issue handler's only after-commit step starts the expiry workflow (`internal/server/operator_enrollment.go:861-876`). The hourly billing sweep (`internal/workflows/billing/sweep_workflow.go:16-29`, `activities.go:41-47`) fires due scheduled changes and reconciles only their subscriptions.
|
||||
|
||||
**The outbox.** `integration.Enqueue` (`internal/integration/outbox.go:42-54`) inserts a `core.outbox` row in the caller's transaction and is the only supported write path. `PollIntegrationOutbox` (`internal/integrations/stripe/workflows/outbox.go:69-114`) hands each pending row to its own workflow, which retries the activity from one second to ten minutes for a day (`:63-67`, `:121-130`), stops at once on a Stripe 4xx other than 409 and 429 (`classifyStripeError`, `:292-302`), and dead-letters a spent budget (`MarkOutboxDeadLetter`, `:277-286`), which the Stripe provider page lists. `executeAction` (`:317-331`) knows three action types and completes any other without acting (`:325-329`).
|
||||
|
||||
**The subscription row.** `core.subscriptions` mirrors the status, the period, `cancel_at_period_end`, `canceled_at` and `ended_at` (`UpdateSubscriptionStatus`, `internal/billing/queries/subscriptions.sql:15-24`, written by `upsertSubscription`, `reconcile.go:335-412`). Nothing mirrors `pause_collection`, though every reconcile reads it with the subscription (`fetchSubscription`, `:163-172`).
|
||||
|
||||
**The operator's side.** The Not delivering badge's title is built by `displacementTitle` (`operator_enrollment.go:516-558`) for the subscriptions `subscriptionMayBeDisplaced` admits (`active`, `trialing`, `past_due`, `unpaid`; `:463-469`); its holder phrase is `displacementHolder` (`:561-572`). The card reads it through `fillDisplacement` and `displacementTitleFor` (`:1746-1762`, `:1861-1874`), the list through `subscriptionTitlesFor`. The grant form's warning is `issueGrantSupersedeWarning` (`internal/server/operator_enrollment_forms.go:130-134`). The Overview's Monthly recurring headline sums every `active` subscription's current items (`SumMonthlyRecurringByCurrency`, `subscriptions.sql:106-126`; `operator_overview.go:159-186`), leaving trialing ones to the caption (`recurringCaption`, `:224-238`).
|
||||
|
||||
**Stripe, as checked.** A Stripe sandbox run on test clocks at the console's pinned version, `2025-02-24.acacia`, with the console's restricted test key for the pause calls, established:
|
||||
|
||||
- A pause with `behavior=void` leaves `active` as `active` and the period advancing. Each renewal made while paused is a draft for about an hour (`next_payment_attempt` is the creation plus one hour) and is finalized and voided in the same instant at that hour; no charge is attempted. `invoice.finalized` (carrying `status=void`) and `invoice.voided` are sent.
|
||||
- `pause_collection=` (stripe-go: `AddExtra("pause_collection", "")`) and `metadata[member_console_collection]=` clear the pause and delete only that metadata key; no invoice and no proration follow, and the next renewal is charged in full.
|
||||
- A pause set inside a renewal's draft hour voids that renewal; a clear inside a paused renewal's draft hour lets it be charged in full. The deciding instant at both edges is the draft's finalization, about one hour after the renewal.
|
||||
- Stripe accepts the pause on a subscription a schedule manages. The pause and the marker survive a phase transition and a release, and the phase's renewal is voided.
|
||||
- The pause and `cancel_at_period_end=true` coexist; the subscription cancels at the period end with no final invoice.
|
||||
- An invoice already open when the pause is set keeps being retried on the account's schedule; the subscription stays `past_due`; renewals made while paused are voided; when the retries run out, the account's dunning setting cancels the paused subscription.
|
||||
- A pause during a trial voids the trial-end invoice; `trialing` becomes `active` with the pause kept.
|
||||
- Each pause or clear call produces one `customer.subscription.updated`, with `previous_attributes.pause_collection`.
|
||||
- Stripe refuses, with 400 ("You cannot create a new invoice for a paused subscription. Unpause the subscription before attempting to create a new invoice."), an `always_invoice` price change on a paused subscription; nothing changes. The same change in one update that also clears the pause and removes the marker succeeds: its proration invoice is created after the clear and paid at once, and it credits the old price's unused time although that period's renewal was voided. Two calls, the clear and then the change, give the same invoice.
|
||||
- A subscription paused through its upcoming-renewal reminder date and cleared three days before the renewal receives no `invoice.upcoming` and is charged in full at the renewal.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- While a grant holds a ladder against a subscription, Stripe charges the subscription nothing for that time, and the pause is applied and lifted without anyone's act, durably and visibly.
|
||||
- When the grant ends, the subscription's tier is delivered again in the same transaction and its collection resumes.
|
||||
- The member sees the paused plan, can cancel it at the period end, and can switch it to the granted tier or a higher one, which ends the grant's hold; when the grant ranks below the paid tier, the member can resume the paid tier at its own price, which also ends the grant's hold.
|
||||
- No ladder carries two subscriptions through the console.
|
||||
- The operator sees whether the pause is confirmed, and the grant form says what the grant does to the subscription's billing.
|
||||
|
||||
**Non-Goals:**
|
||||
- Money at the grant's edges (#280), a tier chosen for the grant's end (#279), a multi-ladder subscription's other ladders (#271) (proposal, Out of scope).
|
||||
- Voiding or forgiving an invoice from before the grant (D6).
|
||||
- A Stripe call made by any path but the outbox's reconcile and the member's own moves (D1).
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1. Where the pause is decided, and who calls Stripe
|
||||
|
||||
Options:
|
||||
- (a) The subscription reconcile decides, under the pool row, from a pure rule; a reconcile run by the outbox makes the Stripe call after its commit and returns a failure to Temporal; every other reconcile that finds Stripe disagreeing with the rule writes the outbox entry instead of calling.
|
||||
- (b) The reconcile calls Stripe after its commit for every caller and logs a failure, as `releaseSpentSchedule` (`reconcile.go:1214-1227`) does.
|
||||
- (c) Each act calls Stripe after its own commit.
|
||||
- (d) `resumes_at` alone, with no resume call.
|
||||
- (e) A database trigger, or the desired-state outbox.
|
||||
|
||||
Pick: (a).
|
||||
|
||||
Reason: the reconcile holds the strongest view: the live subscription it just read, the pool row, and the displacement rule's inputs read under it. Every Stripe call then has the outbox's retries, its dead letter and its page. A member's move calls `ReconcileSubscription` after its own Stripe call (`plan_change.go:369`, `:454`, `:512`, `:661`, `:681`) and never makes the pause call, so a pause failure never reports a successful cancellation or switch as failed. The decision is a set-to-state, so two runs that cross converge: the late call's `customer.subscription.updated` runs a reconcile that sees the disagreement and writes another entry.
|
||||
- (b) leaves a failure waiting for the next event, which for an edited-nowhere subscription is the renewal the pause had to void.
|
||||
- (c) loses the call on a crash between the commit and the call, restates the rule at each site, and sends commands that two quick acts can deliver in the wrong order.
|
||||
- (d) cannot follow an extension, a revocation before the date, an open-ended grant or a holder that changes without the grant ending (D2).
|
||||
- (e) `internal/integration/outbox.go:20-23` forbids a direct insert, and the desired-state outbox is for providers with connections, which Stripe has none of.
|
||||
|
||||
Shape:
|
||||
- `reconcile(ctx, db, logger, keyMode, stripeSubscriptionID, reason, applyCollection bool) (called bool, err error)` is `ReconcileSubscription`'s body; `ReconcileSubscription` calls it with `false` and drops the flag.
|
||||
- `ApplySubscriptionCollection(ctx, db, logger, keyMode, coreSubscriptionID, reason) error` is the outbox executor's entry: it reads the subscription's Stripe mapping (none, or no Stripe id: log L3 and return nil) and calls `reconcile` with `true`; when that run made a call (`called`), it runs `reconcile` with `true` once more, so the decision is made again from a fetch taken after its own call, at most twice in all. Every error it returns names the Stripe subscription id, because the Stripe provider page's dead-letter table shows the action type and the error alone. An unreachable mapping is skipped by `skipUnreachableSubscription` (`reconcile.go:146-156`) as today.
|
||||
- In the active and suspended branches the transaction computes the wanted state (D2) and the action (D2's table). With `applyCollection`, a non-empty action is made after the commit (`applyCollectionAction`), its error returned, so Temporal retries the whole reconcile, which re-reads Stripe and decides again. Without it, a non-empty action writes one `reconcile_subscription` entry for the subscription in the reconcile's transaction (`entitlements.RequestSubscriptionReconcile`).
|
||||
- The action type is `reconcile_subscription`, provider `stripe`, payload `{"subscription_id": "<core id>"}`. `executeAction` gains the case, calling `fulfillment.ApplySubscriptionCollection` with `sdkKeyMode()` (as `webhook_subscription.go:58`, `:96` do) and the reason `outbox:reconcile_subscription:<entry id>`.
|
||||
- The call needs no idempotency key of its own: stripe-go adds one per request and reuses it across its own retries, and the call sets a state, so repeating it is harmless.
|
||||
- Latency: up to the relay's 15-second poll plus the reconcile.
|
||||
|
||||
### D2. The pause rule, the marker, and whose pause the console changes
|
||||
|
||||
The rule, decided with the maintainer: a subscription's collection is paused when its status is `active`, `trialing`, `past_due` or `unpaid`, at least one of its current items confers a product (a product with an entitlement set, as `mirrorItems` counts it, `reconcile.go:532-537`), every conferring product is left alone by `DisplacedProducts` (D8's rule included), and every displacement that leaves one alone has `holder_source = 'grant'`. A subscription partly displaced, or displaced by another subscription, keeps billing; after this change only an edit in the Stripe Dashboard reaches either. An item with no entitlement set rides the pause: a Dashboard-made subscription with a set-less item (a donation or support line) beside a displaced tier stops billing for that item too, because the rule counts only conferring products (decided with the maintainer, question 10; the console never sells that shape, and `docs/stripe.md` states it, task 4.6).
|
||||
|
||||
`entitlements.CollectionPauseWanted(status string, desired []string, left map[string]Displacement) bool` states it and reads no row. The reconcile's active branch passes `sortedProducts(desired)` and the `left` map `convergeConferrals` already computed; the suspended branch computes both (D6).
|
||||
|
||||
The Stripe state, read from the subscription the reconcile fetched:
|
||||
- **The console's pause**: `pause_collection` set and `metadata[member_console_collection] = "paused_for_grant"`.
|
||||
- **A foreign pause**: `pause_collection` set without the marker (a pause made in the Dashboard).
|
||||
- **A stale marker**: the marker with no `pause_collection` (collection resumed in the Dashboard).
|
||||
|
||||
| Wanted | Stripe state | Action |
|
||||
|---|---|---|
|
||||
| paused | none | set: `pause_collection[behavior]=void` and the marker, one update |
|
||||
| paused | the console's, `behavior=void` | none |
|
||||
| paused | the console's, another behavior | set (the marker makes the pause the console's) |
|
||||
| paused | stale marker | set |
|
||||
| paused | foreign | none; log L1 once per reconcile |
|
||||
| not paused | the console's, or a stale marker | clear: `pause_collection=` and `metadata[member_console_collection]=`, one update |
|
||||
| not paused | none, or foreign | none |
|
||||
|
||||
`decideCollection(wanted bool, sub *stripe.Subscription) (collectionAction, foreign bool)` is the table, reading no row.
|
||||
|
||||
Reasons:
|
||||
- `void`: an invoice made while the grant holds is for a period the grant covers, so it must never be payable. `mark_uncollectible` leaves it payable and reads as bad debt; `keep_as_draft` leaves it to be collected later.
|
||||
- No `resumes_at`: an extension is a new grant row with its own `valid_until` (`grant_acts.go:164-177`), an open-ended grant has none, the expiry runs on a timer that can be late, and the holder can change without the grant ending. A missed rewrite would charge for a plan the grant still replaces. Without it, a missed clear gives the member the tier free until the next reconcile or the drift sweep (D5), a cost that falls on the operator.
|
||||
- The marker: the console's precedent for schedules is to release only one carrying its own metadata (`findSpentSchedule`, `reconcile.go:1179-1204`). An operator's deliberate pause in the Dashboard stays as the operator left it.
|
||||
|
||||
### D3. The pause is mirrored on the subscription row
|
||||
|
||||
Options: three columns on `core.subscriptions` written by every reconcile; or no mirror, the pages saying "paused" whenever the rule says so.
|
||||
|
||||
Pick: the columns, migration `00036_subscription_collection_pause.sql`:
|
||||
- `pause_collection_behavior TEXT NULL`, with no check: `core.subscriptions.status` mirrors Stripe's enum with no check (`00001_init.sql`), and a behavior value a later API version adds must not stop every reconcile of the subscription;
|
||||
- `pause_collection_resumes_at TIMESTAMPTZ NULL`;
|
||||
- `pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE`, true when the subscription's metadata carries the console's marker.
|
||||
|
||||
A new query, `UpdateSubscriptionCollection(subscription_id, behavior, resumes_at, marked)`, writes the three columns, and `upsertSubscription` calls it with the values of the fetched subscription on both branches, after `CreateSubscription` or `UpdateSubscriptionStatus`, which stay as they are. No status writer can then clear the mirror: the test kit's `Suspend`, `CancelAtPeriodEnd` and `EndSubscription` and the demo seed call `UpdateSubscriptionStatus`, and with the three values in it they would reset a pause recorded before them.
|
||||
|
||||
Reason: the badge, the paid card and the Overview must say what Stripe confirmed. Between an act and Stripe's echo, and after a failed call, the rule and Stripe differ, and only the mirror tells them apart. The third column is beyond the two the research named: the drift sweep reads the database only (D5), and without the marker it would read a foreign pause as a disagreement and ask for a reconcile every hour. The columns hold no personal data, so the reader role reads them (`scripts/db-reader-role.sql`; `internal/migrate/testdata/console-reader-columns.txt` gains three `read` lines).
|
||||
|
||||
### D4. Which acts ask for a reconcile, and for which subscriptions
|
||||
|
||||
Options for the subscriptions: every live subscription of the organization; or only those whose displacement the act changed, read before and after. For the acts: every act that can change who holds a ladder; or the grant acts alone, the sweep covering the rest.
|
||||
|
||||
Pick: every live subscription (`active`, `trialing`, `past_due`, `unpaid`) of the pool's organization, written by each act that can change a holder, in the act's own transaction, through `entitlements.RequestPoolSubscriptionReconciles(ctx, tx, poolID, exceptSubscriptionID string) error` over one new query, `ListLiveSubscriptionsOfPool` (the pool's organization, its accounts, their live subscriptions, ordered by subscription id).
|
||||
|
||||
Reason: an organization has a handful of subscriptions at most, the reconcile is repeat-safe, and a second statement of "which subscriptions this act affected" would restate the displacement rule. The cost is one Stripe read per subscription per act. The acts:
|
||||
|
||||
| Act | Where the request is written |
|
||||
|---|---|
|
||||
| Issue grant | `entitlements.IssueGrant(ctx, db, in ConferGrantInput)`: `ConferGrantTx` and the request in one `BeginMaterializing` transaction; the handler (`operator_enrollment.go:828`) calls it in place of `ConferGrant` |
|
||||
| Manage (an extension) | `ManageGrantTx` (`grant_acts.go:567`), after its act |
|
||||
| Revocation | `RevokeGrantTx`, after the floor and the materialization |
|
||||
| Expiry | `ExpireGrantTx`, when it has a pool, after the materialization |
|
||||
| A default change's grandfathered legacy grant | `obligationEnactment.enactOutgoing` (`internal/entitlements/plan_act_move.go:174-217`), after `ConferGrantTx` (`:185`) |
|
||||
| Tier removal | `removeFromPool` (`internal/entitlements/ladder_acts.go:421-455`), per pool, after the materialization |
|
||||
| A reconcile that ended one of its own provisions | `reconcileEnded` when it ended something, and the active branch when `endSurplusConferrals` ended something, for the organization's other live subscriptions (`exceptSubscriptionID` the reconciled one) |
|
||||
| Resume plan (D20) | `entitlements.ResumeSubscription`, after its conferral, with no exception |
|
||||
|
||||
`ConferGrantTx` itself does not request: provisioning, the default floor, the demo seed and the test kit call it, and none of their conferrals can take a ladder from a subscription. The demo seed's revocation and expiry (`internal/demoseed/demoseed.go:1208`, `:1227`) do request, for Carlos's canceling subscription; the seed maps no Stripe subscription, so each entry completes with L3 and no Stripe call.
|
||||
|
||||
A reconcile's own disagreement writes one entry for its own subscription (D1). Acts left to the drift sweep, which finds each within the hour:
|
||||
- a tier reorder, a tier add or a product shape edit, because D8's exception reads ranks and can flip whether a subscription yields (F44);
|
||||
- a switch that supersedes a bundle grant, which leaves the bundle's other ladder vacant and another subscription displaced there paused until the sweep, and inherits #88's whole-bundle exception (F45);
|
||||
- a Stripe-`paused` subscription with a stale console marker: `ListLiveSubscriptionsOfPool` leaves out `paused`, which D5's sweep includes, and clearing a pause on a `paused` subscription is unverified.
|
||||
|
||||
### D5. The drift sweep
|
||||
|
||||
Options: an hourly database-only sweep that enqueues a reconcile for each subscription whose mirror disagrees with the rule; or none.
|
||||
|
||||
Pick: the sweep, `fulfillment.SweepCollectionDrift(ctx, db, logger, keyMode) (int, error)`, run as a second activity of `SweepScheduledChangesWorkflow` (`SweepCollectionDriftActivity`, after `SweepScheduledChangesActivity`, each failing on its own).
|
||||
|
||||
Reason: a dead-lettered entry is never retried, and a path that forgets to request a reconcile is otherwise invisible. It is also the deploy's backfill: within an hour of the deploy every subscription already in this state is paused.
|
||||
|
||||
Shape: it pages the live subscriptions (`active`, `trialing`, `past_due`, `unpaid` and `paused`) by id, 500 at a time (`ListLiveSubscriptionsForCollectionSweep`: id, status, the three mirror columns, keyset `subscription_id > $after`, joined to `stripe.subscription_mappings` so that a subscription with no Stripe mapping never appears). The query lives in `internal/integrations/stripe/store/queries/subscription_mappings.sql` (Go package `stripe`, which `fulfillment` imports as `internalstripe`), because billing's sqlc loads `internal/db/migrations/` and `internal/db/sqlc_schemas.sql` only, which declare no `stripe` table, while the store's sqlc loads both streams; `FillInvoiceSubscriptionLinks` (`invoice_mappings.sql:66-82`) is the precedent of a store query that joins `core.subscriptions`. For each page the sweep reads, once each, the current items (`ListCurrentSubscriptionItemsBySubscriptionIDs`), the live provisions' products (`ListLiveProvisionProductsBySubscriptionIDs`, new), the shapes (`ListConferralShapes`), the displacements (`ListSubscriptionDisplacementsBySubscriptionIDs`) and the subscriptions with a `reconcile_subscription` entry that is `pending`, `processing` or `failed`, or `dead_letter` and updated within the last day (`ListSubscriptionsWithRecentReconcileEntries`, in `internal/integration/queries`). `collectionDrift` (reading no row) applies `CollectionPauseWanted` per subscription over its recorded items: a subscription the rule wants paused whose mirror has no pause, or one the rule wants unpaused whose mirror carries the console's marker, drifts; a foreign pause never does; a Stripe-`paused` subscription is never wanted paused, so one whose mirror carries the console's marker drifts. The sweep drops a row whose mapping fails `MappingReachable` under the key, because such an entry would complete as a skip (L3, or `skipUnreachableSubscription`), change no mirror, and be asked for again every hour. Each drifting subscription without a recent entry gets one entry, in one transaction per page. L5 logs the count. A failed read logs L6 and fails the activity; the next hour runs again.
|
||||
|
||||
The sweep reads the recorded items, where the reconcile reads Stripe's; a difference costs one reconcile that decides from Stripe and changes nothing.
|
||||
|
||||
### D6. The suspended branch, and the invoice open before the grant
|
||||
|
||||
The pause is decided in the suspended branch too (`reconcileSuspended`, `reconcile.go:286-303`): a `past_due` or `unpaid` subscription a grant displaces would otherwise keep generating renewals Stripe charges on a plan the grant replaces. The branch does not mirror items, so `collectionInputs` resolves the fetched subscription's items to their products (`resolveItem`, `:544-568`, no writes; a product with no entitlement set left out), then reads the live provisions, the shapes and the displacements under the pool row it already holds. A `paused` subscription is in this branch and is never wanted paused.
|
||||
|
||||
The invoice open when the grant took the ladder, decided with the maintainer: the console voids nothing. That invoice is for a period before the grant, and the console voids only its own declined upgrade invoices (`plan_change.go:301`, `:343`). Stripe keeps retrying it, the subscription stays `past_due`, and when the retries run out the account's dunning setting can cancel the subscription during the grant; its reconcile then ends nothing, and nothing is delivered when the grant ends. The paid card says the payment is due and offers Pay invoice (D10), so a member who pays it keeps the subscription. A past-due position already delivers nothing, so the invoice covers a period the paid tier delivered nothing in; #280 would bank it if paid during the hold.
|
||||
|
||||
### D7. The act that ends a holder delivers the subscription again (#270)
|
||||
|
||||
Options:
|
||||
- (a) Revocation, expiry, `reconcileEnded` and `endSurplusConferrals` confer each displaced subscription's recorded products in their own transaction, after resumption and before the floor, under the pool row alone.
|
||||
- (b) Let the floor run and the requested reconcile confer seconds later.
|
||||
- (c) Skip the floor when a subscription will deliver, and let the reconcile confer.
|
||||
|
||||
Pick: (a), `entitlements.DeliverDisplacedSubscriptionsTx(ctx, tx, poolID, exceptSubscriptionID, reason string, endedProvisionIDs []string) ([]DeliveredProduct, error)`.
|
||||
|
||||
Reason: #270 asks for the same transaction and no Stripe event. (b) confers a default and supersedes it, writing two transitions and pushing an entitlement change to every integration, and keeps the default while Temporal is down. (c) leaves the ladder vacant for those seconds.
|
||||
|
||||
Shape:
|
||||
- Each act calls it when it ended at least one provision of the ending plan, after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, with the reason `subscription-delivery:revocation:<grant id>`, `subscription-delivery:expiration:<grant id>` or `subscription-delivery:subscription:<subscription id>`. An act that ended nothing delivers nothing, as it resumes nothing, so a replay is inert.
|
||||
- It reads, under the pool row the caller holds, the recorded products of the organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused` (`ListRecordedSubscriptionProductsOfPool`: subscription id, status, product id and the summed quantity of its current items, `core.subscription_items.ended_at IS NULL`, for products with an entitlement set, ordered by subscription id then product id), skipping the ending subscription in `reconcileEnded`.
|
||||
- Short-circuit: when the read returns no row other than the excepted subscription, the step makes no further read, including the ordering read `ListSubscriptionsSupersededByProvisions`; a subscription with no missing product makes no shape or displacement read. The step reads per live subscription, displaced or not, so every trace of an act that ended a provision gains the one read.
|
||||
- The order: first the subscriptions the ending plan superseded, then the rest, each group in subscription id order. A subscription the ending plan superseded is one whose latest episode on a ladder of the pool ended in a `core.supersession_pairs` row whose `successor_provision_id` is one of `endedProvisionIDs`; one new read, `ListSubscriptionsSupersededByProvisions(pool_id, provision_ids, subscription_ids)`, finds them among the listed subscriptions, with the latest episode taken as `core.subscription_displacements` takes it (`00034_subscription_displacements.sql:41-49`) and the pairs matched as the view pairs them (`00033_supersession_pairs.sql:27-43`). The holder of a displacement cannot order them: `core.subscription_displacements` names only a live position as holder (`h.status IN ('active', 'suspended')`, `00034:69-73`), so after `core.end_conferral` no displacement names an ended provision, and before it, the holder is whatever holds the ladder now, not the plan that superseded the subscription. Take S1 displaced by S2 and S2 displaced by a grant G: when G ends, S2 delivers first and S1 then finds S2 holding the ladder, where subscription id order alone would give the ladder to S1 and leave S2, the subscription G displaced, billing undelivered. The limit: the read matches the pair's successor against `endedProvisionIDs` alone, and an extension (Manage) supersedes its predecessor's provision with its own, so when the ending grant is an extension of the grant that displaced S2, S2's pair names the predecessor's provision and S2 falls into the id-ordered rest. When S2 has the higher id, S1 then takes the ladder and S2 stays left alone, displaced by S1, billing without delivering (F62). Two subscriptions on one ladder is a shape only the Dashboard makes (F16), so the step does not follow the grant's lineage.
|
||||
- Per subscription, in that order: its live provisions (`GetLivePoolProvisionsBySubscriptionID`); the missing products; the shapes (one `ListConferralShapes` for every product); its displacements (`ListSubscriptionDisplacements`); `DisplacedProducts` over the missing ones; `ChooseTiers` over the rest; then, under a savepoint (`subscription_delivery`), `core.confer` sourced by the subscription for each kept missing product in product id order, actor `system`; and, when the status is `past_due`, `unpaid` or `paused`, `core.sync_source_status('suspended')` for the subscription, so its tier comes back suspended. A refused conferral rolls back to the savepoint, is logged (L4), and the ending proceeds; a lock wait, a deadlock or a cancelled context fails the act, as in resumption.
|
||||
- It confers only; ending and re-bounding stay with the reconcile, which the act's request (D4) runs seconds later.
|
||||
- A grant resumed just before it holds its rungs, so `DisplacedProducts` leaves the subscription's product alone there; the floor then sees the ladder held.
|
||||
|
||||
Why it is safe without the subscription's advisory lock: since `reconcile-takes-pool-lock` every position write is under the pool row, and the subscription lock protects the subscription's own rows, which this step only reads. A reconcile that changed the status to `canceled` and waits on the pool row finds the provision the act just conferred and ends it in its ended branch; a reconcile that changed the item from P to Q finds P live and Q desired, confers Q and ends P. Both converge. The rule "no path takes a pool row and then a subscription's advisory lock" (`docs/database-locks.md`) holds.
|
||||
|
||||
The tier removal and the plan-act moves can also vacate a ladder; they leave the delivery to the reconcile they request (D4).
|
||||
|
||||
### D8. A subscription that pays at or above the grant takes the ladder
|
||||
|
||||
The switch (D12) changes the subscription's item to a tier at or above the grant, and the subscription must then deliver it, though it is displaced on that ladder.
|
||||
|
||||
Options:
|
||||
- (a) A state-derived exception in `DisplacedProducts`: a displacement does not leave a missing product alone when its holder is a grant, the product is not the displacement's `displaced_product_id`, and the product's rank on the ladder is at or above the holder's rank there.
|
||||
- (b) The switch confers the target itself, after Stripe's applied answer.
|
||||
- (c) The switch records its intent durably (Stripe metadata, or a row) for the reconcile to read.
|
||||
- (d) The switch's reconcile carries a flag that lets it confer over the grant.
|
||||
|
||||
Pick: (a).
|
||||
|
||||
Reason: Stripe has charged the proration when the switch's update applies. Under (b) and (d), a crash between that answer and the console's conferral, or any other reconcile first (the update's own `customer.subscription.updated`), leaves the new product alone and pauses the subscription again: the member paid and receives nothing. (c) adds state the console must clear and that a Dashboard edit can strand. (a) gives the same answer on every path and every replay, and the organization page and the list read the same function, so neither marks a switched subscription Not delivering. The second condition keeps #212's fix: on no reconcile does the product the grant displaced take the ladder back, whatever its rank. The member's Resume plan (D20) is the one act that takes it back, by conferring it under the pool row; once that conferral commits the subscription is no longer displaced, so the rule here never has to yield to it.
|
||||
|
||||
What (a) also decides, beyond the member's switch:
|
||||
- A downgrade scheduled before a grant ranked below it lands at renewal on a tier at or above the grant, which then takes the ladder: the member's own scheduled plan outranks the grant. The reconcile that confers it finds the rule no longer wanting a pause and writes the clear's entry, so collection resumes at the lower price. Decided with the maintainer together with question 3 (F27). A downgrade landing below the grant stays left alone (F26).
|
||||
- An edit in the Stripe Dashboard that moves the item to a tier at or above the grant takes the ladder.
|
||||
- A subscription displaced by another subscription is unaffected: the exception names grant holders only.
|
||||
|
||||
Migration `00037_displacement_holder_rank.sql` replaces `core.subscription_displacements` (`DROP FUNCTION` and `CREATE FUNCTION`, since the return type changes) with two more columns after its five: `holder_product_id UUID` (the holding episode's `product_id`, `h.product_id`) and `holder_rank INT`, that product's rank on the ladder (`LEFT JOIN core.plan_ladder_tiers t ON t.plan_ladder_id = h.plan_ladder_id AND t.product_id = h.product_id`), NULL when the product is no tier of the ladder. A NULL rank never yields. The three queries over it (`ListSubscriptionDisplacements`, `ListAccountSubscriptionDisplacements`, `ListSubscriptionDisplacementsBySubscriptionIDs`, `internal/entitlements/queries/pool_provision_transitions.sql:70-130`) name seven aliases and select the two columns in the same place, so the list's row type still converts to the account's. `Displacement` gains `HolderProductID string`, `HolderRank int32` and `HolderRanked bool`.
|
||||
|
||||
`DisplacedProducts` becomes: index the displacements by ladder as today; a missing product is left alone by the first of its rungs, in rung order, whose ladder is indexed and whose displacement does not yield to it; a displacement yields to product p on rung r when `HolderSource == "grant"`, `HolderRanked`, `p != DisplacedProductID` and `r.Rank >= HolderRank`. A bundle is left alone when any of its displaced ladders does not yield, since a conferral places the whole product.
|
||||
|
||||
### D9. The offer decision knows a subscription that pays without holding (#277)
|
||||
|
||||
Options: (a) a `Position` fact, "a live subscription pays for a tier of this ladder without holding its rung", read from the subscription's current items and their products' tiers, with its own rule; (b) the displacement rows alone.
|
||||
|
||||
Pick: (a). Reason: one fact reaches the Products page, Checkout and the switch, all of which build their position in `onLadder`. Reading the items, not the displacements, also covers a bundle's vacated ladder (#271), where the subscription still pays for a tier and holds nothing: Checkout there would start a second subscription.
|
||||
|
||||
`plans.Position` gains `Paying *Paying`:
|
||||
|
||||
```go
|
||||
// Paying is a live subscription that pays for a tier of this ladder while it
|
||||
// does not hold the ladder's rung. Nil when there is none.
|
||||
type Paying struct {
|
||||
ProductID string // the tier it pays for
|
||||
Rank int32
|
||||
GrantHolds bool // a grant holds the ladder's rung
|
||||
Suspended bool // its status is past_due, unpaid or paused
|
||||
Paused bool // its status is paused
|
||||
ConsolePaused bool // its row records a pause and the console's marker
|
||||
MoveScheduled bool // a cancellation or a downgrade is scheduled on it
|
||||
OtherLadders bool // its product is a tier of another ladder too
|
||||
}
|
||||
```
|
||||
|
||||
The read: `ListSubscriptionRungsByOrg` (billing), one statement per request, read once per request and cached on the `positionLoader` as `predictions` is cached (`positions()` is not cached): the organization's live subscriptions (`active`, `trialing`, `past_due`, `unpaid`, `paused`) with their status, period end, `cancel_at_period_end`, the mirror's `pause_collection_behavior` and `pause_collection_marked`, the first scheduled cancellation and plan switch (joined as `ListLadderPositionsByPool` joins them, `internal/entitlements/queries/pool_provision_ladders.sql:212-243`), and each current item's product, its price (id, `unit_amount`, `currency`, `recurring_interval`, so the paid card names the subscription's own price with no read of its own, D10, D20) and the product's tier rows (`core.plan_ladder_tiers`: ladder and rank), ordered by ladder, subscription id and product id. `payingByLadder(rows, positions)` (reading no row) keeps, per ladder, the first subscription that does not hold that ladder's position, and sets `Paused` from the status, `ConsolePaused` from the behavior and the marker together, `MoveScheduled` from `cancel_at_period_end` or either scheduled row, and `OtherLadders` when the product's tier rows name another ladder. `onLadder` gains the ladder's paying row and sets `pos.Paying`; `GrantHolds` is the held position's `grant_id` being set while its `pool_provision_ladders.default_sourced` is false, because a default position is a grant row with `grant_reason = 'default'` and must not read as a grant; `ListLadderPositionsByPool` carries `grant_id` and gains `default_sourced`. The choice of a ladder's paying subscription is one pure function in `entitlements` beside `PositionsByLadder`, which `payingByLadder` and the resolver (D11) both call, so the rule is stated once. Section 9 builds every field; `ConsolePaused`, `MoveScheduled` and `OtherLadders` are read by the rule from section 12 on.
|
||||
|
||||
The rule, rule 3a, ahead of rule 3 (the target is the current product), applied when `Paying` is set and no subscription backs the held position (`!pos.Subscribed`, the condition of D11's fallback), so a subscription that holds the rung over another one, as a Dashboard-made subscription can, keeps its own moves:
|
||||
1. the target is the paying product: Resume, enabled, relation `Upgrade`, when D20's conditions hold (a grant ranked below the paying product holds the rung, the subscription is not suspended, its row records the console's pause, nothing is scheduled on it, and its product is a tier of this ladder alone); otherwise none, reason `PaidHere` ("a subscription pays for the target without holding the ladder"). In the section 9 commit this item always answers none, reason `PaidHere`, and the section 12 commit adds Resume;
|
||||
2. `GrantHolds`, not `Suspended`, the target ranks at or above the current rung and above the paying product: Switch, through the price rule, relation `Upgrade` (D12). The rank test against the paying product is question 3's answer: under a grant ranked below the paid tier, the paid tier resumes (item 1) and only the tiers above it switch, so every switch stays an immediate upgrade. In the section 9 commit this item answers none, reason `PaysOnLadder`, and the section 11 commit makes it a switch, because the preview and the resolver reach a paying subscription only from section 10 and the Stripe update clears the pause only from section 11;
|
||||
3. the target is the current product: none, reason `Current`;
|
||||
4. any other target: none, reason `PaysOnLadder` ("a subscription pays on the ladder without holding it"). This includes every tier between a lower grant and the paid tier.
|
||||
|
||||
It sits ahead of rule 3 because the granted tier, the current one, is offered the switch. No answer on such a ladder is Checkout, and `plans.Across` is unchanged: rule 3a answers no Checkout on any paying ladder, so a product with such a ladder already combines to none. `switchOffer` (`plan_offer.go:337-381`) maps a refusal with `Paying` set and `Suspended` to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and then a refusal with `Paying` set and not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on. On a ladder a grant holds against a paying subscription `pos.Subscribed` is false, so without the second case every other rule 3a refusal (the paid tier, item 1, and a tier between a lower grant and the paid tier, item 4) would reach `!pos.Subscribed`, and `renderPlansAfterMove` would answer "There's no active subscription to change on this plan.", which is false there, since a subscription pays on the ladder. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence. `resumeOfferFor` (D20) maps the same way.
|
||||
|
||||
### D10. The paid plan's card
|
||||
|
||||
The card of the tier the paying subscription pays for, on a ladder a grant holds, carries the subscription's state and controls; it may be the current card when the grant is of the subscription's own tier. `buildTier` draws it even when its product is no longer a public plan, as it draws the current and the held rungs (`member_plans.go:399-412`), so Cancel plan stays reachable; such a card also offers Resume when D20's conditions hold. On a ladder no plan holds (a bundle's vacated ladder) the paid tier draws no line and no control, and the cards on the ladder a grant holds carry them (#271 decides more).
|
||||
|
||||
The card's states, read from the paying row and the mirror:
|
||||
|
||||
| State | Price line | Fact line | Controls |
|
||||
|---|---|---|---|
|
||||
| Pause confirmed (the mirror's behavior set), status `active` or `trialing`, nothing scheduled | M0 "Paused while {granted} is granted" | none | Resume plan when the decision offers it (D20), then Cancel plan |
|
||||
| Pause confirmed, status `active` or `trialing`, a cancellation scheduled | M0, with the ladder heading's existing "cancels on {date}" badge | none | Keep plan |
|
||||
| Pause confirmed, a downgrade scheduled before the grant | M8 "Paused while {granted} is granted, moves to {tier} on {date}" | none | Keep plan, then Cancel plan; Pay invoice first when the status is `past_due` or `unpaid` |
|
||||
| Pause confirmed, status `past_due` or `unpaid` | M1 "Paused while {granted} is granted, payment due" | none | Pay invoice, then Cancel plan or Keep plan |
|
||||
| Pause not confirmed (pending, failed, or not wanted), status `active` or `trialing` | the existing "{price}, renews {date}", "{price}, moves to {tier} on {date}" or "{price}, ends {date}" | none | Cancel plan; Keep plan |
|
||||
| Pause not confirmed, status `past_due` or `unpaid` | "{price}, payment due" (existing) | none | Pay invoice, then Cancel plan or Keep plan |
|
||||
| Status `paused` (Stripe's own) | "{price}, paused" (existing) | "Entitlements are suspended." (existing) | none |
|
||||
|
||||
{granted} is the product name of the position the grant holds on the card's ladder; {price} is the subscription's own price, from the paying row (D9). M8 wins over M1 when both apply, as the existing current card keeps "moves to" over "payment due" (`member_plans.html:64-69`). The confirmed lines read the mirror, not the rule, as the operator's title does (D16): "Paused" while Stripe still charges would be false, and the card must match the badge (O3). The mirror records a pause whoever set it, so a pause made in the Dashboard also reads as paused, and Stripe collects nothing in either case. The unconfirmed lines are existing strings (M5, reused). Keep plan is offered while a cancellation (`cancel_at_period_end`) or a downgrade is scheduled, and Cancel plan unless a cancellation is scheduled, as `setCurrent` does (`member_plans.go:455-466`); the ladder heading's existing "cancels on {date}" badge carries a scheduled cancellation's date, read from the paying row. The cancelled paused card is M0, Keep plan and that badge, with no new string (decided with the maintainer, question 6). A grant of the subscription's own tier reads M0 with the granted name, which is the paid tier's: "Paused while Plus is granted" (question 8). `TierViewModel` gains `PaidUnderGrant bool`, `GrantedName string` and `CollectionPaused bool`, and in section 12 `CanResume bool`, `ResumeTitle string` and `ResumeBody string` (D20); `PaysInvoice()` also holds for a paid card whose status is `past_due` or `unpaid`.
|
||||
|
||||
The cancel confirmation's body on the card is M2, "{paid} ends on {date}; {granted} stays granted.", when the grant is of another tier, and M9, "Your subscription ends on {date}; {granted} stays granted.", when the grant is of the subscription's own tier, where both tiers have one name; either is followed by the existing " The unpaid invoice stays due." when the status is `past_due` or `unpaid` (M7). {date} is the paying subscription's `current_period_end` in the card's date form.
|
||||
|
||||
Pay invoice: the card links to the existing plan route. `planPosition` (`member_hosted_invoice.go:206-245`), finding a position no subscription backs, takes the paying subscription of the ladder (`ListSubscriptionRungsByOrg` and `payingByLadder`); a paying subscription whose status is `past_due` or `unpaid` is the route's suspended case. For it, `unpaidInvoicePage` reads the subscription's open invoices from Stripe (`invoice.List` with `subscription` and `status=open`, limit 1) and answers that invoice's hosted page, because its `latest_invoice` is a renewal voided while paused. The holding case keeps reading `latest_invoice`.
|
||||
|
||||
### D11. Cancel plan and Keep plan reach the paying subscription
|
||||
|
||||
Options: (a) the resolver falls back from the position to the paying subscription, for every move; (b) a second resolver for Cancel and Keep only, the switch refusing.
|
||||
|
||||
Pick: (a), now that the switch is decided. `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`: when the ladder's position is not subscription-backed, or the pool holds no position on the ladder at all (a bundle's vacated ladder; the resolver returns at `if !ok`, `plan_change.go:792`), it finds the live subscription whose current item's product is a tier of the ladder (`ListSubscriptionRungsByOrg`, the first by subscription id), resolves that item and its mappings as today, and sets `holdsLadder = false`, `positionStatus` to `suspended` when the subscription's status is `past_due`, `unpaid` or `paused`, and `subscriptionStatus` from the subscription row. `SwitchPlan`, `KeepCurrentPlan`, `PreviewSwitch`, `CancelSubscription` and `SubscriptionBacksLadder` call it, and `ResumePlan` from section 12 (D20). Their refusals read the same two fields, so a past-due paying subscription refuses an immediate cancellation and a switch, and a `paused` one refuses every act, as for a holding subscription.
|
||||
|
||||
Cancel plan at the period end, as everywhere (decided with the maintainer): Stripe accepts `cancel_at_period_end` on the paused subscription. If the grant ends first, D7 delivers the subscription again until its period ends. The endpoint still accepts a posted immediate cancellation of an active paying subscription, which the UI never sends.
|
||||
|
||||
### D12. The switch of a paused subscription (#278)
|
||||
|
||||
Offered by D9's rule on the granted tier and every tier above it, and above the paid tier. Under a grant ranked below the paid tier, the granted tier is not above the paid tier, so only the tiers above the paid tier offer the switch, and the paid tier's own card offers Resume plan (D20). On the granted tier's card, the current card, the control renders below its features with the switch's control markup, labelled with the existing "Upgrade" (M6, decided with the maintainer, question 2).
|
||||
|
||||
The Stripe update: `upgradeNow` (`plan_change.go:286-370`) gains `clearPause bool`, true when the subscription it reads first (`:292`) carries the console's pause or a stale marker, whatever holds the ladder. A subscription that holds its ladder is delivering, so clearing the pause there is correct; it stays paused at Stripe for about 15 seconds after an ending act, and for a day or more after a dead-lettered clear, and Stripe refuses its `always_invoice` update. The update then also sends `pause_collection=` (`AddExtra`) and `metadata[member_console_collection]=` (`AddMetadata`), with the existing `items`, `proration_behavior=always_invoice`, `proration_date` and `payment_behavior=pending_if_incomplete`. A foreign pause is not cleared; Stripe then refuses the update with 400, and the member reads the generic failure.
|
||||
|
||||
Whether Stripe accepts `pause_collection` and `metadata` beside `payment_behavior=pending_if_incomplete` is unverified; the sandbox showed the one-update form without it. Item 11.1 checks it before the code. If Stripe refuses the combination, item 11.1 also tries `payment_behavior=error_if_incomplete`, which keeps one atomic update and loses the approval path for a payment that needs authentication, so a member whose card needs authentication could not switch from the paused plan at all. The other fallback is two calls, the clear alone and then the existing upgrade unchanged, which the sandbox showed gives the same invoice and which departs from "one Stripe update". Each fallback changes what a member can do, so if item 11.1(a) is refused, both fallbacks, `error_if_incomplete` and the two-call form, go to the maintainer before item 11.2, not only to the commit message. In the two-call form, a decline or a payment awaiting approval leaves the subscription unpaused while the grant holds. No reconcile follows `ErrUpgradeDeclined` (`plan_change.go:348`), so a declined or approval-pending upgrade calls `ReconcileSubscription` itself, which requests the pause again (D1); collection is paused again within seconds, and a renewal finalized in that window is charged.
|
||||
|
||||
After the update applies, `upgradeNow` reconciles as today: the item now names the target, D8's exception lets it be conferred, `core.confer` supersedes the grant's position (an upgrade, or a transfer at the granted tier), and the pause is already cleared, so the decision finds agreement. The grant is replaced: `core.grant_replacements` pairs it with the subscription, so a grant marked to resume delivers again when the subscription ends, while its own term lasts, and an unmarked one delivers no more.
|
||||
|
||||
Money: Stripe's proration of the update. It credits the old price's unused time although that period's renewal was voided, so the member pays the price difference for the rest of the period, not the new price. D14's fifth cost, accepted with the maintainer until #280 (question 9).
|
||||
|
||||
The preview (`PreviewSwitch`, `:582-596`) previews the paused subscription with `always_invoice`, and the switch sends that preview's `proration_date` back. Whether Stripe answers it for a paused subscription, and whether its `amount_due` equals the total of the one-update switch's proration invoice on the same clock (200 in the sandbox), are unverified; item 11.1(c) records both, and its result fixes the preview's form at build time, because nothing at run time can compare a preview with an update that has not happened. If Stripe refuses the preview or its figure differs from the update's, `PreviewSwitch` returns the unavailable preview for a subscription carrying the console's pause, read from the resolved row's mirror (`ls.sub.PauseCollectionBehavior` set and `ls.sub.PauseCollectionMarked`, which `GetSubscriptionByID` carries from section 2) because `PreviewSwitch` fetches no subscription; the confirmation states that preview with the existing fallback sentence, so the member never reads a charge the update does not make. If the figures are equal, `PreviewSwitch` returns Stripe's figure, and a refusal by Stripe at run time still gives the unavailable preview. The confirmation's message gains one sentence: `planMoveMessage` takes `replacesGrant bool`, and with it the second paragraph opens "Your subscription replaces the grant." before the charge sentence.
|
||||
|
||||
### D13. Every Stripe write on a subscription the console may have paused
|
||||
|
||||
Stripe refuses an `always_invoice` update on a paused subscription unless the update clears the pause. Each write the console makes on a subscription, against a subscription paused by the console:
|
||||
|
||||
| Write | Reachable on a paused subscription | What Stripe does | What the console does |
|
||||
|---|---|---|---|
|
||||
| The pause and the clear (D2) | yes | checked: accepted, one echo each | D1 |
|
||||
| Resume plan (D20) | yes | none of its own: the outbox's clear (D2) follows its commit; the clear changes no item, so Stripe makes no invoice and no proration | D20 |
|
||||
| The paused switch's update (D12) | yes | checked without `pending_if_incomplete`; with it, unverified (item 11.1) | clears in the same update |
|
||||
| An ordinary upgrade (`upgradeNow`, `always_invoice`) | yes, for a subscription that holds its ladder while Stripe still carries the console's pause: between the ending act and the outbox's clear, and after a dead-lettered clear | refused with 400 unless the same update clears the pause (S13) | clears in the same update (D12's `clearPause` is read from the fetched subscription); a foreign pause on a holding subscription refuses its upgrade; generic failure, as today |
|
||||
| Void of an abandoned upgrade's invoice | only from D12's path, before the update | an invoice void, not a subscription update | unchanged |
|
||||
| Downgrade schedule create, update, release (`downgradeAtRenewal`) | yes, for a subscription that holds its ladder while Stripe still carries the pause (between the ending act and the clear, and after a dead-lettered clear); D9 offers no move below the paid tier from a subscription that pays without holding | checked: accepted, and a schedule's phases and release keep the pause | unchanged |
|
||||
| `cancel_at_period_end=false` before a downgrade | yes, in the same window | creates no invoice; unverified | unchanged |
|
||||
| Cancel plan: release, then `cancel_at_period_end=true` | yes | checked: both keep the pause | D11 |
|
||||
| Keep plan: release, `cancel_at_period_end=false` | yes | the release is checked; the flag's clear creates no invoice and is unverified | D11 |
|
||||
| Immediate cancellation (`subscription.Cancel`, no invoice, no proration) | posted only; the UI never sends it | unverified on a paused subscription | as for its status (D11) |
|
||||
| The sweeper's period-end cancellation (`fireCancellation`, `sweep.go:162-178`) | yes: a member's period-end `cancellation` row fires when the hourly sweep reaches it before the deleted webhook closes it out, on a paused subscription too | Stripe has already canceled the subscription at the period end, so the call is refused | the refusal is logged; unchanged |
|
||||
| The sweeper's term-boundary switch (`create_prorations`, `sweep.go:208`) | no: it needs a commitment no console path writes | makes invoice items, not an invoice; its behaviour on a paused subscription is unverified | unchanged |
|
||||
| The release of a spent schedule after a reconcile | yes | checked: a release keeps the pause | unchanged |
|
||||
| Quantity changes | the console makes none | | unchanged |
|
||||
| Operator actions | no operator route writes a Stripe subscription; the billing views only read | | unchanged |
|
||||
|
||||
### D14. Money at the grant's two edges
|
||||
|
||||
Decided with the maintainer, for this change: none moves. The renewal paid before the grant is not credited; each renewal made while the grant holds is voided at its finalization; the rest of the period in which the grant ends is not charged. That is exact for a grant of whole periods and wrong by up to one period either way otherwise, depending on where the renewal date falls. The costs, each accepted by name with the maintainer until #280:
|
||||
- the renewal date decides which way a grant that is not whole periods falls;
|
||||
- the deciding instant is a renewal's finalization, about an hour after the renewal: a pause landing after it lets that renewal be charged, a clear landing before it lets a renewal made while paused be charged;
|
||||
- a pause or clear call that lands late, past that instant, moves a whole period one way or the other, and a void cannot be undone;
|
||||
- the first charge after a grant comes without Stripe's upcoming-renewal reminder when the clear lands inside the account's reminder window;
|
||||
- the switch's proration credits the old price's unused time for a period whose renewal was voided, so the member pays the price difference, not the new price, for the rest of that period (D12; question 9).
|
||||
|
||||
Resume plan (D20) meets the end edge's cost at a moment the member picks: the rest of the period whose renewal was voided is free, up to one whole period, nearly a year on an annual price. This is accepted until #280, as for the grant's end. Nothing is charged at the resume, the time between the grant's start and the resume is not credited, as at the grant's end, and its clear meets the second and third costs like any clear.
|
||||
|
||||
`docs/stripe.md`, in "Plan changes", states these in the bullet **A grant over a paid plan.** (task 4.6; the switch's cost is added with the switch, task 11.5, and Resume's with Resume, task 12.9).
|
||||
|
||||
### D15. Subscription schedules
|
||||
|
||||
Stripe accepts the pause on a subscription a schedule manages, and keeps it through the phase transition and the release, so a downgrade scheduled before the grant needs no special handling: its phase's renewal is voided while the grant holds. The maintainer's fallback for a refusal (keep billing until the scheduled move lands, never release the member's schedule) stays as the documented behaviour if Stripe ever refuses: the outbox entry then dead-letters, the title reads "Billing continues while a grant holds {ladder}.", and the sweep asks again each day.
|
||||
|
||||
### D16. The operator's words
|
||||
|
||||
`displacedSubscription` gains `Paused bool`, set when the subscription's mirror has a pause and every holder of its displaced ladders is a grant; `subscriptionRef` gains the mirror's behavior. `displacementTitle(subscriptions int, displaced []displacedSubscription)`:
|
||||
- one subscription on the account (and every list row): "Billing paused while {grant holder} {ladders}." when paused, otherwise the existing "Billing continues while {holder} {ladders}.";
|
||||
- n subscriptions, of which p displaced are paused and m are not: p = 0 gives the existing "Billing continues on {m} of {n} subscriptions while {holder} {ladders}."; m = 0 gives "Billing paused on {p} of {n} subscriptions while {grant holder} {ladders}."; both gives the paused sentence over the paused subscriptions' ladders, a space, and "Billing continues on {m} while {holder} {ladders}." over the others' ladders and holders.
|
||||
|
||||
{grant holder} is "a grant holds" when one grant provision holds every ladder its sentence names, and "grants hold" when several do (decided with the maintainer, question 5), counted by provision as `displacementHolder` counts them for {holder}; a paused sentence never names another kind of holder, since every holder of a paused subscription is a grant.
|
||||
|
||||
A pause not yet confirmed or failed reads the existing continues title, which is true, and its entry shows on the Stripe provider page as retrying and then as a dead letter. `subscriptionMayBeDisplaced` is unchanged: a `paused` subscription still shows no badge. The list's `ListSubscriptionsPage` gains `s.pause_collection_behavior`.
|
||||
|
||||
The grant form's warning, `issueGrantSupersedeWarning`, reads "Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends." It is true of a past-due subscription's future renewals, and of a `paused` one, which Stripe does not invoice.
|
||||
|
||||
The Overview: `SumMonthlyRecurringByCurrency` gains `AND s.pause_collection_behavior IS NULL`. The caption is unchanged: a subscription whose collection is paused keeps its `active` status and is counted as active.
|
||||
|
||||
The Tier changes list reads the delivery's three reasons through `humanizeTransitionReason` (`internal/server/operator_tier_changes.go:22-58`), for actor `system` only, as a resumption's are (Copy, T1 to T3).
|
||||
|
||||
### D17. The displacement rule moves into `internal/entitlements`
|
||||
|
||||
Options: move `Rung`, `RungsByProduct`, `Displacement`, `displacementsFromRows`, `DisplacedProducts`, `chooseTiers` (exported as `ChooseTiers`), `outrank`, `candidate` and `shared` from `internal/fulfillment/reconcile.go:670-933` to `internal/entitlements/displacement.go`; or keep them and put the delivery step in `fulfillment`.
|
||||
|
||||
Pick: move. The delivery step writes positions inside `RevokeGrantTx` and `ExpireGrantTx`, before their floor, so it lives in `entitlements`, the package that owns the position tables (`docs/go-conventions.md`, "Where a rule and an act live"); `fulfillment` imports `entitlements`, so `entitlements` cannot call the rule where it is. The move is its own commit with no behaviour change; `TestDisplacedProducts` and `TestChooseTiers` move with the functions.
|
||||
|
||||
### D18. Migration numbers, landing order, reader role
|
||||
|
||||
`00036_subscription_collection_pause.sql` and `00037_displacement_holder_rank.sql`, the next numbers after `00035_tier_products_keep_a_set.sql`. No change in flight claims them. After a deploy applies them, the deployment re-runs `scripts/db-reader-role.sql`.
|
||||
|
||||
### D19. Subscriptions already in this state
|
||||
|
||||
No backfill code. The drift sweep pauses every subscription already displaced by a grant within an hour of the deploy (D5), and the next ending act delivers it. Before the push that deploys, whoever lands the change runs a read-only count on each deployment, as `console_reader` (task 13.3), in the form the deployment's schema allows (the function, or its inline form on a schema that predates `00034`), and hands the result to the maintainer.
|
||||
|
||||
### D20. Resume plan when the grant ranks below the paid tier
|
||||
|
||||
Decided with the maintainer (question 3): when the grant that holds the ladder ranks below the tier the paying subscription pays for, the paid tier's card offers Resume plan, which takes the ladder back from the grant for the subscription's own tier with no price change. Tiers above the paid tier offer the switch (D12), and tiers between the grant and the paid tier offer nothing (D9, rule 3a). No reconcile can carry it as D8 carries the switch: the subscription's product is the product the grant displaced, which D8 never lets take the ladder back (#212's fix), so the member's act confers it.
|
||||
|
||||
Options for where it runs and its order against the commit:
|
||||
- (a) A console act: one transaction under the pool row confers the subscription's tier over the grant and writes the reconcile requests (D4); the outbox's reconcile then clears the pause after the commit (D1, D2). The member's request makes no Stripe call.
|
||||
- (b) Direct, Stripe first, as the switch is: the request clears the pause, then confers.
|
||||
- (c) Direct, the console first: the request confers and commits, then clears the pause itself.
|
||||
|
||||
Pick: (a).
|
||||
|
||||
Reason: the switch calls Stripe in the request because its update changes the item and charges a proration, and Stripe refuses that update on a paused subscription unless the same update clears the pause (D12). Resume changes no item and charges nothing, so the only Stripe change it needs is D2's clear, which the sandbox showed makes no invoice and no proration, and which the outbox already makes with its retries, its dead letter and the drift sweep behind it. Under (a) the conferral and the request commit together: a crash after the commit loses nothing, and the decision that clears the pause reads the conferral. Under (b), a crash or a refused conferral after Stripe's clear leaves the grant holding and the subscription unpaused; its echo pauses it again, and the member's act is lost. Under (c), a failed clear has no retry until the next event, and the member's answer would report a pause failure, which D1 keeps out of every member move.
|
||||
|
||||
**The decision.** D9's rule 3a, item 1: the target is the paying product, and the answer is Resume, enabled, relation `Upgrade`, when all of these hold; otherwise none, reason `PaidHere`:
|
||||
- `GrantHolds`, and the held rung ranks below `Paying.Rank`;
|
||||
- not `Suspended`: a past-due subscription pays its invoice first, as a switch does, and a `paused` one is changed by nobody;
|
||||
- `ConsolePaused`: the row records a pause and the console's marker. A pause not yet confirmed, a failed one or a stale marker draws no Resume, because the card does not read "Paused" then (D10) and the confirmation describes a paused plan. A pause made in the Dashboard draws none, because the console never clears it (D2), and the resumed plan would then deliver unpaid;
|
||||
- not `MoveScheduled`: with a cancellation scheduled, the resumed subscription would take the grant's place and then end at its period end; with a downgrade scheduled, the confirmation's "then {price}" would name a price the renewal does not charge, and a downgrade landing below the grant would take effect after the resume on the subscription's own rung and end an unmarked grant. The card offers Keep plan, and Resume after it;
|
||||
- not `OtherLadders`: a conferral places the whole product, so a bundle's Resume would also change its other ladders, which #271 decides;
|
||||
No price rule applies: Resume keeps the subscription's own item and price, as Keep plan names only the ladder. The member gate (`Target.Listed`) is not a condition: Keep plan skips it so that a member on a price an operator has since retired can still keep the plan (`member_plan_moves.go:244-248`), D7 delivers that same product when the grant ends, and `core.confer` refuses only a draft product for this subscription, re-conferring a retired one as continuity when the same subscription held a provision of it in the pool (`00023_grant_resumption.sql:459-492`). The decision reads no lifecycle, so the act refuses a draft product (the table below).
|
||||
|
||||
**A bundle grant.** When the grant's product is a tier of two ladders, `core.confer` supersedes the grant's whole provision, as it does for every conferral over a bundle grant (#88). The grant's other ladder then holds nothing, and the act runs no floor, so not even the default returns there. The act's own requests reconcile every live subscription of the organization (step 5), so another subscription displaced on that ladder delivers there and is unpaused within seconds: once nothing holds the ladder, `core.subscription_displacements` returns no row for it there (F60). Decided: the resume is not refused for it, because the rule is #88's, not Resume's; #271 decides more.
|
||||
|
||||
**The card.** `setPaidUnderGrant` (D10) takes the paid card's move and sets `CanResume` when it allows Resume, with `ResumeTitle` and `ResumeBody` (Copy M11, {price} the paying row's price as `recurringPhrase` words it); the generic move path never draws a Resume. The template draws Resume plan (M10) before Cancel plan, through the shared confirm modal (`#confirmActionModal`) as Cancel plan is drawn: the title M11's heading, the body M11's two sentences, the confirm label "Resume plan", the style `primary`, posting `ladder_id` to `/partials/member/plans/resume`. The modal suffices, where the switch needs a server-rendered preview, because nothing is charged now and there is no figure to fetch. `plansOfferPaidMove` counts an enabled Resume, because it restarts charges on the card on file at the renewal, so the control references the billing line when the line is shown.
|
||||
|
||||
**The route.** `POST /partials/member/plans/resume` with `ladder_id`, declared in `internal/server/action_triggers.go` with `Modal: true`, so `TestEveryMutationRouteIsDeclared` finds it. `PostResume` (`member_plan_moves.go`) asks the decision first (`resumeOfferFor`, built as `switchOfferFor` builds its position and target, asking `plans.Offer` for the paying product), so the route accepts only what the page draws. `resumeOfferFor` answers a refusal in this order: no `Paying` while a subscription backs the held position, `ErrSameTier` ("You're already on that plan."), which a second submit meets once the first has committed, since the resumed subscription then holds the rung and `payingByLadder` keeps only a subscription that does not hold; no `Paying` otherwise, `ErrNoActivePaidSubscription`; a suspended `Paying`, `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when it is paused; any other refusal, `errPlanNotOffered`, which includes a subscription that holds the rung over the paying one (rule 3a does not apply then, so the decision offers no Resume). It then calls `fulfillment.ResumePlan(ctx, db, logger, keyMode, orgID, ladderID, reason string) error` with the reason `member:resume`, and `renderPlansAfterMove` with the action `resume`, which shows no banner, as Keep plan shows none: the card itself becomes the current card.
|
||||
|
||||
**The resolver.** `ResumePlan` finds the subscription through `resolveSubscriptionOnLadder` (D11), so Resume reaches the subscription Cancel plan and Keep plan reach. Before any write it answers `ErrSameTier` when the resolver says the subscription holds the ladder, `ErrSubscriptionSuspended` or `ErrSubscriptionPaused` from the status, and `ErrPriceUnreachable` when the subscription's Stripe mapping fails `MappingReachable` under the key, because the outbox skips such a subscription (`skipUnreachableSubscription`) and the resumed plan would then deliver unpaid with no clear ever made. It then calls `entitlements.ResumeSubscription(ctx, db, ResumeSubscriptionInput{PoolID, LadderID, SubscriptionID, Reason})` and maps its refusals below.
|
||||
|
||||
**The act**, `internal/entitlements/subscription_resume.go`, in one `BeginMaterializing` transaction:
|
||||
1. `LockPools` on the pool, before any read, as the grant acts take it.
|
||||
2. Under the row: `GetSubscriptionResumeFacts` (new, entitlements queries: the subscription's status, `cancel_at_period_end`, `pause_collection_behavior`, `pause_collection_marked`, and whether a `core.subscription_scheduled_changes` row of the subscription is `scheduled`); the subscription's recorded current products (`ListRecordedSubscriptionProductsOfPool`, D7's query) that are tiers of the ladder, and the product's row for its lifecycle; its live provisions (`GetLivePoolProvisionsBySubscriptionID`); the product's shape (`ListConferralShapes`); its displacements (`ListSubscriptionDisplacements`, with D8's holder rank).
|
||||
3. The refusals below, each before any write.
|
||||
4. `Confer` sourced by the subscription for its product, at the summed quantity, actor `system`, reason `member:resume`, as `conferOrBound` confers. `core.confer` supersedes the grant's position as an upgrade, and `core.grant_replacements`, a view over the transitions, then pairs the grant with the subscription.
|
||||
5. `RequestPoolSubscriptionReconciles(ctx, tx, poolID, "")`, since the act changes who holds the ladder (D4).
|
||||
6. `MaterializePoolEntitlements(ctx, q, poolID)`, as `RevokeGrantTx` and `ConferGrantTx` call it: `BeginMaterializing` only opens the transaction and takes the rendezvous, so nothing materializes at commit, and the pool's entitlements would stay at the lower grant's while the ladder holds the paid tier.
|
||||
7. Commit.
|
||||
|
||||
| Refusal, read under the pool row | Error | The member reads (existing strings) |
|
||||
|---|---|---|
|
||||
| The subscription holds a live provision on the ladder (a second submit, or an ending act that delivered it first) | `ErrSubscriptionHoldsLadder` → `ErrSameTier` | "You're already on that plan." |
|
||||
| Status `past_due` or `unpaid` | `ErrResumeSuspended` → `ErrSubscriptionSuspended` | "Pay the unpaid invoice before changing this plan." |
|
||||
| Status `paused` | `ErrResumePaused` → `ErrSubscriptionPaused` | "A paused plan cannot be changed." |
|
||||
| Any other status but `active` and `trialing` (canceled, ended, incomplete) | `ErrResumeRefused` → `ErrResumeUnavailable` | "That plan is no longer available. Refresh the page and choose a current plan." |
|
||||
| A cancellation (`cancel_at_period_end`) or a downgrade scheduled | `ErrResumeRefused` → `ErrResumeUnavailable` | the same |
|
||||
| No console pause recorded: no behavior, or no marker | `ErrResumeRefused` → `ErrResumeUnavailable` | the same |
|
||||
| No displacement on the ladder whose holder is a grant ranked below the product (the holder a subscription, the default, a purchase, or a grant at or above the product) | `ErrResumeRefused` → `ErrResumeUnavailable` | the same |
|
||||
| The product is a tier of another ladder, or the subscription records no single product that is a tier of this one | `ErrResumeRefused` → `ErrResumeUnavailable` | the same |
|
||||
| The product is a draft | `ErrResumeRefused` → `ErrResumeUnavailable` | the same |
|
||||
|
||||
`ErrResumeRefused` is `entitlements`'s and `ErrResumeUnavailable` is `fulfillment`'s, which `ResumePlan` returns for every `ErrResumeRefused`; `renderPlansAfterMove` answers it as it answers `errPlanNotOffered`. The decision refuses every case before the act runs, so these mappings answer only a race (`TestResumePlan_MapsTheActsRefusals`). A database failure is the existing "We couldn't complete that change. Try again in a moment."
|
||||
|
||||
**Locks.** The act takes the rendezvous, then the pool row, and no subscription advisory lock, for D7's reason: every position write is under the pool row, and the subscription lock protects the subscription's own rows, which the act only reads. A reconcile of the subscription waiting on the pool row then finds the conferred provision live and its product desired, and writes nothing; one that changed the status to `canceled` ends the provision in its ended branch, as for any live provision. No path takes a pool row and then a subscription's advisory lock (`docs/database-locks.md`).
|
||||
|
||||
**What follows.** The outbox's reconcile finds the subscription holding its ladder, the rule not wanting a pause, and the console's pause at Stripe, and clears `pause_collection` and the marker in one update (D2). The next renewal is charged at the subscription's price; the rest of the period whose renewal was voided is free, accepted until #280, as for the grant's end. A grant marked to resume delivers again when the subscription ends while the grant's own term lasts (`grant-resumption`), and an unmarked one delivers no more, as after a switch (D12). The transition's reason renders raw in the Tier changes list, as the switch's `member:switch` does. Between the commit and the clear, about 15 seconds, the subscription delivers while Stripe still pauses it: a renewal finalized in that window is voided, D14's third cost, and an upgrade in it clears the pause in its own update (D13).
|
||||
|
||||
## Failure table
|
||||
|
||||
"S" is a subscription the organization pays for, "G" an operator's grant; "displaced" is the reconcile's rule with D8's exception.
|
||||
|
||||
| # | State | Today | After | Rule |
|
||||
|---|---|---|---|---|
|
||||
| F1 | G issued over S's tier | S keeps billing; nothing at Stripe | The issue writes S's entry; the outbox reconcile pauses S with the marker; the mirror reads paused at the echo | D1, D2, D4 |
|
||||
| F2 | The outbox entry fails retryably | n/a | Temporal retries the reconcile for a day; the title reads "continues"; then a dead letter, and the sweep asks again after a day | D1, D5 |
|
||||
| F3 | Stripe refuses the pause call (4xx) | n/a | Dead letter at once; the title reads "continues"; the sweep asks again after a day | D1, D5 |
|
||||
| F4 | The pause lands inside a renewal's draft hour | n/a | That renewal is voided | Stripe |
|
||||
| F5 | The pause lands after a renewal was finalized | n/a | That renewal is charged; accepted | D14 |
|
||||
| F6 | Each renewal while G holds | Charged | Draft for an hour, then voided; projected as Void, listed on Billing | D2 |
|
||||
| F7 | G revoked or expires, S displaced only by it | S delivers at its next Stripe event | The act confers S's tier before the floor; no default conferred; the outbox reconcile clears the pause | D7, D4 |
|
||||
| F8 | The clear lands inside a paused renewal's draft hour | n/a | That renewal is charged in full; correct, the tier delivers from then | Stripe |
|
||||
| F9 | The clear lands after a paused renewal's finalization | n/a | The rest of that period is free; accepted | D14 |
|
||||
| F10 | G ends, S `past_due` | S's tier back at its recovery | S's tier conferred suspended in the act; the pause cleared | D7 |
|
||||
| F11 | G ends, S's conferral refused (a product drafted since) | n/a | Rolled back to its savepoint, L4; the floor runs; the outbox reconcile fails the same way as today's reconcile would; S stays paused while the default delivers, and its reconcile fails each time, so a dead letter returns each day through the sweep; this is the accepted end state until someone repairs the product, and it shows on the Stripe provider page | D7 |
|
||||
| F12 | G ends while a marked grant G0 it replaced resumes | n/a | G0 resumes first; S stays left alone (G0 holds); S stays paused | D7 |
|
||||
| F13 | G extended (Manage) | S keeps billing | The holder is the extension; S stays paused; the request finds agreement | D4 |
|
||||
| F14 | A grant ending with nothing live (already superseded) | n/a | Ends nothing, delivers nothing, still requests | D7, D4 |
|
||||
| F15 | Issue then revoke within seconds | n/a | Two entries; each decides from the database under the lock; a crossed call is corrected by its echo (the echo's `customer.subscription.updated`, or the next renewal's within the draft hour); the second run after a successful call narrows the window | D1 |
|
||||
| F16 | S displaced by another subscription (Dashboard only) | Bills | Not paused; title "continues while another subscription holds" | D2 |
|
||||
| F17 | S partly displaced (a bundle still delivering another product) | Bills | Not paused | D2 |
|
||||
| F18 | A foreign pause on a displaced S | n/a | Left as it is, L1; the badge reads paused when every holder is a grant | D2, D16 |
|
||||
| F19 | A stale marker with no pause | n/a | Paused again while wanted; cleared otherwise | D2 |
|
||||
| F20 | Collection resumed in the Dashboard on S | n/a | Its echo reconcile pauses it again | D2 |
|
||||
| F21 | S `past_due` with an open invoice when G is issued | Bills | Paused; the open invoice is retried; dunning can cancel S during G; the card reads "payment due" with Pay invoice | D6, D10 |
|
||||
| F22 | Dunning cancels a paused S | n/a | S's ended reconcile ends nothing; G keeps the ladder; nothing to deliver when G ends | D6 |
|
||||
| F23 | S trialing when G is issued | n/a | Paused; the trial-end invoice voided; `trialing` becomes `active`, paused | D2 |
|
||||
| F24 | S `paused` (Stripe's own) under G | n/a | Never wanted paused; no badge; the card shows "{price}, paused" and no control | D2, D10 |
|
||||
| F25 | S carries a downgrade schedule when G is issued | n/a | Paused; the phase's renewal voided; the pause survives the phase and the release | D15 |
|
||||
| F26 | That downgrade lands below G's tier | Applied, not conferred | Unchanged; S stays paused | D8 |
|
||||
| F27 | That downgrade lands at or above G's tier (G below S's tier) | Applied, not conferred | Conferred over G; the pause cleared, so collection resumes at the lower price (accepted with question 3) | D8 |
|
||||
| F28 | The member cancels the paused S | Refused (no subscription) | `cancel_at_period_end` with the pause kept; ends at the period end with no invoice; G keeps the ladder | D11 |
|
||||
| F29 | G ends before S's cancellation date | n/a | S delivered again until its period end, then ends; M2 said G stays granted | D7, D11 |
|
||||
| F30 | The member keeps the cancelled paused S | n/a | The flag cleared, the pause kept | D11 |
|
||||
| F31 | The member switches the paused S to G's tier or above | Checkout sold a second subscription above G | One update: item, clear, marker; proration charged now; S takes the ladder; G replaced | D12, D8 |
|
||||
| F32 | The paused switch is declined | n/a | Nothing applied; S stays paused (one-update form) or is paused again within seconds (two-call form, where the declined upgrade calls `ReconcileSubscription` itself) | D12 |
|
||||
| F33 | The paused switch needs approval | n/a | As for an ordinary upgrade; the pending update expires after 23 hours | D12 |
|
||||
| F34 | A crash after Stripe applied the switch, before the console's reconcile | n/a | Any later reconcile confers the target over G | D8 |
|
||||
| F35 | Checkout on a ladder S pays for, any tier | Sold | Refused with 422 before Stripe | D9 |
|
||||
| F36 | A bundle's vacated ladder | Checkout sold | Refused; the paid tier shows no line; #271 unchanged | D9, D10 |
|
||||
| F37 | A switch from a past-due paying S | n/a | Refused: "Pay the unpaid invoice before changing this plan." | D9 |
|
||||
| F38 | A grant of S's own tier (a transfer) | S bills | Paused; the current card is also the paid card; tiers above it offer the switch | D10 |
|
||||
| F39 | A grant ranked below S's tier | S bills | Paused; S's card offers Resume plan; the tiers above S's tier offer the switch; the tiers between G's and S's offer nothing | D9, D20 |
|
||||
| F40 | Pay invoice on the paused card | 404 (no subscription behind the position) | The open invoice's hosted page | D10 |
|
||||
| F41 | Temporal down | n/a | Entries wait `pending`; the boot sweep and the relay pick them up; the delivery in the ending act needs no Temporal | D1, D7 |
|
||||
| F42 | The old binary after a rollback | n/a | Pending entries complete without acting; paused subscriptions stay paused (Rollback) | |
|
||||
| F43 | S holds its ladder again, Stripe still has it paused (between the ending act and the clear, or after a dead-lettered clear) | n/a | An upgrade clears the pause in the same update; a downgrade is accepted; renewals finalized meanwhile are voided (D14's late-call cost) | D12, D13 |
|
||||
| F44 | A tier reorder, a tier add or a product shape edit flips whether S yields | n/a | S keeps its state until the sweep's reconcile, within the hour | D4 |
|
||||
| F45 | A switch supersedes a bundle grant, leaving the bundle's other ladder vacant with another subscription displaced there paused | n/a | That subscription stays paused until the sweep, within the hour; the switch inherits #88's whole-bundle exception | D4, D8 |
|
||||
| F46 | The member resumes S under a lower G | n/a | One transaction under the pool row confers S's tier over G (an upgrade), pairs G with S as replaced, and writes the requests; the outbox's reconcile clears the pause with no invoice and no proration; the next renewal is charged at S's price | D20 |
|
||||
| F47 | The outbox's clear after a resume fails | n/a | Retried for a day, then a dead letter; S delivers while Stripe still pauses it, so a renewal finalized meanwhile is voided (D14's third cost, on the operator); the sweep asks again after a day (not wanted, the marker recorded) | D20, D5 |
|
||||
| F48 | A revocation or an expiry of G holds the pool row while a resume waits | n/a | The ending act delivers S (D7); the resume then finds S holding its ladder, writes nothing and answers "You're already on that plan.", the same answer a double submit gets (F50), so the member sees no difference between the two cases | D20, D7 |
|
||||
| F49 | A resume commits before a revocation or an expiry of G | n/a | The ending act ends nothing, since G was superseded, delivers nothing and still requests (F14) | D20, D7 |
|
||||
| F50 | A double submit of Resume | n/a | The second finds S holding its ladder: "You're already on that plan.", no second conferral | D20 |
|
||||
| F51 | A crash after the resume's commit | n/a | The outbox entry is in the committed transaction; the clear follows when the relay runs | D20, D1 |
|
||||
| F52 | S canceled at Stripe while the resume commits, the row not yet updated | n/a | The resume confers; S's ended reconcile, waiting on the pool row, ends that provision; a marked G resumes, an unmarked G does not, and the floor runs | D20, D7 |
|
||||
| F53 | Resume with the pause unconfirmed, failed, made in the Dashboard, or a stale marker | n/a | Not offered; a post from an older tab is refused with the unavailable-plan sentence; Cancel plan stays | D20 |
|
||||
| F54 | Resume with a cancellation or a downgrade scheduled | n/a | Not offered; refused with the unavailable-plan sentence; Keep plan first | D20 |
|
||||
| F55 | Resume of a past-due or Stripe-`paused` S | n/a | Not offered; refused with "Pay the unpaid invoice before changing this plan." or "A paused plan cannot be changed." | D20 |
|
||||
| F56 | The resume's clear lands inside a paused renewal's draft hour | n/a | That renewal is charged in full at its finalization; correct, since the tier delivers for that period, though the confirmation said nothing is charged now (D14's second cost) | D20, D14 |
|
||||
| F57 | A bundle S paused under a lower G | n/a | No Resume; #271 | D20 |
|
||||
| F58 | G marked to resume, S resumed, and S later ends within G's term | n/a | G resumes under the existing resumption rules | D20 |
|
||||
| F59 | An operator issues a grant again over a resumed S | n/a | S is displaced again and paused again (F1) | D4 |
|
||||
| F60 | The member resumes S under a bundle grant G (G's product is a tier of two ladders) | n/a | G's whole provision is superseded (#88); the act runs no floor, so the default does not return there; the act's own requests reconcile every live subscription, so another subscription displaced on that ladder delivers there and is unpaused within seconds | D4, D20 |
|
||||
| F61 | The member cancels S in one tab while a resume commits in another | n/a | The resume reads no scheduled cancellation, because `CancelSubscription` calls Stripe (`plan_change.go:671`) before its reconcile records `cancel_at_period_end` and the scheduled change; S takes the ladder from G and ends at its period end, and an unmarked G delivers no more after that; accepted, since both acts are the member's own and D20's refusal cannot see Stripe | D20 |
|
||||
| F62 | S1 displaced by S2, S2 displaced by G, G extended through Manage, and the extension ends; S2 has the higher id (two subscriptions on one ladder, a shape only the Dashboard makes) | n/a | S2's pair names the provision of the grant the extension replaced, not one the ending act ended, so the ordering read misses S2 and both go in id order: S1 takes the ladder, and S2 stays left alone, displaced by S1, billing without delivering; accepted | D7 |
|
||||
|
||||
## Locks and transactions
|
||||
|
||||
- **Subscription reconcile, active branch:** as today, the rendezvous, the subscription advisory lock, the row, the pool row, the resume, the items, the reads; the decision uses the reads already made under the pool row. A disagreement's `core.outbox` insert is in the transaction and takes no lock. When `endSurplusConferrals` ended something, `DeliverDisplacedSubscriptionsTx` (the pool row held) and `RequestPoolSubscriptionReconciles` follow, before materialization. With `applyCollection`, the Stripe call is made after the commit, with no lock held.
|
||||
- **Suspended branch:** the pool row, then the suspension, then the decision's reads (`collectionInputs`) under the row.
|
||||
- **Ended branch:** `core.end_conferral`, resumption, then, only when something ended, the delivery step under the pool row the resumption took, then `LockPools` and the floor as today, materialization, then the request for the organization's other subscriptions.
|
||||
- **Revocation and expiry:** unchanged up to the resumption; then the delivery step under the pool row the act holds, the floor, materialization, the requests. No subscription advisory lock is taken.
|
||||
- **Issue (`IssueGrant`), Manage, the legacy grant, tier removal:** each act's own order, then the requests, which are inserts.
|
||||
- **The paused switch and Cancel or Keep on a paying subscription:** no transaction of their own; Stripe, then `ReconcileSubscription`.
|
||||
- **Resume plan (`ResumeSubscription`):** the rendezvous, then the pool row, then every read the refusals need under it, the conferral, the requests (inserts) and materialization; no subscription advisory lock and no Stripe call (D20).
|
||||
- **The drift sweep:** reads with no lock, and one plain transaction per page for its inserts.
|
||||
|
||||
No path takes a pool row and then a subscription's advisory lock. `docs/database-locks.md` gains, in "Grant acts", the delivery step after resumption in Revoke and Expire, under the row they hold, and the requests; in "Subscription reconcile", the decision's reads in the suspended branch, the delivery step in the ended branch and after a surplus end, and the outbox's call after the commit; Resume plan's transaction under the pool row (task 12.9); and a sentence that an outbox request is an insert in the act's transaction and takes no lock.
|
||||
|
||||
## Copy
|
||||
|
||||
Every sentence a person reads that this change adds or reuses in a new place. The UI copy rules apply (`AGENTS.md`, "UI copy"; `openspec/specs/ui-vocabulary/spec.md`, "Copy earns its place"). Angle brackets mark values filled at run time. "Approved" rows were approved with the maintainer and are used verbatim; "reused" rows are existing strings in a new place.
|
||||
|
||||
### Member
|
||||
|
||||
| # | Where | Text | Status |
|
||||
|---|---|---|---|
|
||||
| M0 | The paid plan's card, price line, pause confirmed, status `active` or `trialing`, with nothing scheduled or a cancellation scheduled; also under a grant of the subscription's own tier | `Paused while <granted> is granted`, for example `Paused while Pro is granted`, and `Paused while Plus is granted` under a grant of Plus over a Plus subscription | approved |
|
||||
| M1 | The same, status `past_due` or `unpaid`; no "Entitlements are suspended…" line; Pay invoice then Cancel plan | `Paused while <granted> is granted, payment due` | approved |
|
||||
| M2 | Cancel plan's confirmation body on the paid plan's card, under a grant of another tier | `<paid> ends on <date>; <granted> stays granted.`, for example `Plus ends on Jan 15, 2099; Pro stays granted.` | approved |
|
||||
| M3 | The switch's confirmation from a paused subscription: the heading, then the second paragraph's first sentence, then the existing charge sentence | `Switch to <target>?`, then `Your subscription replaces the grant.` followed by `Your card is charged <amount> now for the rest of this period, then <price>.` | approved |
|
||||
| M4 | The paid card of a subscription Stripe holds as `paused` | `<price>, paused` and `Entitlements are suspended.`, both existing | approved (kept) |
|
||||
| M5 | The paid card when the pause is not confirmed | the existing `<price>, renews <date>`, `<price>, moves to <tier> on <date>`, `<price>, ends <date>`, or `<price>, payment due` | reused (question 1 settled: the mirror decides) |
|
||||
| M6 | The switch control's label on the granted tier's card | `Upgrade`, the existing label | approved |
|
||||
| M7 | M2 or M9 on a card whose payment is due | M2 or M9 followed by the existing ` The unpaid invoice stays due.`, for example `Plus ends on Jan 15, 2099; Pro stays granted. The unpaid invoice stays due.` | approved |
|
||||
| M8 | The paid plan's card, price line, pause confirmed, a downgrade scheduled before the grant | `Paused while <granted> is granted, moves to <tier> on <date>`, for example `Paused while Pro is granted, moves to Basic on Jan 15, 2099` | approved |
|
||||
| M9 | Cancel plan's confirmation body under a grant of the subscription's own tier | `Your subscription ends on <date>; <granted> stays granted.`, for example `Your subscription ends on Jan 15, 2099; Plus stays granted.` | approved |
|
||||
| M10 | The control on the paid plan's card when the grant ranks below it, and its confirmation's confirm label | `Resume plan` | approved |
|
||||
| M11 | Resume plan's confirmation: the modal's title, then its body | `Resume <paid>?`, then `Your subscription replaces the grant.` followed by the existing `Nothing is charged now; then <price>.`, for example `Resume Pro?` and `Your subscription replaces the grant. Nothing is charged now; then $30.00 a month.` | approved |
|
||||
|
||||
Reused unchanged: "Cancel plan", "Keep plan", "Pay invoice", "Your plan change has been submitted.", "Your cancellation is scheduled.", "Your card was declined; you're still on <tier>.", "Pay the unpaid invoice before changing this plan.", "A paused plan cannot be changed.", "That plan is no longer available. Refresh the page and choose a current plan.", "You're already on that plan.", "There's no active subscription to change on this plan.", "We couldn't complete that change. Try again in a moment.", the M3 fallback "Your card is charged the prorated difference now, then <price>.", and the ladder heading's cancellation badge.
|
||||
|
||||
### Operator
|
||||
|
||||
| # | Where | Text | Status |
|
||||
|---|---|---|---|
|
||||
| O0 | The Not delivering badge's title, one subscription | `Billing paused while <grant holder> <ladders>.`, for example `Billing paused while a grant holds Demo Ladder.`, and `Billing paused while grants hold Hosting and Wiki.` when two grant provisions hold the ladders | approved |
|
||||
| O1 | The card's title, several subscriptions, every displaced one paused | `Billing paused on <k> of <n> subscriptions while <grant holder> <ladders>.` | approved |
|
||||
| O2 | The same, some paused and some not | `Billing paused on <k> of <n> subscriptions while <grant holder> <ladders>. Billing continues on <m> while <holder> <ladders>.` | approved |
|
||||
| O3 | A pause not yet confirmed, or failed | the existing `Billing continues while a grant holds <ladder>.` | approved |
|
||||
| O4 | The Overview's Monthly recurring headline | leaves out a subscription whose collection is paused; no caption | approved |
|
||||
| O5 | The member's Billing page | void renewals stay, with their Void badge | approved |
|
||||
| W | Issue grant, the warning when a product is marked ⚠ | `Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends.` | approved |
|
||||
| T1 | Tier changes, a delivery after a revocation (actor `system`, reason `subscription-delivery:revocation:`) | `Subscription delivers again after a revocation` | approved |
|
||||
| T2 | The same after an expiry | `Subscription delivers again after a grant expired` | approved |
|
||||
| T3 | The same after a subscription that held the ladder ended | `Subscription delivers again after a subscription ended` | approved |
|
||||
|
||||
`<ladders>` and `<holder>` are as `displacementTitle` fills them today. `<grant holder>` is `a grant holds` when one grant provision holds every ladder its sentence names and `grants hold` when several do (question 5); a paused sentence names no other holder, since the rule pauses only under grants.
|
||||
|
||||
### Log lines
|
||||
|
||||
| # | Where, level | Text |
|
||||
|---|---|---|
|
||||
| L1 | The reconcile, a wanted pause over a foreign one (Info) | `reconcile: collection paused outside the console; left as it is`, attributes `subscription_id`, `behavior` |
|
||||
| L2 | `applyCollectionAction`, after a successful call (Info) | `reconcile: subscription collection paused for a grant` or `reconcile: subscription collection resumed`, attribute `stripe_subscription_id` |
|
||||
| L3 | `ApplySubscriptionCollection`, a subscription with no Stripe mapping (Info) | `reconcile: subscription has no Stripe mapping; nothing to apply`, attribute `subscription_id` |
|
||||
| L4 | `DeliverDisplacedSubscriptionsTx`, a refused conferral (Warn) | `subscription delivery refused; the ending proceeds without it`, attributes `subscription_id`, `product_id`, `pool_id`, `error` |
|
||||
| L5 | `SweepCollectionDrift`, after a run that asked for any (Info) | `collection sweep: subscriptions asked for a reconcile`, attribute `count` |
|
||||
| L6 | `SweepCollectionDrift`, a failed read (Error) | `collection sweep: read failed`, attribute `error` |
|
||||
|
||||
## Tests
|
||||
|
||||
Each claim is pinned by a deliberate break (`docs/testing.md`, "Prove a test with deliberate breaks"); the tasks list each break with its wanted text.
|
||||
|
||||
| Section | Tests | What they prove |
|
||||
|---|---|---|
|
||||
| 1 | `TestDisplacedProducts`, `TestChooseTiers` (moved) | The move changes nothing |
|
||||
| 2 | `TestReconcile_MirrorsTheCollectionPause`, `TestSubscriptionCollectionPauseMigrationUpDownUp`, `TestConsoleReaderColumns`, `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription` | The mirror, the migration, the reader role, O4 |
|
||||
| 3 | `TestCollectionPauseWanted`, `TestDecideCollection`, `TestReconcile_AGrantOverTheSubscriptionRequestsThePause`, `TestApplyCollection_*` (eight), `TestOutbox_ReconcileSubscriptionAction`, trace goldens | D1, D2, D6 |
|
||||
| 4 | `TestActsRequestSubscriptionReconciles` (one row per act), `TestConferGrantTxRequestsNothing`, `TestReconcileEndedRequestsTheOtherSubscriptions`, `TestSurplusEndRequestsTheOtherSubscriptions`, `TestIssueGrantHandlerRequestsAReconcile`, the demo seed's assertion | D4 |
|
||||
| 5 | `TestDisplacementTitle` (rewritten, with the several-grants rows), `TestSubscriptionTitlesFor`, `TestDisplacedOnPage`, `TestSubscriptionsListMarksAPausedSubscription`, `TestOrgEnrollmentGolden` (`grant-over-subscription-paused`), `TestOrgEnrollmentIssueGrantPanel_Stacked`, `TestOrgEnrollmentProductsSection` | D16 |
|
||||
| 6 | `TestCollectionDrift`, `TestSweepCollectionDrift_*` (five), `TestSweepScheduledChangesWorkflowRunsTheCollectionSweepAfterAFailure` | D5 |
|
||||
| 7 | `TestDeliverDisplaced_*` (including the ending holder's displaced subscription first), `TestHumanizeTransitionReason` rows, trace goldens | D7 |
|
||||
| 8 | `TestDisplacedProducts` rows, `TestSubscriptionDisplacements_TheHolderRank`, `TestDisplacementHolderRankMigrationUpDownUp`, `TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder`, `TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder` | D8 |
|
||||
| 9 | `TestOffer` rows (the switch rows land in section 11), `TestAcross` (unedited), `TestPayingByLadder`, `TestCheckoutRefusesALadderASubscriptionPaysFor`, `TestProductsPageReadsPayingOnce`, the Products page's Checkout absence | D9 |
|
||||
| 10 | `TestPaidPlanCardUnderAGrant` (rows per state), `TestMemberPlansGolden` states, `TestPlansOfferPaidMoveGate` (the paid card's Pay invoice), `TestCancelAPausedSubscription`, `TestKeepAPausedSubscription`, `TestAPastDuePayingSubscriptionIsNotCancelledImmediately`, `TestPlanUnpaidInvoiceForAPausedPlan`, `TestCancelBodyOnThePaidCard` (M2, M7, M9) | D10, D11 |
|
||||
| 11 | `TestSwitchAPausedSubscription_*` (seven), `TestPreviewSwitchOfAPausedSubscription`, `TestOffer` rows for the switch (a lower grant's included), `TestPlanMoveMessageStatesTheTiming` row, `TestPostSwitchFromAPausedSubscription` | D12 |
|
||||
| 12 | `TestOffer` rows for Resume, `TestResumeSubscription_*` (six), `TestResumePlan_*` (four), `TestPostResume`, `TestResumeConfirmation`, `TestPaidPlanCardUnderAGrant` rows, `TestMemberPlansGolden` (`paid-standard-under-granted-basic`), `TestPlansOfferPaidMoveGate` (Resume), `TestEveryMutationRouteIsDeclared` | D20 |
|
||||
|
||||
`TestOperatorPagesReadAFixedNumberOfTimes` passes unedited for the organization page and the subscriptions list: the mirror rides reads they already make. `TestProductsPageReadsPayingOnce` pins that the Products page and Checkout make one statement more per request (`ListSubscriptionRungsByOrg`), never one per ladder.
|
||||
|
||||
A break no test of its section sees is named in that section's commit with the reason; two are known at drafting. In section 9 (task 9.5), `switchOffer`'s paying refusal left to `!pos.Subscribed` is unseen, because no section-9 test posts a switch on a paying ladder; section 11's `TestPostSwitchFromAPausedSubscription` catches it (task 11.6). In section 12 (task 12.8), the supersession of a bundle grant's other ladder is unseen, because `core.confer` owns it. The handler's decision gate is caught by `TestPostResume`'s row `held by another subscription`, which only the decision refuses. Every other break has a test that reads it, among them each mirrored column and each returned column (tasks 2.6 and 8.4).
|
||||
|
||||
## What is unverified
|
||||
|
||||
- **`pause_collection` and `metadata` beside `payment_behavior=pending_if_incomplete`** (D12). Item 11.1 runs it on a test clock before the switch's code: one subscription paused with the marker, one update carrying all of D12's parameters, then a declined card on a second subscription. If Stripe refuses that update, both fallbacks, `error_if_incomplete` and the two-call form, go to the maintainer first.
|
||||
- **Stripe's invoice preview of a paused subscription** (D12). Item 11.1(c) runs it and compares its figure with the update's proration invoice; a refusal or a different figure gives the unavailable preview.
|
||||
- **`cancel_at_period_end=false`, and an immediate cancellation, on a paused subscription** (D13). Neither creates an invoice, which is what Stripe refuses on a paused subscription; item 10.1 runs the first on a test clock.
|
||||
- **`GET /v1/invoices?subscription=…&status=open` on a paused, past-due subscription** (D10). Standard listing; step 12 of the landing walk (item 13.4) opens it.
|
||||
- **Clearing `pause_collection` on a subscription whose status is `paused`** (D4, D5). The drift sweep asks for it when a Stripe-`paused` subscription's row carries the console's marker. On a refusal, the sweep's entry dead-letters every day.
|
||||
- **A dunning cancellation's events during a pause.** The sandbox saw the subscription canceled; the console's reconcile of `customer.subscription.deleted` is unchanged.
|
||||
|
||||
## Migration plan
|
||||
|
||||
- `internal/db/migrations/00036_subscription_collection_pause.sql`: the three columns, with no check (D3), a header comment in the style of `00026`. Down drops the columns.
|
||||
- `internal/db/migrations/00037_displacement_holder_rank.sql`: `DROP FUNCTION core.subscription_displacements(UUID, UUID);` and the function again with `holder_product_id` and `holder_rank` (D8), `GRANT EXECUTE ... TO core_reader, core_writer, core_owner;`. Down restores `00034`'s body and grant.
|
||||
- Queries regenerated with `make sqlc-generate`. `internal/migrate/testdata/console-reader-columns.txt` gains `read core.subscriptions.pause_collection_behavior`, `read core.subscriptions.pause_collection_marked`, `read core.subscriptions.pause_collection_resumes_at`.
|
||||
- After a deploy applies them, re-run `scripts/db-reader-role.sql`.
|
||||
|
||||
## Rollback
|
||||
|
||||
The previous binary runs against the migrated schema without a down migration:
|
||||
- sqlc expands each `SELECT *` and `RETURNING *` into the columns that existed when the code was generated, so the old binary never reads the three new columns, and its inserts leave them at NULL and false;
|
||||
- `00037` appends `holder_product_id` and `holder_rank` after the function's five columns, and PostgreSQL applies a column alias list shorter than a function's columns to the first ones, so the old queries' five-name lists still name the right columns (item 8.4 runs the old form against the new function);
|
||||
- it completes pending `reconcile_subscription` entries without acting (`outbox.go:325-329`).
|
||||
|
||||
A subscription the console paused stays paused under the old binary, which never clears it. Before rolling back, list the live subscriptions (status `active`, `trialing`, `past_due` or `unpaid`; a canceled object keeps its `pause_collection`) whose mirror carries the console's marker (`pause_collection_marked`) and either clear each one in the Dashboard or accept that each delivers unpaid until it is cleared.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **The edges are inexact** until #280 (D14), by up to a period either way, a year on an annual price.
|
||||
- **A late call moves a whole period** (D14): the outbox's latency is seconds, and a dead letter is visible on the Stripe provider page and caught by the sweep after a day.
|
||||
- **A paused, past-due subscription can be cancelled by dunning during the grant** (D6), and the member keeps nothing when the grant ends; the card says the payment is due.
|
||||
- **A grant act now costs a Stripe read per live subscription** of the organization, after its commit.
|
||||
- **The member's payment ends an operator's grant** on a switch at or above it (D8, D12), the decided reversal, when the member resumes a paid tier ranked above the grant (D20), and when a scheduled downgrade lands at or above a grant below the paid tier.
|
||||
- **The switch's proration credits time the member never paid** (D12), accepted with the maintainer until #280 (question 9).
|
||||
- **A resumed plan's free remainder** of the period whose renewal was voided, at a moment the member picks (D14), accepted until #280, as for the grant's end.
|
||||
- **A resumed plan delivers while Stripe still pauses it** for the seconds before the outbox's clear, and for a day or more after a dead-lettered one (D20, F47).
|
||||
- **The demo seed's acts write outbox entries** that complete without a Stripe call (D4).
|
||||
- **Rollback needs a hand step** for paused subscriptions (Rollback).
|
||||
|
||||
## Open questions
|
||||
|
||||
All questions are settled.
|
||||
|
||||
**Settled** (1 and 11 by the designer, 2 to 10 and 12 with the maintainer):
|
||||
|
||||
1. The paid card while the pause is pending or failed: the mirror decides, with the existing lines (M5).
|
||||
2. The switch's label on the granted tier's card: the existing "Upgrade" (M6).
|
||||
3. A grant ranked below the paid tier: the paid tier's card offers Resume plan (D20, M10, M11), the tiers above it offer the switch, the tiers between offer nothing; a downgrade scheduled before such a grant that lands at or above it takes the ladder and resumes billing at the lower price (D8, F27).
|
||||
4. Cancel plan's confirmation when payment is due: M2 or M9 followed by the existing " The unpaid invoice stays due." (M7).
|
||||
5. The paused titles under several grants: "grants hold {ladders}", and "a grant holds" for one grant (O0 to O2).
|
||||
6. The cancelled paused card: M0, Keep plan and the heading's existing "cancels on {date}" badge, no new string; a downgrade scheduled before the grant reads M8.
|
||||
7. The Tier changes labels: T1 to T3 as written.
|
||||
8. A grant of the subscription's own tier: the card reads M0 with the shared name ("Paused while Plus is granted"), and Cancel plan's confirmation reads M9.
|
||||
9. The switch's proration credit for voided time: accepted until #280, D14's fifth cost, named in `docs/stripe.md` (task 11.5).
|
||||
10. An item with no entitlement set rides the pause: stated in D2 and in `docs/stripe.md` (task 4.6).
|
||||
11. The fallbacks of the paused switch's update: if item 11.1(a) finds the one update with `pending_if_incomplete` refused, both fallbacks, `payment_behavior=error_if_incomplete` and the two-call form, go to the maintainer before item 11.2, because each changes what a member can do; no question arises unless 11.1(a) is refused.
|
||||
12. The free remainder of a resumed period: accepted until #280 and named in docs/stripe.md (option A).
|
||||
@@ -0,0 +1,76 @@
|
||||
## Why
|
||||
|
||||
An operator's grant over a tier a subscription pays for takes the ladder: `core.confer` supersedes the subscription's position, and the subscription's reconcile leaves the ladder alone while the grant holds it (`docs/models/plan-ladders-transitions.md:80`). Stripe keeps charging the subscription every period, and four things go wrong around it.
|
||||
|
||||
- **#269.** The member cannot stop paying in the console. Every plan move finds its subscription through the position the organization holds on the ladder, and that position is the grant's, so Cancel plan answers that there is no active paid subscription (`resolveLadderSubscription`, `internal/fulfillment/plan_change.go:770-850`, the refusal at `:801-804`; `CancelSubscription` at `:613-619`). The Products page shows the grant's tier with no price and no control, and nothing on the page names the subscription that bills (`internal/server/member_plans.go:443-470`, `:745-787`).
|
||||
- **#270.** When the grant ends, the subscription gets its tier back only at its next Stripe event, usually its renewal. Until then the member pays and receives the organization type's default or nothing on that ladder (`RevokeGrantTx`, `internal/entitlements/grant_acts.go:242-321`; `ExpireGrantTx`, `:339-400`; `reconcileEnded`, `internal/fulfillment/reconcile.go:213-278`).
|
||||
- **#277.** The Products page offers, and Checkout sells, every tier above the grant (rule 13 of `plans.Offer`, `internal/plans/offer.go:280`; `checkoutOffer`, `internal/server/billing.go:263-291`). A purchase starts a second subscription on the ladder while the first one keeps billing, which the billing model says cannot happen (`docs/models/payments-billing.md:65`).
|
||||
- **#278.** A member whose subscription waits behind a grant cannot make the granted tier, or a higher one, their paid plan before the grant ends.
|
||||
|
||||
The decisions are recorded on #269 and #278: while a grant holds a ladder against a subscription, the console pauses the subscription's payment collection at Stripe (`pause_collection` with `behavior=void`); when the grant ends, collection resumes and the subscription's tier is delivered again in the same act; the paid plan's card says it is paused and offers Cancel plan; the granted tier and every tier above it offer a switch of the paused subscription, which takes the ladder from the grant at once; when the grant ranks below the paid tier, the paid tier's card offers Resume plan, which takes the ladder back at the subscription's own price, and only the tiers above the paid tier offer the switch; and no tier of that ladder is sold through Checkout. This change moves no money at the grant's two edges; #280 is the exact rule, a change of its own.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **A grant's hold pauses the subscription's collection.** A pure rule says a subscription's collection is paused when its status is `active`, `trialing`, `past_due` or `unpaid`, at least one of its current items confers a product, every conferring product is left alone because another plan holds one of its ladders, and every such holder is a grant. The subscription reconcile evaluates the rule under the pool row. A reconcile run by the transactional outbox then sets or clears `pause_collection` at Stripe after its commit, with the console's marker in the subscription's metadata (`member_console_collection=paused_for_grant`) in the same update; any other reconcile that finds Stripe disagreeing with the rule writes an outbox entry instead of calling Stripe. The console never sets `resumes_at`, and never clears or replaces a pause that does not carry its marker.
|
||||
- **Every act that can change who holds a ladder asks for a reconcile.** Issuing a grant, Manage's extension, a revocation, an expiry, a default change's grandfathered legacy grant, a tier removal, a member's Resume plan, and a subscription reconcile that ended one of its own provisions each write a `reconcile_subscription` outbox entry, in their own transaction, for each live subscription of the organization. An hourly sweep enqueues the same entry for each subscription whose recorded pause disagrees with the rule, as the backstop for a missed trigger and for a dead-lettered entry.
|
||||
- **The subscription row mirrors the pause.** Migration `00036` adds the pause's behavior, its `resumes_at` and whether the console's marker is set to `core.subscriptions`; every reconcile writes them from the subscription it read. The organization page, the subscriptions list, the Products page and the Overview read the mirror, so they say what Stripe confirmed, not what the console intends.
|
||||
- **The act that ends a grant delivers the subscription again (#270).** A revocation, an expiry, the end of a subscription that held the ladder and a subscription dropping the item that held it confer each live subscription's recorded products that nothing holds off any more, after the resumption of marked grants and before the default floor, under the pool row alone, each subscription under a savepoint. A subscription whose status is `past_due`, `unpaid` or `paused` gets its tier back suspended.
|
||||
- **A subscription that pays at or above the grant takes the ladder (#278).** The reconcile's displacement rule gains one exception: a missing product is not left alone on a ladder a grant holds when the product ranks at or above the grant's tier there and is not the product the grant displaced. Migration `00037` adds the holder's product and rank to `core.subscription_displacements` for it. This reverses, for that case only, the rule that a subscription never takes a ladder back from a grant. A downgrade scheduled before a grant ranked below it that lands at or above the grant therefore takes the ladder, and collection resumes at the lower price.
|
||||
- **No Checkout on a ladder a subscription pays for (#277).** The offer decision gains the fact "a live subscription pays for a tier of this ladder without holding its rung", read from the subscription's current items and the tiers of their products. On such a ladder no tier is offered Checkout, Checkout refuses before any Stripe call, the paid tier's card carries the subscription's own controls, the granted tier and each tier above it, and above the paid tier, offer a switch, and the tiers between a lower grant and the paid tier offer nothing.
|
||||
- **The paid plan's card (#269).** While a pause is recorded, whoever set it, the card reads "Paused while Pro is granted" and offers Cancel plan, which ends the subscription at its period end with the confirmation "Plus ends on {date}; Pro stays granted.", or "Your subscription ends on {date}; Plus stays granted." under a grant of the subscription's own tier. While an invoice from before the grant is open, the card reads "Paused while Pro is granted, payment due" and offers Pay invoice before Cancel plan, whose confirmation adds the existing "The unpaid invoice stays due.". A scheduled cancellation keeps the paused line with Keep plan and the ladder's existing "cancels on {date}" badge; a downgrade scheduled before the grant reads "Paused while Pro is granted, moves to Basic on {date}". A subscription Stripe holds as `paused` keeps today's "{price}, paused" and "Entitlements are suspended.". Cancel plan, Keep plan and Pay invoice reach the subscription that pays on the ladder, whatever holds the rung. The card is drawn even when its product is no longer a public plan, as the current and held rungs are, so Cancel plan stays reachable.
|
||||
- **Resume plan under a lower grant.** When the grant ranks below the tier the subscription pays for and the console's pause is confirmed, the paid tier's card offers Resume plan. Its confirmation reads "Resume Pro?", then "Your subscription replaces the grant." and the existing "Nothing is charged now; then {price}.". One transaction under the pool row confers the subscription's tier over the grant and writes the subscription reconciles to the outbox, and the outbox's reconcile then clears the pause at Stripe; the request itself makes no Stripe call, and with no item change Stripe makes no invoice and no proration. Resume plan is not offered while the subscription is past due or paused, while a cancellation or a downgrade is scheduled, for a bundle, or over a pause made in the Dashboard; it applies no member gate, as Keep plan applies none, so a product no longer public can be resumed. A grant marked to resume returns when the subscription ends, while its own term lasts.
|
||||
- **The switch of a paused subscription (#278).** Its Stripe update changes the item, clears the pause and removes the marker in one call, because Stripe refuses an `always_invoice` update on a paused subscription unless that update also clears the pause. Its confirmation reads "Switch to Max?", then "Your subscription replaces the grant." followed by the existing charge sentence.
|
||||
- **The operator's words.** The Not delivering badge's title reads "Billing paused while a grant holds Demo Ladder." once the pause is confirmed ("grants hold" when several grants hold the ladders), with the several-subscription and mixed forms; a pause not yet confirmed, or failed, keeps "Billing continues while a grant holds {ladder}.". The grant form's warning reads "Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends." The Overview's Monthly recurring headline leaves out a subscription whose collection is paused, as it leaves out a trialing one.
|
||||
- **Money at the grant's edges.** None moves. The renewal paid before the grant is not credited, each renewal Stripe creates while the grant holds is voided at its finalization, about an hour after the renewal, and the rest of the period in which the grant ends is not charged. `docs/stripe.md` states it, with the costs this accepts until #280, among them the switch's proration credit for the voided period, and that an item with no entitlement set stops billing with the paused tier beside it. The rest of a period whose renewal was voided is free after a member's Resume plan, at a moment the member picks; that is accepted until #280, as for the grant's end.
|
||||
|
||||
## Restructuring inside this change
|
||||
|
||||
Listed so the change carries it openly (`CONTRIBUTING.md`, "How changes are made", item 1). The first two bullets are this change's own work; the third is a small fix that rides along.
|
||||
|
||||
- **Core `entitlements` enqueues a Stripe provider action.** `RequestSubscriptionReconcile` and `ReconcileSubscriptionAction` make the domain package depend on the outbox's Stripe vocabulary, which no act did before; the comment at `internal/server/operator_integrations_stripe.go:263` that says only Stripe enqueues from `operator_billing.go` is updated with it.
|
||||
- **The displacement rule moves into `internal/entitlements`.** `Rung`, `RungsByProduct`, `Displacement`, `DisplacedProducts` and `chooseTiers` move from `internal/fulfillment/reconcile.go:670-933` to `internal/entitlements`, unchanged. The ending acts that deliver a subscription again live in `entitlements`, which `fulfillment` imports, so they cannot call the rule where it is today. The organization page and the subscriptions list follow the move. No behaviour changes in that commit.
|
||||
- **Ride-along: the paid card is drawn when its product is no longer a public plan.** `buildTier` (`internal/server/member_plans.go:400-412`) skipped such a tier; it now draws the paid card as it draws the current and held rungs, so Cancel plan stays reachable. One function, no new lock or invariant. Section 10 tests it with the state `paid-retired-plus-under-granted-pro`.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Each is a forge issue, a comment at landing, or a note in the design.
|
||||
|
||||
- **#280**, the exact money rule (a grant never uses up time the member paid for). It applies to every grant that ends after it ships, so this change records nothing extra for it.
|
||||
- **#279**, choosing a tier for when the grant ends. It stays its own issue.
|
||||
- **#271**, what a grant on one ladder does to a multi-ladder subscription's other ladders. This change refuses Checkout on the vacated ladder, because the subscription still pays for a tier of it, and decides nothing else about it.
|
||||
- **The pre-grant open invoice.** The console voids nothing; Stripe keeps retrying it, and when the retries run out the account's dunning setting can cancel the paused subscription during the grant. The card says the payment is due.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `stripe-subscription-management`: added "A grant's hold pauses the subscription's collection at Stripe", "A subscription delivers again in the act that ends the plan holding its ladder", "Cancel plan and Keep plan reach a subscription that pays on a ladder without holding it", "A subscription paused for a grant is switched to the granted tier or above" and "A member resumes a plan paused under a grant ranked below it"; modified "Subscription reconcile computes a genuine diff, grouped by product" (the exception at or above a grant, the pause in place of "changes nothing at Stripe", the delivery in the ending act) and "Suspension and resume propagate via sync_source_status" (the pause in place of "SHALL NOT attempt to stop the subscription's billing").
|
||||
- `member-offer`: modified "One decision says which move a member is offered on a ladder" (the subscription that pays without holding, its rule, and Resume).
|
||||
- `stripe-subscription-creation`: added "Checkout refuses a ladder a subscription pays for without holding it".
|
||||
- `member-product-discovery`: added "A paid plan whose ladder a grant holds shows its pause on its own card".
|
||||
- `member-invoice-history`: modified "Stripe's page of an invoice is read when the member opens it" (the plan route reaches the paying subscription's open invoice).
|
||||
- `plan-enrollment-administration`: modified "Advisory warning when a grant would supersede a subscription-sourced position" (the warning's text, and the grant now pauses the subscription's collection) and "The billing card says when a subscription delivers nothing while another plan holds its ladder" (the paused titles).
|
||||
- `operator-billing-views`: modified "The subscriptions list marks a subscription that delivers nothing while another plan holds its ladder" (the paused title).
|
||||
- `grant-resumption`: modified "Only the end of a replacing plan resumes a grant" (the ending act's delivery of a subscription is not a resumption and runs after it; a switch or a resume that takes the ladder replaces the grant) and "A grant waits on the nearest plan above it that has not ended" (its scenario's subscription is live while the operator's grant supersedes its position).
|
||||
- `operator-panel-navigation`: added "The Monthly recurring headline leaves out a subscription whose collection is paused".
|
||||
|
||||
## Impact
|
||||
|
||||
- **Code:** `internal/fulfillment/reconcile.go`, `plan_change.go`, a new `collection.go` (the decision, the Stripe call, the drift sweep); `internal/entitlements` (the moved rule, the pause rule, the outbox requests, the delivery step, `IssueGrant`, the resume act); `internal/plans/offer.go`; `internal/server/plan_offer.go`, `member_plans.go`, `member_plan_moves.go`, `member_hosted_invoice.go`, `billing.go`, `action_triggers.go`, `operator_enrollment.go`, `operator_enrollment_forms.go`, `operator_billing.go`, `operator_tier_changes.go`; `internal/embeds/templates/partials/member_plans.html`; `internal/integrations/stripe/workflows/outbox.go`; `internal/workflows/billing/`; `internal/stripetest/mock.go` (an invoice list).
|
||||
- **Schema:** `00036_subscription_collection_pause.sql` (three columns on `core.subscriptions`) and `00037_displacement_holder_rank.sql` (`core.subscription_displacements` returns the holder's product and rank).
|
||||
- **Stripe calls:** `POST /v1/subscriptions/{id}` setting or clearing `pause_collection` and the marker (the Subscriptions write the moves already need); the paused switch's update; `GET /v1/invoices?subscription=…&status=open` for Pay invoice on a paused card (Invoices read, already held).
|
||||
- **Routes:** one added, `POST /partials/member/plans/resume`, declared as an action trigger.
|
||||
- **Behaviour a deployment sees:** a grant over a paid tier stops the subscription's charges within seconds and resumes them when the grant ends, with the tier delivered in the same act; the member sees the paused plan, can cancel it, move it to the granted tier or above, or, under a lower grant, resume it; no second subscription on a ladder can be bought.
|
||||
- **Deploy:** re-run `scripts/db-reader-role.sql` after the migrations so the reader role reads the three new columns (`docs/database-management.md`, "Running the script"). Nothing to backfill: the drift sweep pauses every subscription already displaced by a grant within an hour of the deploy (D19), and a read-only count before the push goes to the maintainer (task 13.3).
|
||||
- **Tests:** unit tests of the rules, reconcile tests through the Stripe mock, database tests of each act's request and of the delivery step, the trace goldens, handler tests of the Products page, Checkout, the switch, Resume plan and Pay invoice, database tests of the resume act and its refusals, the organization page and subscriptions list titles, the migrations' up-down-up, and the Stripe sandbox walk at landing.
|
||||
- **Docs:** `docs/stripe.md`, `docs/models/payments-billing.md`, `docs/models/plan-ladders-transitions.md`, `docs/plan-management.md`, `docs/database-locks.md`, `test/AGENTS.md`.
|
||||
|
||||
## Related issues
|
||||
|
||||
- **#269** is this change, with **#270**, **#277** and **#278**, which close with it.
|
||||
- **#271** stays open; this change's refusal of Checkout on a vacated ladder is noted on it at landing.
|
||||
- **#279** and **#280** stay open and build on this change.
|
||||
@@ -0,0 +1,78 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Only the end of a replacing plan resumes a grant
|
||||
|
||||
Reconcile's item pass, suspension, an extension, the org-type default change's migrate disposition and tier removal's migrate disposition SHALL NOT resume any grant: each keeps its behaviour and, where it has one today, the guarded default restoration alone. `ReapplyDefaultsIfVacant` SHALL remain the floor and SHALL NOT resume grants. An extension SHALL continue its lineage, so a grant waiting on the extended grant keeps waiting on the extension. The supersession of a subscription's position by an operator's grant SHALL NOT trigger resumption. When that subscription later ends, reconcile ends nothing of the superseded position: if the subscription holds no other provision, nothing resumes, and otherwise a grant it replaced is judged by the definition, whose condition 4 finds the grant's rungs held while the operator's grant holds them.
|
||||
|
||||
The delivery of a displaced subscription by the act that ends the plan holding its ladder (`stripe-subscription-management`, "A subscription delivers again in the act that ends the plan holding its ladder") SHALL NOT be a resumption: it SHALL run after the act's resumption step, so a resumable grant the ending plan replaced takes its rungs first, and the subscription delivers only where nothing holds them. A subscription that moves to a tier at or above the grant holding its ladder, or whose tier the member resumes over a grant ranked below it (`stripe-subscription-management`, "A member resumes a plan paused under a grant ranked below it"), SHALL supersede the grant as any conferral does, and `core.grant_replacements` SHALL record the grant as replaced by that subscription, so a grant marked to resume delivers again when the subscription ends while the grant's own term lasts.
|
||||
|
||||
#### Scenario: Extending a holder keeps the grant waiting
|
||||
|
||||
- **WHEN** evaluation grant E for Pro, issued over marked grant G for Plus, is extended to a later date
|
||||
- **THEN** G does not resume, and it resumes when the extension ends
|
||||
|
||||
#### Scenario: A subscription superseded by an operator's grant
|
||||
|
||||
- **WHEN** subscription S replaced marked grant G, an operator's grant then superseded S's position, S holds no other provision, and S is later canceled
|
||||
- **THEN** reconcile ends nothing of S and G does not resume
|
||||
|
||||
#### Scenario: A tier removal ends a subscription's rung
|
||||
|
||||
- **WHEN** a tier removal's alignment ends subscription S's rung on ladder L, where S replaced marked grant G
|
||||
- **THEN** G does not resume then
|
||||
|
||||
#### Scenario: The grant waits for the subscription's end after a tier removal
|
||||
|
||||
- **WHEN** a tier removal ended subscription S's rung on ladder L, and S later ends with L still vacant
|
||||
- **THEN** marked grant G, which S replaced on L, resumes
|
||||
|
||||
#### Scenario: A resumable grant takes its rungs before a displaced subscription
|
||||
|
||||
- **WHEN** grant E replaced marked grant G on ladder L and also displaced subscription S there, and E is revoked
|
||||
- **THEN** G resumes, and the revocation's delivery step confers nothing for S on L
|
||||
|
||||
#### Scenario: A switch above a marked grant waits for the subscription's end
|
||||
|
||||
- **WHEN** marked grant G displaced subscription S, and S switches to a tier ranked above G's
|
||||
- **THEN** S's conferral supersedes G and records G as replaced by S, and when S later ends while G's term lasts, G resumes
|
||||
|
||||
#### Scenario: A resume over a lower marked grant waits for the subscription's end
|
||||
|
||||
- **WHEN** marked grant G for Basic displaced subscription S on Pro, and the member resumes Pro
|
||||
- **THEN** S's conferral supersedes G and records G as replaced by S, and when S later ends while G's term lasts, G resumes
|
||||
|
||||
### Requirement: A grant waits on the nearest plan above it that has not ended
|
||||
|
||||
A grant's **lineage** SHALL be the grant and every grant that extends it, directly or through another extension, and its **head** the lineage's grant that no grant extends; a lineage is one plan, and wherever this capability says a grant resumes or is waited on, it SHALL mean a lineage's head. A lineage's **current replacement** SHALL be the latest `core.grant_replacements` row of any of its grants, provided none of its grants has delivered since that row's `replaced_at`. A grant lineage **has ended** at instant `t` when its head is not `active`, is not valid at `t`, or neither delivers nor is marked.
|
||||
|
||||
The **holder** of a lineage at `t` SHALL be found by following current replacements upward from it: the walk stops at the first source that is a subscription or a grant lineage that has not ended at `t`, and when it reaches a lineage with no current replacement without stopping, that lineage is the holder. The chain's **top** SHALL be where the walk ends when it never stops early: the first subscription, or the first lineage with no current replacement. A marked grant SHALL resume when its holder ends, and a plan between a grant and its holder that ends first SHALL be passed over, so the grant then waits on the next plan up.
|
||||
|
||||
#### Scenario: An evaluation holds the grant it was issued over
|
||||
|
||||
- **WHEN** marked complimentary grant G for Plus was replaced by an operator's evaluation grant E for Pro, which delivers
|
||||
- **THEN** E is G's holder
|
||||
|
||||
#### Scenario: A marked, valid plan in the middle of a chain is the holder
|
||||
|
||||
- **WHEN** marked grant G for Plus was replaced by marked evaluation grant E for Pro, E was then replaced by subscription S for Max, and E is still valid
|
||||
- **THEN** E is G's holder, and S is E's holder
|
||||
|
||||
#### Scenario: An ended plan in the middle of a chain is passed over
|
||||
|
||||
- **WHEN** the same chain holds but E has expired, or E was never marked
|
||||
- **THEN** S is G's holder
|
||||
|
||||
#### Scenario: An extension waits in its predecessor's place
|
||||
|
||||
- **WHEN** an operator moves the Valid until of marked grant G, which waits on subscription S, through Manage, and the extension E delivers nothing yet
|
||||
- **THEN** E is the head of G's lineage, E's holder is S, and G is no longer a head
|
||||
|
||||
#### Scenario: A lineage that delivered since has no current replacement
|
||||
|
||||
- **WHEN** grant G was replaced by evaluation E, E was revoked and G resumed, and G still delivers
|
||||
- **THEN** G's lineage has no current replacement, and G has no holder
|
||||
|
||||
#### Scenario: A subscription stops the walk
|
||||
|
||||
- **WHEN** marked grant G was replaced by subscription S, and an operator's grant later superseded S's position while S is live
|
||||
- **THEN** S is G's holder and the chain's top
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Stripe's page of an invoice is read when the member opens it
|
||||
|
||||
The console SHALL send a member to Stripe's hosted invoice page through two member routes, each behind the member session the other billing routes require, each answering a redirect and nothing else:
|
||||
|
||||
- `GET /billing/invoices/{invoiceID}/hosted` SHALL apply the gate the invoice detail applies, through the same function: an invoice that does not exist, or whose billing account does not belong to the member's organization, SHALL answer 404. It SHALL then read the invoice's Stripe mapping. With Stripe not configured, no mapping, or a mapping whose recorded environment the API key's mode cannot reach, or that the environment check marked stale (stripe-integration-infrastructure, Requirement: Mappings record the environment that made their ids), it SHALL answer 303 to `/billing` and SHALL call Stripe for nothing. Otherwise it SHALL read the invoice from Stripe and SHALL answer 303 to its `hosted_invoice_url` whenever Stripe returns one, whatever the invoice's status, and 303 to `/billing` when Stripe returns none or the read fails.
|
||||
- `GET /billing/plans/{ladderID}/unpaid-invoice` SHALL read the organization's position on the ladder in its default pool. When no subscription backs the position, or there is no position, it SHALL take the live subscription that pays for a tier of the ladder without holding its rung (`member-offer`, "One decision says which move a member is offered on a ladder"), if there is one. A ladder id that is not a UUID, neither a subscription-backed position nor a paying subscription, or a subscription whose billing account does not belong to the member's organization SHALL answer 404. It SHALL pick its row through `entitlements.PositionsByLadder`, so a ladder holding an active and a suspended row yields the active one. A picked row whose position status is not `suspended` SHALL answer 303 to `/billing` and SHALL call Stripe for nothing, because the route exists to pay the invoice that suspended the plan, and an active subscription's open latest invoice can be an upgrade the member walked away from; a paying subscription counts as suspended when its status is `past_due` or `unpaid`, and otherwise SHALL answer the same way. With Stripe not configured, no mapping for the subscription, or a mapping the environment check refuses, as the first route applies it to the invoice's, it SHALL answer 303 to `/billing` and SHALL call Stripe for nothing. Otherwise, for a subscription that backs the position, it SHALL read the subscription from Stripe with its latest invoice expanded, and SHALL answer 303 to the latest invoice's `hosted_invoice_url` when that invoice is `open`, and 303 to `/billing` otherwise, a failed read included. For a paying subscription, whose latest invoice can be a renewal voided while the console paused its collection, it SHALL list the subscription's invoices whose status is `open`, newest first, one at most, and SHALL answer 303 to that invoice's `hosted_invoice_url`, and 303 to `/billing` when there is none or the read fails.
|
||||
|
||||
The hosted invoice URL changes on every read, expires, and lets anyone holding it view and pay the invoice, so it SHALL be read when the member opens a route and SHALL NOT be stored or written to any log line; both routes' answers SHALL carry `Cache-Control: no-store`. A failed Stripe read SHALL log the organization, the invoice or subscription id and the error.
|
||||
|
||||
#### Scenario: An open invoice opens its hosted page
|
||||
|
||||
- **WHEN** a member opens the invoice route for an open invoice of their organization whose mapping the key reaches
|
||||
- **THEN** the console reads the invoice from Stripe and answers 303 to its `hosted_invoice_url`
|
||||
- **AND** no log line and no database row carries the URL
|
||||
|
||||
#### Scenario: A paid invoice opens its hosted page
|
||||
|
||||
- **WHEN** a member opens the invoice route for a paid invoice of their organization whose mapping the key reaches
|
||||
- **THEN** the console answers 303 to its `hosted_invoice_url`
|
||||
|
||||
#### Scenario: Another organization's invoice is not found
|
||||
|
||||
- **WHEN** a member opens the invoice route for an invoice whose billing account belongs to another organization
|
||||
- **THEN** the console answers 404 and calls Stripe for nothing
|
||||
|
||||
#### Scenario: An invoice in the other environment goes to the Billing page
|
||||
|
||||
- **WHEN** a member opens the invoice route for an invoice whose mapping records the environment the key is not in
|
||||
- **THEN** the console answers 303 to `/billing` and calls Stripe for nothing
|
||||
|
||||
#### Scenario: The plan's unpaid invoice opens its hosted page
|
||||
|
||||
- **WHEN** a member whose subscription on a ladder is `past_due` opens the plan route for that ladder, and the subscription's latest invoice is open
|
||||
- **THEN** the console answers 303 to that invoice's `hosted_invoice_url`
|
||||
|
||||
#### Scenario: A paused plan's unpaid invoice opens its hosted page
|
||||
|
||||
- **WHEN** a grant holds the ladder, the organization's subscription that pays on it is `past_due` with an invoice from before the grant still open, its latest invoice is a renewal voided while paused, and the member opens the plan route for that ladder
|
||||
- **THEN** the console lists the subscription's open invoices and answers 303 to the open invoice's `hosted_invoice_url`
|
||||
|
||||
#### Scenario: A paused plan with no payment due goes to the Billing page
|
||||
|
||||
- **WHEN** the paying subscription's status is `active` and the member opens the plan route
|
||||
- **THEN** the console answers 303 to `/billing` and calls Stripe for nothing
|
||||
|
||||
#### Scenario: A plan whose latest invoice is paid goes to the Billing page
|
||||
|
||||
- **WHEN** a member opens the plan route after the plan's latest invoice was paid
|
||||
- **THEN** the console answers 303 to `/billing`
|
||||
|
||||
#### Scenario: A plan that is not suspended goes to the Billing page
|
||||
|
||||
- **WHEN** a member opens the plan route for a ladder on which the position is active, whose subscription has an open latest invoice for an upgrade awaiting approval
|
||||
- **THEN** the console answers 303 to `/billing` and calls Stripe for nothing
|
||||
|
||||
#### Scenario: A plan the organization does not hold is not found
|
||||
|
||||
- **WHEN** a member opens the plan route for a ladder on which the organization holds no position a subscription backs and no subscription pays
|
||||
- **THEN** the console answers 404 and calls Stripe for nothing
|
||||
@@ -0,0 +1,139 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: One decision says which move a member is offered on a ladder
|
||||
|
||||
The console SHALL decide which move an organization is offered toward a target price on a plan ladder in one function, `plans.Offer` in `internal/plans`, that reads no database row and calls no payment provider. Its inputs SHALL be the organization's position on the ladder and the target:
|
||||
|
||||
- the position: the ladder's tiers and their ranks; the product the organization holds on the ladder, if any, through a position that is active or suspended; whether a subscription pays for that rung, as opposed to a grant, the organization type's default or a purchase; whether the position is suspended, which its ladder row's status says (the subscription reconcile suspends it while the subscription is `past_due`, `unpaid` or `paused`); whether it is paused, which the subscription's status `paused` says; whether the subscription's cancellation is scheduled; the product an active scheduled downgrade moves to; the held rung (`member-product-discovery`, "Plan-move controls reflect built billing mechanics"); when the cancel prediction exists, the product it puts on the ladder, if any; and, when a live subscription of the organization pays for a tier of the ladder without holding the ladder's rung (the paying subscription), the tier it pays for and its rank, whether a grant holds the rung, whether the paying subscription is suspended (its status is `past_due`, `unpaid` or `paused`) and whether it is `paused`, whether its `core.subscriptions` row records a `pause_collection` behavior together with the console's marker, whether a cancellation or a downgrade is scheduled on it, and whether its product is a tier of another ladder too;
|
||||
- the target: the product; whether it clears the member gate (published, active, public); and the target price, with whether it is the product's default price (price-management, "Each product has at most one default price, which every purchase surface tracks"), whether it is recurring, and whether its Stripe mapping carries an id the current key can reach. A product with no active price is a target with no price.
|
||||
|
||||
The paying subscription SHALL be read from the organization's live subscriptions (status `active`, `trialing`, `past_due`, `unpaid` or `paused`), their current items, and the tiers of the items' products, in one statement per request, never one per ladder; on each ladder the first such subscription by id that does not hold the ladder's position is the paying subscription.
|
||||
|
||||
Its answer SHALL be one move: Checkout, a switch, a downgrade at the period end (the cancellation after which the held rung or the free rung follows), Resume (the paying subscription takes the ladder back from a lower grant at its own price), or none; whether an offered move is enabled; and the reason when no move is offered or the move is disabled. It SHALL route moves as `member-product-discovery`'s "Plan-move controls reflect built billing mechanics" states, and in addition:
|
||||
|
||||
- a price that is not the product's default price SHALL be offered no move;
|
||||
- a Checkout or a switch toward a price that is one-time, or whose mapping has no Stripe id the key can reach, or toward a tier with no price, SHALL be offered disabled;
|
||||
- a Checkout or a switch toward a product that fails the member gate SHALL be offered no move;
|
||||
- a position whose current product is not a tier of the ladder SHALL be offered no move on that ladder;
|
||||
- on a ladder with a paying subscription while no subscription backs the held position, ahead of the rule for the current tier: the tier the subscription pays for SHALL be offered Resume, enabled, when a grant holds the rung at a tier ranked below it, the paying subscription is not suspended, its row records the pause with the console's marker, no cancellation or downgrade is scheduled on it, and its product is a tier of this ladder alone, through no price rule and no member gate, as Keep plan applies none; it SHALL otherwise be offered no move, with the reason that a subscription pays for it on this ladder; when a grant holds the rung and the paying subscription is not suspended, a tier ranked at or above the held rung and above the tier the subscription pays for SHALL be offered a switch of the paying subscription, through the price rules above; the current tier SHALL otherwise keep the reason that it is current; every other tier SHALL be offered no move, with the reason that a subscription pays on the ladder without holding it; and no tier of the ladder SHALL be offered Checkout;
|
||||
- a suspended position SHALL be offered no switch, in either direction, with the reason that the position is suspended; the downgrades at the period end (the held rung's and the free rung's) SHALL be offered as for a position that is not suspended, and, because a subscription backs the rung, no tier of the ladder SHALL be offered Checkout;
|
||||
- a paused position SHALL be offered no move toward any tier but its current one, with the reason that the position is paused: no switch, and no downgrade at the period end either, because what a cancellation does to a paused subscription is unverified; the current tier keeps the reason that it is current.
|
||||
|
||||
The Products page, Checkout, the plan switch, the switch preview and Resume plan SHALL all decide through this function, so no surface offers or accepts a move another refuses. Checkout of a product SHALL be refused when any of the product's ladders has a paying subscription. The switch, its preview and Resume plan SHALL refuse a target the decision answers with no move because the paying subscription is suspended with "Pay the unpaid invoice before changing this plan.", or "A paused plan cannot be changed." when its status is `paused`.
|
||||
|
||||
#### Scenario: A price other than the default is offered nothing
|
||||
|
||||
- **WHEN** a product on a ladder has an older active price and a newer default price, and the decision is asked about the older price for an organization that holds nothing on the ladder
|
||||
- **THEN** it answers no move, with the reason that the price is not the default
|
||||
|
||||
#### Scenario: A one-time default price cannot be bought
|
||||
|
||||
- **WHEN** the decision is asked about a tier whose default price is one-time, for an organization that holds nothing on the ladder
|
||||
- **THEN** it answers Checkout, disabled, with the reason that the price is one-time
|
||||
|
||||
#### Scenario: A tier below a granted rung is offered nothing
|
||||
|
||||
- **WHEN** an organization holds Plus by a grant and the decision is asked about Basic, ranked below Plus
|
||||
- **THEN** it answers no move, with the reason that no subscription pays for the rung
|
||||
|
||||
#### Scenario: The granted tier itself is offered nothing
|
||||
|
||||
- **WHEN** an organization holds Plus by a grant, no subscription pays on the ladder, and the decision is asked about Plus's default price
|
||||
- **THEN** it answers no move, with the reason that the tier is current
|
||||
|
||||
#### Scenario: A higher tier over a grant is Checkout
|
||||
|
||||
- **WHEN** an organization holds Plus by a grant, no subscription pays on the ladder, and the decision is asked about Pro's default price, recurring and reachable
|
||||
- **THEN** it answers Checkout, enabled
|
||||
|
||||
#### Scenario: A tier above a grant that displaced a subscription is a switch
|
||||
|
||||
- **WHEN** an organization holds Pro by a grant, its subscription to Plus pays on the ladder and is active, and the decision is asked about Max's default price, recurring and reachable
|
||||
- **THEN** it answers a switch, enabled, and no Checkout
|
||||
|
||||
#### Scenario: The granted tier over a paying subscription is a switch
|
||||
|
||||
- **WHEN** the same organization's decision is asked about Pro's default price
|
||||
- **THEN** it answers a switch, enabled
|
||||
|
||||
#### Scenario: The paid tier is offered nothing
|
||||
|
||||
- **WHEN** the same organization's decision is asked about Plus
|
||||
- **THEN** it answers no move, with the reason that a subscription pays for it on this ladder
|
||||
|
||||
#### Scenario: A tier between a lower grant and the paid tier is offered nothing
|
||||
|
||||
- **WHEN** an organization holds Basic by a grant, its subscription to Pro pays on the ladder, Plus ranks between them, and the decision is asked about Plus
|
||||
- **THEN** it answers no move, with the reason that a subscription pays on the ladder without holding it
|
||||
|
||||
#### Scenario: The paid tier above a lower grant is offered Resume
|
||||
|
||||
- **WHEN** the same organization's subscription to Pro is active, its row records the pause with the console's marker, nothing is scheduled on it, and the decision is asked about Pro
|
||||
- **THEN** it answers Resume, enabled
|
||||
|
||||
#### Scenario: A tier above the paid tier over a lower grant is a switch
|
||||
|
||||
- **WHEN** the same organization's decision is asked about Max, ranked above Pro
|
||||
- **THEN** it answers a switch, enabled, and no Checkout
|
||||
|
||||
#### Scenario: No Resume without the console's pause
|
||||
|
||||
- **WHEN** the same organization's subscription to Pro has no pause recorded yet, or a pause made in the Stripe Dashboard without the console's marker, and the decision is asked about Pro
|
||||
- **THEN** it answers no move, with the reason that a subscription pays for it on this ladder
|
||||
|
||||
#### Scenario: No Resume while a move is scheduled
|
||||
|
||||
- **WHEN** the same subscription to Pro has a cancellation or a downgrade scheduled, and the decision is asked about Pro
|
||||
- **THEN** it answers no move, with the reason that a subscription pays for it on this ladder
|
||||
|
||||
#### Scenario: Resume is offered over a product no longer public
|
||||
|
||||
- **WHEN** a Basic grant holds the ladder, the organization's subscription to Pro is paused for it with the console's marker, Pro has since been retired, and the decision is asked about Pro
|
||||
- **THEN** it answers Resume, enabled
|
||||
|
||||
#### Scenario: No Resume under a grant of the paid tier or above
|
||||
|
||||
- **WHEN** an organization holds Plus or Pro by a grant, its subscription to Plus pays on the ladder, and the decision is asked about Plus
|
||||
- **THEN** it answers no move, with the reason that a subscription pays for it on this ladder
|
||||
|
||||
#### Scenario: A past-due paying subscription is offered no switch
|
||||
|
||||
- **WHEN** an organization holds Pro by a grant, its subscription to Plus is `past_due`, and the decision is asked about Max
|
||||
- **THEN** it answers no move, and the switch endpoint refuses Max with "Pay the unpaid invoice before changing this plan."
|
||||
|
||||
#### Scenario: A subscription that holds the rung over another keeps its moves
|
||||
|
||||
- **WHEN** an organization's Dashboard-made subscription to Pro holds the ladder's rung over its subscription to Plus, and the decision is asked about Max
|
||||
- **THEN** it answers a switch, as for any subscription that holds its rung, and not the reason that a subscription pays on the ladder without holding it
|
||||
|
||||
#### Scenario: A vacated ladder of a bundle offers no Checkout
|
||||
|
||||
- **WHEN** an organization's subscription pays for a bundle that is a tier of ladders L1 and L2, a grant holds L2, L1 holds nothing, and the decision is asked about a tier of L1
|
||||
- **THEN** it answers no move and no Checkout, because a subscription pays for a tier of L1
|
||||
|
||||
#### Scenario: The tier a scheduled downgrade moves to is offered nothing
|
||||
|
||||
- **WHEN** an organization's subscription on Pro has a downgrade to Standard scheduled and the decision is asked about Standard's default price
|
||||
- **THEN** it answers no move, with the reason that the move is scheduled
|
||||
|
||||
#### Scenario: A suspended position is offered no switch
|
||||
|
||||
- **WHEN** an organization's subscription on Standard is `past_due`, so its position is suspended, and the decision is asked about Pro, ranked above Standard, or about Basic, a priced tier ranked below it
|
||||
- **THEN** it answers no move, with the reason that the position is suspended
|
||||
- **AND** it answers no Checkout for either
|
||||
|
||||
#### Scenario: A suspended position keeps its downgrade at the period end
|
||||
|
||||
- **WHEN** the same organization's subscription bought over a grant for Basic that is marked to resume, and the decision is asked about Basic
|
||||
- **THEN** it answers the downgrade at the period end, enabled, as it does for a position that is not suspended
|
||||
|
||||
#### Scenario: A paused position is offered nothing
|
||||
|
||||
- **WHEN** an organization's subscription on Standard is `paused`, and the decision is asked about Pro, about a held rung ranked below Standard, and about the free rung that follows a cancellation
|
||||
- **THEN** it answers no move for each, with the reason that the position is paused
|
||||
- **AND** asked about Standard itself, it answers no move, with the reason that the tier is current
|
||||
|
||||
#### Scenario: The decision reads nothing
|
||||
|
||||
- **WHEN** the decision's package is built
|
||||
- **THEN** it imports no database, query or payment-provider package, and its table test runs without a database
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: A paid plan whose ladder a grant holds shows its pause on its own card
|
||||
|
||||
On the Products page, on a ladder a grant holds while a live subscription of the organization pays for a tier of it (`member-offer`, "One decision says which move a member is offered on a ladder"), the card of the tier the subscription pays for SHALL carry the subscription's state and its controls, whichever card it is, the current card included when the grant is of that tier, and SHALL be drawn even when its product is no longer a public plan. Its price line SHALL read, by the subscription's state as `core.subscriptions` records it:
|
||||
|
||||
- a `pause_collection` behavior recorded (whoever set the pause), status `active` or `trialing`, nothing scheduled: "Paused while {granted} is granted", with Resume plan when the decision offers it and then Cancel plan;
|
||||
- a `pause_collection` behavior recorded and a cancellation scheduled: "Paused while {granted} is granted", with Keep plan, and the ladder's existing "cancels on {date}" badge;
|
||||
- a `pause_collection` behavior recorded and a downgrade scheduled before the grant: "Paused while {granted} is granted, moves to {tier} on {date}", with Keep plan and then Cancel plan, Pay invoice first when the payment is due;
|
||||
- a `pause_collection` behavior recorded, status `past_due` or `unpaid`: "Paused while {granted} is granted, payment due", with Pay invoice and then Cancel plan or Keep plan, and no "Entitlements are suspended" line;
|
||||
- no `pause_collection` behavior recorded (the pause pending or failed): the existing "{price}, renews {date}", "{price}, moves to {tier} on {date}" or "{price}, ends {date}", or "{price}, payment due" with Pay invoice, with the same controls and no Resume plan;
|
||||
- status `paused`: the existing "{price}, paused" and "Entitlements are suspended.", and no control.
|
||||
|
||||
{granted} SHALL be the name of the product the grant holds on the ladder, the paid tier's own name under a grant of that tier. Cancel plan on that card SHALL cancel the subscription at its period end, and its confirmation's body SHALL read "{paid} ends on {date}; {granted} stays granted." under a grant of another tier and "Your subscription ends on {date}; {granted} stays granted." under a grant of the subscription's own tier, each followed by " The unpaid invoice stays due." when the payment is due, {date} the subscription's period end. Resume plan SHALL open the shared confirmation dialog titled "Resume {paid}?" whose body reads "Your subscription replaces the grant. Nothing is charged now; then {price}.", {price} the subscription's own recurring price, and whose confirm control reads "Resume plan". The granted tier's card and each tier ranked above it, and above the paid tier, SHALL draw the switch the decision offers, labelled "Upgrade"; under a grant ranked below the paid tier, the tiers between them SHALL draw no control. On a ladder the subscription pays for and no plan holds, the paid tier's card SHALL draw no price line and no control. The page SHALL read the paying subscriptions in one statement per request.
|
||||
|
||||
#### Scenario: The paid plan's card while the grant holds
|
||||
|
||||
- **WHEN** a member opens the Products page of an organization whose subscription to Plus is paused for a Pro grant on the same ladder
|
||||
- **THEN** Plus's card reads "Paused while Pro is granted" with Cancel plan, and Pro's card, the current card, and Max's card each offer the switch
|
||||
|
||||
#### Scenario: A payment due from before the grant
|
||||
|
||||
- **WHEN** the same subscription is `past_due` with an invoice from before the grant
|
||||
- **THEN** Plus's card reads "Paused while Pro is granted, payment due" with Pay invoice and then Cancel plan, and no "Entitlements are suspended" line
|
||||
|
||||
#### Scenario: The cancellation's confirmation
|
||||
|
||||
- **WHEN** the member chooses Cancel plan on Plus's card
|
||||
- **THEN** the confirmation reads "Plus ends on {date}; Pro stays granted." with the subscription's period end as the date
|
||||
|
||||
#### Scenario: A pause not yet confirmed
|
||||
|
||||
- **WHEN** the grant was issued and Stripe has not yet confirmed the pause
|
||||
- **THEN** Plus's card reads "{price}, renews {date}" with Cancel plan
|
||||
|
||||
#### Scenario: A subscription Stripe holds as paused
|
||||
|
||||
- **WHEN** the subscription to Plus is `paused` at Stripe while the Pro grant holds the ladder
|
||||
- **THEN** Plus's card reads "{price}, paused" and "Entitlements are suspended.", and draws no control
|
||||
|
||||
#### Scenario: The cancellation's confirmation when the payment is due
|
||||
|
||||
- **WHEN** the paused Plus subscription is `past_due` and the member chooses Cancel plan on Plus's card
|
||||
- **THEN** the confirmation reads "Plus ends on {date}; Pro stays granted. The unpaid invoice stays due."
|
||||
|
||||
#### Scenario: A cancelled paused plan
|
||||
|
||||
- **WHEN** the paused Plus subscription is set to cancel at its period end
|
||||
- **THEN** Plus's card reads "Paused while Pro is granted" with Keep plan, and the ladder carries its "cancels on {date}" badge
|
||||
|
||||
#### Scenario: A downgrade scheduled before the grant
|
||||
|
||||
- **WHEN** the Plus subscription scheduled a downgrade to Basic before the Pro grant, and the pause is confirmed
|
||||
- **THEN** Plus's card reads "Paused while Pro is granted, moves to Basic on {date}" with Keep plan and then Cancel plan
|
||||
|
||||
#### Scenario: A grant of the subscription's own tier
|
||||
|
||||
- **WHEN** a grant of Plus holds the ladder over the paused Plus subscription, and the member chooses Cancel plan on Plus's card, the current card
|
||||
- **THEN** the card reads "Paused while Plus is granted", and the confirmation reads "Your subscription ends on {date}; Plus stays granted."
|
||||
|
||||
#### Scenario: Resume plan under a lower grant
|
||||
|
||||
- **WHEN** a member opens the Products page of an organization whose subscription to Pro is paused with the console's marker for a Basic grant on the same ladder
|
||||
- **THEN** Pro's card reads "Paused while Basic is granted" with Resume plan and then Cancel plan, Plus's card draws no control, and Max's card offers "Upgrade"
|
||||
- **AND** Resume plan opens the confirmation "Resume Pro?" with "Your subscription replaces the grant. Nothing is charged now; then {price}."
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: The subscriptions list marks a subscription that delivers nothing while another plan holds its ladder
|
||||
|
||||
In the operator's subscriptions list (`/operator/billing/subscriptions`), the row of a subscription whose status is `active`, `trialing`, `past_due` or `unpaid` and that is displaced on a ladder another plan holds SHALL carry the "Not delivering" badge, in the warning tone, through the shared status-badge part, in its Status cell after the state badge and, when it renders, the Canceling badge. The row SHALL be decided by the rule the organization composite's billing card applies (`plan-enrollment-administration`, "The billing card says when a subscription delivers nothing while another plan holds its ladder"): `core.subscription_displacements` for the subscription and its organization's active default pool, applied through the reconcile's choice over the subscription's current items, so the list and the card never disagree about a subscription. The badge's title SHALL be worded as the card words it for an account of one subscription, because a row is one subscription: "Billing paused while a grant holds {ladders}." when the row records a `pause_collection` behavior and every plan that holds the subscription's displaced ladders is a grant ("grants hold" when several grant provisions hold them), and "Billing continues while {holder} {ladders}." otherwise. The list SHALL read the pause from the page's own subscription read. A canceled, `paused` or `incomplete` subscription, a subscription no other plan displaced, and a ladder held only by the organization type's default SHALL produce no badge.
|
||||
|
||||
The list SHALL read the displacements, the current items and their ladders once for the page, never once per row. A failed read of any of them SHALL be logged, SHALL leave every row without the badge, and SHALL render "Failed to load deliveries." once, above the table, in the danger style, while the rows the page read still render with their state, period and sync status.
|
||||
|
||||
#### Scenario: A grant over a subscription marks its row
|
||||
|
||||
- **WHEN** an operator views the subscriptions list, and an operator's grant superseded a listed subscription's position on ladder Hosting and still delivers, and Stripe has not confirmed the pause
|
||||
- **THEN** that row's Status cell reads its state badge and the "Not delivering" badge titled "Billing continues while a grant holds Hosting."
|
||||
|
||||
#### Scenario: A confirmed pause marks its row as paused
|
||||
|
||||
- **WHEN** the same subscription's row records the console's pause
|
||||
- **THEN** the badge's title reads "Billing paused while a grant holds Hosting."
|
||||
|
||||
#### Scenario: Two grants hold a paused row's ladders
|
||||
|
||||
- **WHEN** a listed subscription pays for a tier of Hosting and a tier of Wiki (a shape only the Stripe Dashboard makes, since Checkout sells one line item), one operator's grant superseded it on Hosting and another on Wiki, and the row records the console's pause
|
||||
- **THEN** the badge's title reads "Billing paused while grants hold Hosting and Wiki."
|
||||
|
||||
#### Scenario: Two rows paused under their own grants
|
||||
|
||||
- **WHEN** two listed subscriptions with one item each are displaced, one by a grant on Hosting and the other by another grant on Wiki, and both rows record the console's pause
|
||||
- **THEN** the first row's badge title reads "Billing paused while a grant holds Hosting." and the second's reads "Billing paused while a grant holds Wiki."
|
||||
|
||||
#### Scenario: A delivering subscription has no badge
|
||||
|
||||
- **WHEN** a listed subscription delivers on every ladder its current items name
|
||||
- **THEN** its row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A canceled subscription has no badge
|
||||
|
||||
- **WHEN** a listed subscription that an operator's grant superseded has been canceled
|
||||
- **THEN** its row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: The list and the card agree
|
||||
|
||||
- **WHEN** an organization has one subscription, displaced by an operator's grant, paused or not
|
||||
- **THEN** the badge's title on its row in the subscriptions list equals the title of the badge on the organization's billing card
|
||||
|
||||
#### Scenario: The page reads once
|
||||
|
||||
- **WHEN** two more displaced subscriptions are added to the subscriptions a page of the list shows
|
||||
- **THEN** the page runs no more statements than before
|
||||
|
||||
#### Scenario: A failed read says so above the table
|
||||
|
||||
- **WHEN** the read of the displacements for the page fails
|
||||
- **THEN** the list renders its rows without the badge and "Failed to load deliveries." once above the table
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: The Monthly recurring headline leaves out a subscription whose collection is paused
|
||||
|
||||
The Overview's Monthly recurring headline SHALL sum only the current items of `active` subscriptions whose `core.subscriptions` row records no `pause_collection` behavior, because Stripe collects nothing from a subscription whose collection is paused, whoever paused it; the headline leaves such a subscription out as it leaves out a trialing one. The tile's caption SHALL be unchanged: it SHALL count a paused subscription among the active ones, by its status, and SHALL add no clause for paused subscriptions.
|
||||
|
||||
#### Scenario: A paused subscription is left out of the headline
|
||||
|
||||
- **WHEN** the console holds two `active` subscriptions in one currency, one of them recorded with a `pause_collection` behavior
|
||||
- **THEN** the Monthly recurring headline sums the other subscription's current items alone
|
||||
- **AND** the caption reads "2 active subscriptions"
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Advisory warning when a grant would supersede a subscription-sourced position
|
||||
|
||||
When an operator's grant submission would cause `confer` to supersede a position currently held by a subscription-sourced provision, active or suspended, the UI SHALL display an advisory warning, before or alongside the confirmation of the submission, stating that the subscription's billing pauses until the grant ends: "Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends." (`stripe-subscription-management`, "A grant's hold pauses the subscription's collection at Stripe", states when the pause applies, and "Subscription reconcile computes a genuine diff, grouped by product" when the subscription delivers again). The warning SHALL NOT send the operator to another view to change the subscription, because the operator's billing views only read. A suspended position counts because `confer` supersedes a suspended incumbent as it supersedes an active one; a past-due subscription's renewals pause as an active one's do, and a paused one is not invoiced. This is a visibility measure only: the system SHALL NOT block the submission. The grant's own transaction SHALL NOT call Stripe; it SHALL request the subscription's reconcile through the transactional outbox, which pauses the subscription's collection, and SHALL NOT cancel the subscription.
|
||||
|
||||
#### Scenario: Operator is warned before superseding a subscription-held position
|
||||
|
||||
- **WHEN** an operator submits a grant for a product that would supersede a ladder position currently delivered by a subscription-sourced provision
|
||||
- **THEN** the UI SHALL display the advisory warning that the subscription's billing pauses until the grant ends
|
||||
- **AND** the submission SHALL proceed to create the grant and invoke `confer` if the operator confirms, and its transaction SHALL write a `reconcile_subscription` outbox entry for the subscription
|
||||
|
||||
#### Scenario: Operator is warned about a suspended subscription's position
|
||||
|
||||
- **WHEN** an operator opens Issue grant for an organization whose subscription on a ladder is `past_due`, so its position there is suspended
|
||||
- **THEN** the form SHALL mark the products that are tiers of that ladder as superseding a subscription and SHALL show the advisory warning
|
||||
|
||||
#### Scenario: The warning names no view to change the subscription
|
||||
|
||||
- **WHEN** an operator opens Issue grant and the Product select offers a product marked ⚠
|
||||
- **THEN** the warning under the form's lead reads "Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends."
|
||||
- **AND** it names no billing view
|
||||
|
||||
### Requirement: The billing card says when a subscription delivers nothing while another plan holds its ladder
|
||||
|
||||
On the organization composite, the billing card's Subscriptions row SHALL carry a "Not delivering" badge, in the warning tone, through the shared status-badge part, directly after the row's state badge and before the count, when at least one subscription of the billing account whose status is `active`, `trialing`, `past_due` or `unpaid` is displaced on a ladder that another plan holds, as `core.subscription_displacements` states it for the subscription and the organization's default pool, for a product among the subscription's current items, through the same choice the reconcile makes (`stripe-subscription-management`, "Subscription reconcile computes a genuine diff, grouped by product"). The card SHALL NOT restate the rule, and a displacement on a ladder that no current item of the subscription names SHALL produce no badge. A displaced subscription is **paused** for this title when `core.subscriptions` records a `pause_collection` behavior for it and every plan that holds its displaced ladders is a grant; the card SHALL read the record, never the rule, so a pause Stripe has not confirmed reads as billing. The badge's title SHALL name the ladders, by their display names, and the kind of plan that holds them, and SHALL name no product, as the rest of the card names none:
|
||||
|
||||
- for an account with one subscription: "Billing paused while {grant holder} {ladders}." when it is paused, and "Billing continues while {holder} {ladders}." otherwise;
|
||||
- for an account with n subscriptions, n greater than 1 and the row's count, of which k are displaced and paused and m are displaced and not paused: "Billing paused on {k} of {n} subscriptions while {grant holder} {ladders}." when m is 0; "Billing continues on {m} of {n} subscriptions while {holder} {ladders}." when k is 0; and "Billing paused on {k} of {n} subscriptions while {grant holder} {ladders}. Billing continues on {m} while {holder} {ladders}." otherwise, each sentence naming the ladders and holders of its own subscriptions.
|
||||
|
||||
{ladders} SHALL be the distinct displaced ladders' names sorted by `strings.Compare`, joined as "A", "A and B", or "A, B and C". {holder} SHALL be "a grant holds", "another subscription holds" or "another plan holds" when one provision holds every ladder the sentence names, by that provision's source (a grant, a subscription other than the displaced one, or any other source), and "other plans hold" when several provisions hold them. {grant holder} SHALL be "a grant holds" when one grant provision holds every ladder the paused sentence names and "grants hold" when several grant provisions hold them. A subscription that is canceled, `paused` or `incomplete`, a subscription no other plan displaced, and a ladder held only by the organization type's default SHALL produce no badge. For a product of several ladders the title SHALL name the displaced ladder the function picked, not the product's other ladders. The row SHALL carry no other text for the condition. A failed read of the displacements, the subscription's items or their ladders SHALL be logged, SHALL show "Failed to load deliveries." under the row's value line in the danger style, and SHALL render no badge, so the row never reads as if every subscription delivered. The card SHALL change nothing at Stripe and SHALL offer no control for the condition.
|
||||
|
||||
#### Scenario: A grant over the only subscription
|
||||
|
||||
- **WHEN** an operator views the organization page of an organization whose one subscription, on ladder Hosting, was superseded by an operator's grant that still delivers, and Stripe has not confirmed the pause
|
||||
- **THEN** the Subscriptions row reads its state badge, the "Not delivering" badge titled "Billing continues while a grant holds Hosting.", "1 subscription" as a link and its period clause
|
||||
|
||||
#### Scenario: A confirmed pause on the only subscription
|
||||
|
||||
- **WHEN** the same subscription's row records the console's pause
|
||||
- **THEN** the badge's title reads "Billing paused while a grant holds Hosting."
|
||||
|
||||
#### Scenario: Several subscriptions, all paused
|
||||
|
||||
- **WHEN** the account holds three subscriptions, two of them both displaced on Hosting, which one grant holds, and both recorded as paused
|
||||
- **THEN** the badge's title reads "Billing paused on 2 of 3 subscriptions while a grant holds Hosting."
|
||||
|
||||
#### Scenario: Two grants hold a paused subscription's ladders
|
||||
|
||||
- **WHEN** the account's only subscription pays for a tier of Hosting and a tier of Wiki (a shape only the Stripe Dashboard makes, since Checkout sells one line item), one operator's grant superseded it on Hosting and another on Wiki, and the subscription's row records the console's pause
|
||||
- **THEN** the badge's title reads "Billing paused while grants hold Hosting and Wiki."
|
||||
|
||||
#### Scenario: Two subscriptions paused under their own grants
|
||||
|
||||
- **WHEN** the account holds two subscriptions with one item each, one displaced by a grant on Hosting and the other by another grant on Wiki, and both are recorded as paused
|
||||
- **THEN** the badge's title reads "Billing paused on 2 of 2 subscriptions while grants hold Hosting and Wiki."
|
||||
|
||||
#### Scenario: Several subscriptions, some paused
|
||||
|
||||
- **WHEN** the account holds three subscriptions, one displaced by a grant on Hosting and recorded as paused, and one displaced on Wiki by another subscription
|
||||
- **THEN** the badge's title reads "Billing paused on 1 of 3 subscriptions while a grant holds Hosting. Billing continues on 1 while another subscription holds Wiki."
|
||||
|
||||
#### Scenario: Another subscription holds the ladder
|
||||
|
||||
- **WHEN** the account holds two subscriptions on ladder Hosting, and the later one superseded the earlier one's position
|
||||
- **THEN** the badge's title reads "Billing continues on 1 of 2 subscriptions while another subscription holds Hosting."
|
||||
|
||||
#### Scenario: The default does not count
|
||||
|
||||
- **WHEN** the ladder the organization's subscription was displaced from is held only by the organization type's default
|
||||
- **THEN** the Subscriptions row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A subscription that delivers has no badge
|
||||
|
||||
- **WHEN** every subscription of the account delivers on its ladders
|
||||
- **THEN** the Subscriptions row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A canceled subscription has no badge
|
||||
|
||||
- **WHEN** the account's only subscription, superseded by an operator's grant, has been canceled
|
||||
- **THEN** the Subscriptions row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A subscription whose item left the ladder has no badge
|
||||
|
||||
- **WHEN** an operator's grant superseded the organization's subscription on ladder Hosting, and the subscription's only current item now names a product of another ladder
|
||||
- **THEN** the Subscriptions row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A subscription switched above the grant has no badge
|
||||
|
||||
- **WHEN** an operator's grant of Pro superseded the organization's subscription to Plus, and the subscription's item now names Max, ranked above Pro
|
||||
- **THEN** the Subscriptions row carries no "Not delivering" badge
|
||||
|
||||
#### Scenario: A failed read shows the section's error
|
||||
|
||||
- **WHEN** the read of the displacements fails
|
||||
- **THEN** the Subscriptions row shows "Failed to load deliveries." under its value line and no "Not delivering" badge
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Checkout refuses a ladder a subscription pays for without holding it
|
||||
|
||||
A live subscription of the organization (status `active`, `trialing`, `past_due`, `unpaid` or `paused`) whose current item names a tier of a ladder SHALL count, for Checkout's offer decision, as a subscription already paying on that ladder, whether or not it holds the ladder's rung (`member-offer`, "One decision says which move a member is offered on a ladder"), because a second subscription would bill on the same ladder while the first one still exists. So Checkout SHALL refuse every tier of such a ladder, and every product one of whose ladders is such a ladder, with 422 and the unavailable-plan sentence, before any Stripe call and without creating a session. This covers a ladder a grant holds against the subscription and a ladder of a bundle the subscription pays for on which it holds nothing. A tier of a ladder no subscription pays on SHALL be offered Checkout as before, a ladder a grant holds alone included.
|
||||
|
||||
#### Scenario: Checkout refuses a tier above a grant that displaced a subscription
|
||||
|
||||
- **WHEN** a grant holds Pro on a ladder, the organization's subscription to Plus is paused for it, and a member requests checkout for Max from a tab rendered before the grant
|
||||
- **THEN** the system answers 422 with "That plan is no longer available. Refresh the page and choose a current plan.", makes no Stripe API call and creates no Checkout Session
|
||||
|
||||
#### Scenario: Checkout refuses the vacated ladder of a bundle
|
||||
|
||||
- **WHEN** the organization's subscription pays for a bundle that is a tier of ladders L1 and L2, a grant holds L2, L1 holds nothing, and a member requests checkout for a tier of L1
|
||||
- **THEN** the system answers 422 with the unavailable-plan sentence and makes no Stripe API call
|
||||
|
||||
#### Scenario: Checkout above a grant with no subscription stays allowed
|
||||
|
||||
- **WHEN** an organization holds Plus by a grant, no subscription pays on the ladder, and a member requests checkout for Pro
|
||||
- **THEN** the system creates the Checkout Session
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: A grant's hold pauses the subscription's collection at Stripe
|
||||
|
||||
The console SHALL pause a subscription's payment collection at Stripe while grants hold every ladder the subscription pays for, and SHALL resume it when they no longer do. One pure function, `entitlements.CollectionPauseWanted`, SHALL state the rule, reading no row: collection is wanted paused when the subscription's status is `active`, `trialing`, `past_due` or `unpaid`, at least one of its current items names a product with an entitlement set, every such product is left alone by the displacement rule ("Subscription reconcile computes a genuine diff, grouped by product"), and every displacement that leaves one alone has a grant as its holder. A subscription partly displaced, displaced by another subscription, or whose status is `paused`, `incomplete`, `canceled` or any other SHALL NOT be wanted paused.
|
||||
|
||||
The console's pause SHALL be `pause_collection[behavior]=void`, with no `resumes_at`, set in one update together with the subscription metadata `member_console_collection=paused_for_grant` (the marker). The clear SHALL send `pause_collection=` and `metadata[member_console_collection]=` in one update. A pause without the marker was made outside the console: the console SHALL NOT clear or replace it, and SHALL log it when the rule wants a pause. A marker without a pause SHALL be set again while the rule wants a pause and cleared otherwise.
|
||||
|
||||
The subscription reconcile SHALL evaluate the rule in its active and suspended branches, from reads it makes under the pool row, and compare it with the subscription it fetched from Stripe. A reconcile run by the transactional outbox's `reconcile_subscription` action (payload: the console's subscription id) SHALL make the pause or clear call after its commit and SHALL return a failed call, with an error that names the Stripe subscription id, to the outbox's workflow, which retries the reconcile on its budget and then dead-letters the entry. After a successful call, that reconcile SHALL run once more, at most twice in all, so the decision is made again from a fetch taken after its own call. Every other reconcile that finds Stripe disagreeing with the rule SHALL write one `reconcile_subscription` entry in its own transaction and SHALL NOT call Stripe for the pause.
|
||||
|
||||
Each act that can change who holds a ladder SHALL write a `reconcile_subscription` entry, in its own transaction, for each subscription of the pool's organization whose status is `active`, `trialing`, `past_due` or `unpaid`: issuing a grant through the operator's form, extending one through Manage, a revocation, an expiry, the grandfathered legacy grant of a default change, a tier removal, a member's Resume plan, and a subscription reconcile that ended one of its own provisions (for the organization's other subscriptions). An hourly sweep SHALL write the same entry for each live subscription that is mapped to a Stripe subscription the key can reach and whose recorded pause disagrees with the rule, unless that subscription has an entry that is pending, processing or failed, or dead-lettered within the last day.
|
||||
|
||||
Every reconcile SHALL record the subscription's `pause_collection` behavior, its `resumes_at` and whether the marker is set on `core.subscriptions`, from the subscription it fetched, so the console's pages say what Stripe confirmed. The console SHALL move no money at either edge: it SHALL NOT credit the renewal paid before the grant, and SHALL NOT charge the rest of the period in which the grant ends.
|
||||
|
||||
#### Scenario: A grant over the subscription pauses its collection
|
||||
|
||||
- **WHEN** an organization pays for Plus through subscription S, and an operator issues a Pro grant that supersedes S's position
|
||||
- **THEN** the grant's transaction writes a `reconcile_subscription` entry for S, and the outbox's reconcile of S sets `pause_collection[behavior]=void` and the marker in one Stripe update and sets no `resumes_at`
|
||||
- **AND** the reconcile of the echo records the pause and the marker on S's row
|
||||
|
||||
#### Scenario: A renewal while the grant holds is voided
|
||||
|
||||
- **WHEN** S renews while its collection is paused by the console
|
||||
- **THEN** Stripe finalizes and voids the renewal about an hour after it is created, no charge is attempted, and the console projects the invoice as void
|
||||
|
||||
#### Scenario: The grant's end resumes collection
|
||||
|
||||
- **WHEN** the Pro grant over S is revoked or expires
|
||||
- **THEN** the act writes a `reconcile_subscription` entry for S, and the outbox's reconcile clears `pause_collection` and the marker in one Stripe update
|
||||
- **AND** the console credits and charges nothing for the period in which the grant ended
|
||||
|
||||
#### Scenario: A failed pause call is retried and then dead-lettered
|
||||
|
||||
- **WHEN** Stripe answers the pause call with a server error for a day
|
||||
- **THEN** the outbox's workflow retries the reconcile on its budget, each attempt reading the subscription again, and then dead-letters the entry
|
||||
- **AND** the drift sweep writes a new entry for S once the dead letter is a day old
|
||||
|
||||
#### Scenario: Stripe refuses the call
|
||||
|
||||
- **WHEN** Stripe answers the pause call with a 4xx other than 409 or 429
|
||||
- **THEN** the entry is dead-lettered without retries and S's row records no pause
|
||||
|
||||
#### Scenario: A partly displaced subscription keeps billing
|
||||
|
||||
- **WHEN** S pays for a bundle that is a tier of ladders L1 and L2 and another product that is a tier of L3, and a grant supersedes S on L1 only
|
||||
- **THEN** the rule does not want S paused, because S still delivers its L3 product, and the console sends no pause
|
||||
|
||||
#### Scenario: A subscription displaced by another subscription keeps billing
|
||||
|
||||
- **WHEN** subscription S2 of the same organization superseded S's position on S's only ladder
|
||||
- **THEN** the rule does not want S paused, because its holder is a subscription
|
||||
|
||||
#### Scenario: A pause made in the Dashboard is left as it is
|
||||
|
||||
- **WHEN** S carries a pause without the marker, and a grant holds S's only ladder
|
||||
- **THEN** the reconcile sends nothing to Stripe and logs "reconcile: collection paused outside the console; left as it is"
|
||||
- **AND** when the grant ends, the reconcile does not clear that pause
|
||||
|
||||
#### Scenario: Collection resumed in the Dashboard is paused again
|
||||
|
||||
- **WHEN** an operator resumes S's collection in the Stripe Dashboard while the grant holds S's only ladder, leaving the marker
|
||||
- **THEN** the reconcile of the echo writes a `reconcile_subscription` entry, and the outbox's reconcile pauses S again
|
||||
|
||||
#### Scenario: A past-due subscription is paused and its open invoice stays due
|
||||
|
||||
- **WHEN** S is `past_due` with an open invoice when the grant supersedes its position
|
||||
- **THEN** the suspended branch's decision wants S paused and the outbox's reconcile pauses it
|
||||
- **AND** the console voids nothing, and Stripe keeps retrying the open invoice
|
||||
|
||||
#### Scenario: A subscription Stripe holds as paused is not paused for a grant
|
||||
|
||||
- **WHEN** S's status is `paused` and a grant holds its only ladder
|
||||
- **THEN** the rule does not want S paused, and the console sends nothing to Stripe
|
||||
|
||||
#### Scenario: A member's move never makes the pause call
|
||||
|
||||
- **WHEN** a member's cancellation of S ends with a reconcile that finds the rule wanting a pause S does not carry
|
||||
- **THEN** that reconcile writes a `reconcile_subscription` entry, calls Stripe for nothing more, and the cancellation answers as it does today
|
||||
|
||||
#### Scenario: The drift sweep skips a subscription with no reachable mapping
|
||||
|
||||
- **WHEN** the rule wants S paused and S has no Stripe mapping, or a mapping for the other key mode
|
||||
- **THEN** the hourly sweep writes no entry for S
|
||||
|
||||
#### Scenario: A crossed call is decided again
|
||||
|
||||
- **WHEN** the outbox's reconcile of S made its pause call from a fetch taken before the call
|
||||
- **THEN** it fetches S again, decides again, and makes a second call only when S still disagrees with the rule
|
||||
|
||||
#### Scenario: The drift sweep asks for a missed subscription
|
||||
|
||||
- **WHEN** the rule wants S paused, S's row records no pause, and S has no outbox entry
|
||||
- **THEN** the hourly sweep writes one `reconcile_subscription` entry for S, and a second run within the hour, with that entry pending, writes none
|
||||
|
||||
### Requirement: A subscription delivers again in the act that ends the plan holding its ladder
|
||||
|
||||
A revocation, an expiry, the subscription reconcile's ended branch and its end of a surplus provision SHALL, when they ended at least one provision of the ending plan, confer in the same transaction each live subscription's recorded products that the displacement rule no longer leaves alone, after the resumption of marked grants and before the default floor, under the pool row the act holds and without any subscription's advisory lock. The step, `entitlements.DeliverDisplacedSubscriptionsTx`, SHALL read the recorded current items of the organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused` (the ending subscription left out), keep each product with an entitlement set that has no live provision of the subscription, apply the displacement rule and the reconcile's choice of tiers to them, and confer each kept product sourced by the subscription, each subscription under its own savepoint, the subscriptions the ending plan superseded first and then the rest, each group in ascending subscription id order and each subscription's products in ascending `product_id` order. A subscription whose status is `past_due`, `unpaid` or `paused` SHALL be suspended through `core.sync_source_status` in the same savepoint, so its tier comes back suspended. A conferral the database refuses SHALL roll back to its savepoint, SHALL be logged, and SHALL NOT fail the act; a lock wait, a deadlock or a cancelled context SHALL fail it. The step SHALL only confer: ending and re-bounding stay with the subscription's own reconcile, which the act's outbox request runs. An act that ended nothing SHALL deliver nothing.
|
||||
|
||||
#### Scenario: A revocation delivers the subscription in its own transaction
|
||||
|
||||
- **WHEN** an operator revokes the Pro grant that displaced subscription S on Plus
|
||||
- **THEN** the revocation's transaction confers Plus sourced by S, and the floor confers no default on the ladder
|
||||
- **AND** no Stripe event is needed for S to deliver
|
||||
|
||||
#### Scenario: An expiry delivers the subscription
|
||||
|
||||
- **WHEN** the Pro grant that displaced S expires
|
||||
- **THEN** the expiry's transaction confers Plus sourced by S
|
||||
|
||||
#### Scenario: The end of the subscription holding the ladder delivers the one it displaced
|
||||
|
||||
- **WHEN** subscription S2 displaced S on ladder L and S2 is canceled
|
||||
- **THEN** S2's ended reconcile confers S's product before the floor
|
||||
|
||||
#### Scenario: A past-due subscription comes back suspended
|
||||
|
||||
- **WHEN** the grant that displaced S ends while S is `past_due`
|
||||
- **THEN** the act confers S's product and suspends it through `core.sync_source_status` in the same transaction
|
||||
|
||||
#### Scenario: The subscription the ending grant displaced goes before the one that displaced it first
|
||||
|
||||
- **WHEN** subscription S1, with the lower id, was displaced by subscription S2, S2 was displaced by grant G, and G is revoked
|
||||
- **THEN** the revocation confers S2's product, and S1's product stays left alone because S2 holds the ladder
|
||||
|
||||
#### Scenario: A marked grant the ending grant replaced resumes first
|
||||
|
||||
- **WHEN** grant G replaced marked grant G0, G also displaced subscription S, and G is revoked
|
||||
- **THEN** G0 resumes, and S's product stays left alone because G0 holds the ladder
|
||||
|
||||
#### Scenario: A refused conferral leaves the ending in place
|
||||
|
||||
- **WHEN** the grant that displaced S is revoked and S's product was drafted after S bought it
|
||||
- **THEN** the revocation commits, S's conferral is rolled back alone and logged, and the floor runs
|
||||
|
||||
#### Scenario: An ending that ended nothing delivers nothing
|
||||
|
||||
- **WHEN** a revocation is replayed for a grant whose conferral already ended
|
||||
- **THEN** the act delivers nothing and writes no position
|
||||
|
||||
### Requirement: Cancel plan and Keep plan reach a subscription that pays on a ladder without holding it
|
||||
|
||||
The cancellation, keep, resume, switch and preview endpoints, and `SubscriptionBacksLadder`, SHALL resolve the subscription for a ladder through the organization's position when a subscription backs it, and otherwise (a position held by a grant, the default or a purchase, or no position on the ladder at all) through the live subscription (status `active`, `trialing`, `past_due`, `unpaid` or `paused`) whose current item names a tier of the ladder, the lowest subscription id first. A subscription found the second way SHALL be refused, released, cancelled and kept by the same rules as one that holds its rung, its suspension read from its status (`past_due`, `unpaid` and `paused` suspend it), so a past-due one refuses an immediate cancellation and a switch, and a paused one refuses every act with "A paused plan cannot be changed.". Its period-end cancellation SHALL set `cancel_at_period_end` and leave the console's pause in place, so the subscription ends at its period end with no final invoice; its keep SHALL clear `cancel_at_period_end` and release the console's schedule and leave the pause in place.
|
||||
|
||||
#### Scenario: Cancel plan on a paused subscription
|
||||
|
||||
- **WHEN** a grant holds Pro on the ladder, the organization's subscription to Plus is paused for it, and the member cancels Plus
|
||||
- **THEN** the console sets `cancel_at_period_end` on the subscription, records the scheduled cancellation and reconciles, and the pause stays
|
||||
|
||||
#### Scenario: Keep plan after that cancellation
|
||||
|
||||
- **WHEN** the same member keeps Plus before its period ends
|
||||
- **THEN** the console clears `cancel_at_period_end`, supersedes the scheduled cancellation, and the pause stays
|
||||
|
||||
#### Scenario: The grant ends before the cancellation date
|
||||
|
||||
- **WHEN** the grant ends while Plus is set to cancel at its period end
|
||||
- **THEN** the ending act delivers Plus again, and Plus ends at its period end
|
||||
|
||||
#### Scenario: A past-due paying subscription is not cancelled immediately
|
||||
|
||||
- **WHEN** the paying subscription is `past_due` and an immediate cancellation is posted for its ladder
|
||||
- **THEN** the request is refused with "A plan with an unpaid invoice cannot end immediately." before any Stripe call
|
||||
|
||||
### Requirement: A subscription paused for a grant is switched to the granted tier or above
|
||||
|
||||
A member SHALL be able to switch a subscription that pays on a ladder a grant holds to the granted tier or to any tier ranked above it, when that tier is also ranked above the tier the subscription pays for and the subscription is not suspended, through the existing switch endpoint and its preview. The switch SHALL be one immediate upgrade, charged at once with `proration_behavior=always_invoice`, whose Stripe update also clears `pause_collection` and removes the marker when the subscription Stripe returns carries the console's pause or a stale marker, whether or not the subscription holds its ladder, because Stripe refuses an `always_invoice` update on a paused subscription unless that update clears the pause. A pause without the marker SHALL NOT be cleared, and Stripe's refusal then answers the switch's generic failure. A declined or incomplete payment SHALL leave the subscription as it was, as for every upgrade. Once Stripe applies the update, the reconcile SHALL confer the new tier over the grant, recording the grant as replaced by the subscription. The preview of a subscription carrying the console's pause SHALL NOT state a charge other than the one the switch's update makes. It SHALL be the existing unavailable preview whenever Stripe refuses the preview, and whenever the change's sandbox check did not find Stripe's preview figure equal to the update's charge. Its confirmation SHALL read "Switch to {target}?", and its second paragraph SHALL open "Your subscription replaces the grant." before the charge sentence.
|
||||
|
||||
#### Scenario: A switch to the granted tier's superior
|
||||
|
||||
- **WHEN** a grant holds Pro, the organization's subscription to Plus is paused for it, and the member switches to Max
|
||||
- **THEN** one Stripe update changes the item to Max with `always_invoice` and clears `pause_collection` and the marker, the proration is charged now, and the reconcile confers Max over the grant
|
||||
|
||||
#### Scenario: An upgrade of a holding subscription Stripe still has paused
|
||||
|
||||
- **WHEN** the grant that displaced S was revoked, S holds Plus again, the outbox has not yet cleared S's pause, and the member upgrades S to Max
|
||||
- **THEN** the same Stripe update clears `pause_collection` and the marker, so Stripe does not refuse it
|
||||
|
||||
#### Scenario: A switch to the granted tier itself
|
||||
|
||||
- **WHEN** the same member switches to Pro
|
||||
- **THEN** the subscription's item becomes Pro, the reconcile confers Pro as a transfer over the grant, and the grant is recorded as replaced by the subscription
|
||||
|
||||
#### Scenario: A declined switch leaves the subscription paused
|
||||
|
||||
- **WHEN** the card is declined on that switch
|
||||
- **THEN** the subscription keeps Plus, the console's pause stays or is set again by the reconcile its echo runs, and the grant keeps the ladder
|
||||
|
||||
#### Scenario: The confirmation says the subscription replaces the grant
|
||||
|
||||
- **WHEN** the member opens the switch to Max from the paused Plus subscription and the preview answers an amount
|
||||
- **THEN** the confirmation reads "Switch to Max?", and its second paragraph reads "Your subscription replaces the grant. Your card is charged {amount} now for the rest of this period, then {price}."
|
||||
|
||||
#### Scenario: Under a lower grant only the tiers above the paid tier switch
|
||||
|
||||
- **WHEN** a grant holds Basic, the organization's subscription to Pro is paused for it, and the member asks for Plus, ranked between them, and for Max, ranked above Pro
|
||||
- **THEN** the switch endpoint refuses Plus with the unavailable-plan sentence and switches to Max as above
|
||||
|
||||
### Requirement: A member resumes a plan paused under a grant ranked below it
|
||||
|
||||
When a grant holds a ladder at a tier ranked below the tier a live subscription of the organization pays for there, a member SHALL be able to resume the subscription's tier through `POST /partials/member/plans/resume`, which takes the ladder back from the grant with no change to the subscription's item or price. The route SHALL first ask the offer decision (`member-offer`, "One decision says which move a member is offered on a ladder") and SHALL accept only a Resume it answers; when the decision offers none because a subscription already holds the ladder's rung and none pays without holding it, as after a resume, the route SHALL answer "You're already on that plan.". The act SHALL then run in one transaction that takes the pool's row before any read and no subscription advisory lock: it SHALL read, under the row, the subscription's status, its scheduled cancellation and scheduled changes, its recorded pause, its current items, its live provisions, the product's shape and lifecycle, and its displacements, and it SHALL refuse, before any write, a subscription that already holds a live provision on the ladder ("You're already on that plan."), one whose status is `past_due` or `unpaid` ("Pay the unpaid invoice before changing this plan."), one whose status is `paused` ("A paused plan cannot be changed."), and, with "That plan is no longer available. Refresh the page and choose a current plan.", one whose status is neither `active` nor `trialing`, one with a cancellation or a downgrade scheduled, one whose row records no pause or no console marker, one not displaced on the ladder by a grant ranked below its product, one whose product is a tier of another ladder, and one whose product is a draft. The member gate does not apply, as it does not to Keep plan. A subscription whose Stripe mapping the key cannot reach SHALL be refused with the same sentence before the transaction. Otherwise the act SHALL confer the subscription's product sourced by the subscription, superseding the grant's position, and SHALL write a `reconcile_subscription` outbox entry for each live subscription of the organization in the same transaction, and SHALL materialize the pool's entitlements before it commits. The member's request SHALL make no Stripe call: the outbox's reconcile SHALL clear `pause_collection` and the marker after the commit, as "A grant's hold pauses the subscription's collection at Stripe" states. Its confirmation SHALL read "Resume {paid}?", then "Your subscription replaces the grant. Nothing is charged now; then {price}.", {price} the subscription's own recurring price, and a successful resume SHALL show no banner.
|
||||
|
||||
#### Scenario: Resume takes the ladder back from a lower grant
|
||||
|
||||
- **WHEN** a Basic grant holds the ladder, the organization's subscription to Pro is paused for it with the console's marker, and the member resumes Pro
|
||||
- **THEN** one transaction confers Pro sourced by the subscription over the grant and writes the subscription's `reconcile_subscription` entry, and the request calls Stripe for nothing
|
||||
- **AND** the outbox's reconcile clears `pause_collection` and the marker in one Stripe update that changes no item, so Stripe creates no invoice and no proration, and the next renewal is charged at Pro's price
|
||||
|
||||
#### Scenario: Resume materializes the pool's entitlements
|
||||
|
||||
- **WHEN** a Basic grant holds the ladder, the organization's subscription to Pro is paused for it, and the member resumes Pro
|
||||
- **THEN** the pool's entitlements equal Pro's when the transaction commits, so the integrations and the member's Entitlements panel read Pro's
|
||||
|
||||
#### Scenario: A marked grant returns when the resumed subscription ends
|
||||
|
||||
- **WHEN** the Basic grant was marked to resume, the member resumed Pro, and the subscription later ends while the grant's term lasts
|
||||
- **THEN** the grant delivers Basic again
|
||||
|
||||
#### Scenario: A revocation first leaves nothing to resume
|
||||
|
||||
- **WHEN** a revocation of the Basic grant holds the pool row while the member's resume waits for it
|
||||
- **THEN** the revocation delivers Pro again, and the resume then answers "You're already on that plan." and writes nothing
|
||||
|
||||
#### Scenario: A double submit confers once
|
||||
|
||||
- **WHEN** the member's resume is posted twice
|
||||
- **THEN** the second answers "You're already on that plan.", and one transition records Pro's conferral
|
||||
|
||||
#### Scenario: A scheduled cancellation refuses the resume
|
||||
|
||||
- **WHEN** the paused Pro subscription is set to cancel at its period end and a resume is posted
|
||||
- **THEN** the request is refused with "That plan is no longer available. Refresh the page and choose a current plan." and nothing is written
|
||||
|
||||
#### Scenario: A pause made in the Dashboard refuses the resume
|
||||
|
||||
- **WHEN** the subscription's pause carries no console marker and a resume is posted
|
||||
- **THEN** the request is refused with the unavailable-plan sentence, because the console never clears that pause
|
||||
|
||||
#### Scenario: A failed clear keeps the resumed ladder
|
||||
|
||||
- **WHEN** Stripe answers the outbox's clear after a resume with a server error until the entry is dead-lettered
|
||||
- **THEN** the subscription keeps holding the ladder, and the hourly sweep writes a new entry for it once the dead letter is a day old
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Subscription reconcile computes a genuine diff, grouped by product
|
||||
|
||||
Subscription reconcile SHALL compute the desired item state from the subscription's current items grouped by product — an item's product resolved via its price, with two items sharing one product collapsed into a single desired entry at the summed quantity — and SHALL compare that desired state against the subscription's live pool provisions, matched on `product_id` (the live-uniqueness grain is `(subscription_id, product_id)`, backed by a partial unique index scoped to non-ended provisions). Reconcile SHALL NOT tear down and recreate the subscription's provisions wholesale on each run; it SHALL act only on the computed delta between desired and live state. A product present in the desired state but absent from the live provisions (missing) SHALL be conferred via `entitlements.confer`, sourced by the subscription, at the item's quantity and period window, unless another plan took one of its ladders from the subscription and still holds it.
|
||||
|
||||
The subscription is **displaced** on a ladder when its latest episode there (its latest `pool_provision_ladders` row on that ladder in the pool, by activation time and then id) has ended in a supersession whose successor is not one of the subscription's own provisions, that is, when the episode's `end` row and the successor's typed row form a row of `core.supersession_pairs` (`grant-resumption`, "The source that replaced a grant is identified from the transition audit"). **Another plan holds** the ladder while an `active` or `suspended` position on it belongs to a provision that is neither the subscription's nor default-sourced. One function, `core.subscription_displacements(subscription_id, pool_id)`, SHALL state both rules, returning each ladder on which the subscription is displaced and another plan holds it, with the subscription's product that was displaced there, the holder's provision and source, the holder's product, and that product's rank on the ladder (NULL when the product is no tier of the ladder); reconcile, the organization page and the operator's subscriptions list SHALL read the rule through it and SHALL NOT restate it. Reconcile SHALL NOT confer a missing product any ladder of whose current shape is such a ladder: it SHALL leave the whole product alone, because a conferral cannot place part of a product's shape, log it, and decide the subscription's collection as "A grant's hold pauses the subscription's collection at Stripe" states. Such a ladder SHALL NOT leave a missing product alone when its holder is a grant, the product is not the product the subscription was displaced from there, and the product's rank on the ladder is at or above the holder's: the subscription then pays for the granted tier or a higher one, and reconcile SHALL confer it over the grant. On no reconcile does the product a grant displaced take the ladder back while the grant holds it, whatever its rank; only the member's Resume plan confers it over a grant ranked below it ("A member resumes a plan paused under a grant ranked below it"). A default-sourced position never holds a ladder against a subscription, so once no other plan holds the ladder, the subscription delivers again: the act that ended the holder confers it ("A subscription delivers again in the act that ends the plan holding its ladder"), and a reconcile that finds the product still missing confers it. A subscription never displaced on a ladder, a new purchase over a grant among them, confers as before and supersedes what holds the ladder.
|
||||
|
||||
When two or more desired products that are not left alone this way have current shapes that share a ladder, reconcile SHALL keep the one with the highest rank on any of its ladders, ties broken by the lower `product_id`: it walks the products in that order and keeps a product unless a product kept before it holds one of its ladders. A product it leaves out is logged with the product that outranked it, is not conferred, and is not ended. Reconcile SHALL confer and update the products it keeps in ascending `product_id` order, never in the order of Stripe's items or of a map. The displacement rule and this choice SHALL live in `internal/entitlements`, where the ending acts that deliver a subscription again call them.
|
||||
|
||||
Reconcile SHALL make its displacement read and its live read under the pool's row lock (`plan-transitions`, "IssueGrant serializes concurrent operators on the same pool"), so that they see every conferral that committed while it waited. A product present among the live provisions but absent from the desired state (surplus) SHALL be ended via `entitlements.end_conferral`. A product present in both whose quantity differs SHALL be updated via `entitlements.update_conferral_bounds`; this SHALL NOT emit a position transition, because a quantity delta is a bounds change, never a remove-plus-add and never a silent absorption. For a product whose conferral shape spans more than one ladder, the single `entitlements.confer` call SHALL write every junction row the product's shape requires, positioning the pool on all of its ladders in one operation; reconcile SHALL NOT implement a per-caller fork or loop over ladder count, and SHALL NOT silently skip position updates for any ladder beyond the first. A replayed webhook event or a re-run of reconcile for an already-converged subscription SHALL be idempotent: `entitlements.confer`'s per-source retry idempotence SHALL produce a `noop` outcome naming the existing provision, rather than a unique-constraint violation against the subscription+product live-uniqueness index.
|
||||
|
||||
#### Scenario: Missing product is conferred
|
||||
|
||||
- **WHEN** reconcile's desired state includes a product with no matching live provision for the subscription, none of whose ladders another plan took from the subscription and still holds
|
||||
- **THEN** the system SHALL call `entitlements.confer` for that product, sourced by the subscription, at the item's quantity
|
||||
|
||||
#### Scenario: Surplus product is ended
|
||||
|
||||
- **WHEN** a subscription's live provision names a product no longer present among the subscription's current items
|
||||
- **THEN** the system SHALL call `entitlements.end_conferral` for that provision
|
||||
- **AND** it SHALL NOT tear down or recreate the subscription's other, unaffected live provisions
|
||||
|
||||
#### Scenario: Quantity-only change updates bounds without a position transition
|
||||
|
||||
- **WHEN** a matched product's item quantity changes on the subscription while the product itself is unchanged
|
||||
- **THEN** the system SHALL call `entitlements.update_conferral_bounds` with the new quantity
|
||||
- **AND** no position transition (`initiate`/`upgrade`/`downgrade`/`transfer`/`end`) SHALL be recorded for that change
|
||||
|
||||
#### Scenario: A multi-ladder product is positioned in one confer call
|
||||
|
||||
- **WHEN** a missing product occupies more than one ladder
|
||||
- **THEN** the single `entitlements.confer` call SHALL create a junction row on every ladder the product's shape requires
|
||||
- **AND** the system SHALL NOT loop per ladder or skip any ladder beyond the first
|
||||
|
||||
#### Scenario: Webhook replay is idempotent, not a unique-violation error
|
||||
|
||||
- **WHEN** a webhook event that already produced a `confer` call for a subscription and product is replayed
|
||||
- **THEN** `entitlements.confer` SHALL return a `noop` outcome naming the existing provision
|
||||
- **AND** the replay SHALL NOT raise a unique-constraint violation against the subscription+product live-uniqueness index
|
||||
|
||||
#### Scenario: A grant over the subscription keeps the ladder at the next reconcile
|
||||
|
||||
- **WHEN** an organization pays for Plus through subscription S, an operator issues a Max grant that supersedes S's position, and S renews with its items unchanged
|
||||
- **THEN** reconcile SHALL NOT confer Plus, and SHALL write no position, transition or entitlement row
|
||||
- **AND** the Max grant SHALL keep delivering, S SHALL hold no live provision, and S's collection SHALL stay paused by the console
|
||||
|
||||
#### Scenario: A grant of the subscription's own tier keeps the ladder
|
||||
|
||||
- **WHEN** an operator issues a grant of Plus, the tier subscription S pays for, which takes S's position as a transfer, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer Plus for S, and the grant SHALL keep delivering
|
||||
|
||||
#### Scenario: A grant below the subscription's tier keeps the ladder
|
||||
|
||||
- **WHEN** an operator issues a grant of Basic over subscription S's position on Plus, ranked above Basic, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer Plus, because Plus is the product the grant displaced
|
||||
|
||||
#### Scenario: A tier at or above the grant takes the ladder
|
||||
|
||||
- **WHEN** a Pro grant displaced subscription S on Plus, S's item is changed to Max, ranked above Pro, or to Pro itself, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL confer the new product over the grant, an upgrade for Max and a transfer for Pro, and `core.grant_replacements` SHALL pair the grant with S
|
||||
|
||||
#### Scenario: A downgrade landing below the grant stays left alone
|
||||
|
||||
- **WHEN** subscription S on Max scheduled a downgrade to Plus, a Pro grant then displaced S, and the downgrade lands at renewal
|
||||
- **THEN** reconcile SHALL NOT confer Plus, which ranks below Pro
|
||||
|
||||
#### Scenario: A downgrade landing at or above a lower grant takes the ladder
|
||||
|
||||
- **WHEN** subscription S on Max scheduled a downgrade to Pro, a Plus grant then displaced S, and the downgrade lands at renewal
|
||||
- **THEN** reconcile SHALL confer Pro over the grant, and S's collection SHALL resume at Pro's price
|
||||
|
||||
#### Scenario: A quantity change while displaced writes nothing
|
||||
|
||||
- **WHEN** the item of a displaced subscription changes quantity at Stripe while the grant that displaced it holds the ladder
|
||||
- **THEN** reconcile SHALL write no position, transition or entitlement row, since the subscription has no live provision whose bounds could change
|
||||
|
||||
#### Scenario: A grant marked to resume is not recorded as replaced by the subscription
|
||||
|
||||
- **WHEN** an operator issues a grant marked to resume over subscription S's position, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer over the grant, and `core.grant_replacements` SHALL have no row naming the grant and S
|
||||
|
||||
#### Scenario: The subscription delivers again over the default
|
||||
|
||||
- **WHEN** subscription S was displaced on a ladder that the organization type's default now holds alone, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL confer S's product over the default, because a default never holds a ladder against a subscription
|
||||
|
||||
#### Scenario: The subscription delivers again on a vacant ladder
|
||||
|
||||
- **WHEN** subscription S was displaced on a ladder that no plan holds now, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL confer S's product on the vacant ladder
|
||||
|
||||
#### Scenario: A grant issued over the default keeps the ladder
|
||||
|
||||
- **WHEN** grant G superseded subscription S's position, G was revoked and the floor conferred the default, an operator then issues grant G3 over the default, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer over G3, because G3 is another plan holding a ladder S was displaced from, whether or not G3 replaced the plan that displaced S
|
||||
|
||||
#### Scenario: An extension of the grant keeps the ladder
|
||||
|
||||
- **WHEN** grant G superseded subscription S's position, an operator extends G, whose successor takes G's position, and S's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer over the extension
|
||||
|
||||
#### Scenario: A purchase over a grant still supersedes it
|
||||
|
||||
- **WHEN** an organization holds Plus by grant and buys Pro on the same ladder through Checkout, and the new subscription's first reconcile runs
|
||||
- **THEN** reconcile SHALL confer Pro, superseding the grant's position, because the new subscription was never displaced on the ladder
|
||||
|
||||
#### Scenario: A later subscription keeps the ladder it took
|
||||
|
||||
- **WHEN** subscription S2 of the same organization confers a tier of the ladder subscription S1 holds, superseding S1's position, and S1's next reconcile runs
|
||||
- **THEN** reconcile SHALL NOT confer S1's product over S2's position, and later reconciles of either subscription SHALL write nothing on that ladder
|
||||
|
||||
#### Scenario: The subscription's own tier change is not a displacement
|
||||
|
||||
- **WHEN** subscription S moves from Plus to Pro on one ladder and its later reconcile runs
|
||||
- **THEN** S SHALL NOT be displaced on that ladder, since the successor of its Plus episode is its own Pro provision
|
||||
|
||||
#### Scenario: A product of two ladders displaced on one is left alone
|
||||
|
||||
- **WHEN** subscription S pays for a product that is a tier of ladders L1 and L2, and an operator's grant of a product that is a tier of L2 only supersedes S's position, ending S's rungs on both ladders
|
||||
- **THEN** reconcile SHALL NOT confer S's product, and L1 SHALL stay vacant while the grant holds L2
|
||||
|
||||
#### Scenario: A grant issued while the reconcile waits is seen
|
||||
|
||||
- **WHEN** an operator's grant over subscription S's position holds the pool row, uncommitted, while S's reconcile, which would confer a changed item's product, starts
|
||||
- **THEN** the reconcile SHALL wait for the pool row, read the grant once it commits, and SHALL NOT confer over it
|
||||
|
||||
#### Scenario: Two tiers on one subscription confer the higher
|
||||
|
||||
- **WHEN** a subscription carries items for Plan and Plus, two tiers of one ladder with Plus ranked higher, whatever their order on the subscription
|
||||
- **THEN** reconcile SHALL confer Plus and SHALL NOT confer Plan, logging Plan with Plus as the product that outranked it
|
||||
- **AND** a later reconcile with the items unchanged SHALL write no position, transition or entitlement row
|
||||
|
||||
#### Scenario: The reconcile confers in a fixed order
|
||||
|
||||
- **WHEN** a subscription's first reconcile confers three products, each a tier of a ladder of its own, whose items Stripe lists in an order other than their ids'
|
||||
- **THEN** reconcile SHALL confer them in ascending `product_id` order, and a second run on another subscription with the items in another order SHALL do the same
|
||||
|
||||
### Requirement: Suspension and resume propagate via sync_source_status
|
||||
|
||||
When a subscription transitions to a suspending status (`past_due`) or resumes (returns to `active`), reconcile SHALL propagate the change to the subscription's live pool provisions by calling `entitlements.sync_source_status`, rather than by ending or recreating the provision. Suspension SHALL NEVER permanently end a provision: `sync_source_status` SHALL only ever move a provision's status between `suspended` and `active` and SHALL NOT write `status = 'ended'`. If a provision is superseded by a different source while suspended (per `entitlements.confer`'s supersession, which considers `suspended` incumbents equally with `active` ones), that provision SHALL remain ended, and a subsequent resume of its original source SHALL NOT resurrect it — `sync_source_status` SHALL find no non-ended target for that source and SHALL return the empty set. A recovery reaches the item pass, which follows the resume in the same transaction, and the item pass SHALL NOT confer the subscription's product again while another plan holds the ladder (see "Subscription reconcile computes a genuine diff, grouped by product"). The resulting condition, the original subscription paying for a position it no longer holds, SHALL stay in place until no other plan holds the ladder or the subscription moves to a tier at or above a grant that holds it. It SHALL be surfaced through the operator-facing audit trail, the organization page's Billing card (`plan-enrollment-administration`, "The billing card says when a subscription delivers nothing while another plan holds its ladder") and the operator's subscriptions list (`operator-billing-views`, "The subscriptions list marks a subscription that delivers nothing while another plan holds its ladder"). The suspended branch SHALL decide the subscription's collection as "A grant's hold pauses the subscription's collection at Stripe" states, from the subscription's items as Stripe returned them and reads made under the pool row, so a `past_due` or `unpaid` subscription that grants displace is paused like an active one; reconcile SHALL NOT void, refund or forgive an invoice that was open before the grant.
|
||||
|
||||
#### Scenario: past_due suspends without ending
|
||||
|
||||
- **WHEN** a subscription transitions to `past_due`
|
||||
- **THEN** the system SHALL call `entitlements.sync_source_status` with status `suspended` for the subscription's live provisions
|
||||
- **AND** no provision SHALL be marked ended as a result
|
||||
|
||||
#### Scenario: Resume reactivates a still-live suspended provision
|
||||
|
||||
- **WHEN** a `past_due` subscription returns to `active` and its provision was not superseded while suspended
|
||||
- **THEN** the system SHALL call `entitlements.sync_source_status` with status `active`
|
||||
- **AND** the provision SHALL resume active status with its existing position intact
|
||||
|
||||
#### Scenario: Resume does not resurrect a provision superseded while suspended
|
||||
|
||||
- **WHEN** a subscription's provision was ended by a competing `confer` call while the subscription was suspended, and the subscription later resumes
|
||||
- **THEN** `entitlements.sync_source_status` SHALL find no non-ended provision for that source and SHALL return the empty set
|
||||
- **AND** the subscription SHALL NOT regain the superseded position, neither through the resume nor through the item pass that follows it, while another plan holds the ladder
|
||||
- **AND** the system SHALL surface the resulting billing/entitlement mismatch via the audit trail and the Not delivering badge on the Billing card and in the subscriptions list, rather than resolving it automatically
|
||||
|
||||
#### Scenario: A recovery through the reconcile leaves the grant in place
|
||||
|
||||
- **WHEN** an operator's grant superseded the position of a `past_due` subscription, and the subscription returns to `active` and is reconciled
|
||||
- **THEN** the resume SHALL change nothing, the item pass SHALL NOT confer the subscription's product, and the grant SHALL keep delivering
|
||||
|
||||
#### Scenario: A past-due subscription a grant displaces is paused
|
||||
|
||||
- **WHEN** an operator's grant supersedes the position of a `past_due` subscription that pays for nothing else, and the subscription's reconcile runs
|
||||
- **THEN** the suspended branch SHALL want the subscription's collection paused and SHALL write a `reconcile_subscription` entry when Stripe does not carry the console's pause, and the open invoice SHALL stay due at Stripe
|
||||
@@ -0,0 +1,481 @@
|
||||
Tests follow `docs/testing.md`: database tests open the database through `dbtest`, build their rows through the test kit (`internal/testkit/world`) or the package's fixtures, filter to the rows their own fixture made, and pass twice in a row without a reset; tests meet the same complexity limit as production code, so a table runs its rows through a named function. A test of a lock holds one transaction open and waits for the block with `dbtest.AwaitLockWait`, never a sleep. A test of an order feeds its input in more than one order. A test of a migration applies it to a `dbtest.Scratch` database. A page's or a refusal's test compares the whole sentence with its entry in the design's Copy table. A test that asserts a log line finds one line that holds the message and each named attribute (`wantInLine`). A test of a Stripe call reads the call's form from `stripetest.MockBackend.Calls`, never the mock's state.
|
||||
|
||||
Sections 1 to 12 are one commit each, and their items are that commit's parts; section 13 is not a commit. The sections are ordered so that each passes alone: section 1 moves the rule with no behaviour change; sections 2 to 6 pause and resume collection and say so to the operator; section 7 delivers the subscription in the ending act (#270); section 8 lets a tier at or above the grant take the ladder; sections 9 to 12 are the member's side (#277, #269, #278, and Resume plan under a grant ranked below the paid tier); section 9's offer rule answers no switch and no Resume yet, because the preview and the resolver reach a paying subscription only from section 10 and the Stripe update clears the pause only from section 11, which turns the switch's answer into Switch, and section 12 turns the paid tier's answer into Resume once the act, the route and the card's control exist. Between sections 4 and 7 a grant's end still delivers the subscription within seconds, because the outbox's reconcile that clears the pause confers the tier; section 7 moves that into the ending act. Every commit passes `make test` with the test stack up, which runs `make lint` first (`filler-copy`, `em-dash-copy`, `screen-coverage`, the notebook-citations check and `deadcode` among its checks) and then every package one at a time (`-p 1`). A migration is applied by `test/reset-test-db.sh` before the section's tests run (`make test` runs it). A query change is followed by `make sqlc-generate`, and its diff is read: a change to a generated file the section's items do not name is a stop. No golden, route table or test result changes except where a section's items name it; any other change is a stop. A golden is rewritten with `-update` only where an item says so, and its diff is read before the commit. Sections 5, 7, 9, 10, 11 and 12 change what a page renders (section 7 through the demo seed's ledger acts, 7.9), so each runs `make screens` after its tests pass, and `make screens` resets the app database to the demo state; sections 2, 3, 4, 6 and 8 run it too and expect no change. Every row of the design's Copy table is approved or reuses an existing string; a string that differs from its entry is a stop. A script's usage is learned from its header or source, never by running it. No step calls Stripe except items 10.1, 11.1 and 13.4, which run in a Stripe sandbox with test keys.
|
||||
|
||||
**Breaks.** Each section's list is written to a file outside the repository and run with `go run ./scripts/mutation-check -list <file> -side new` on the section's commit, from the repository root, after `test/reset-test-db.sh` and with `test/.env` loaded as `make test` loads it (without it the database tests skip and every record reports SKIPPED), after its green control run. A break of Go code or of a generated sqlc file is a test record (`file`, `old`, `new`, `pkg`, `run_new`, `want_new`); a break of a sqlc query edits the generated `.sql.go` file beside the querier, whose constant the test runs, not the `.sql` file. A break of a migration's SQL is a command record: `cmd` is `(cd test && ./reset-test-db.sh) && go test -p 1 -count=1 -run '<pattern>' <pkg>`, `exit` 1, and the list carries `"prepare": "cd test && ./reset-test-db.sh"`, so each record starts from the restored migration and the last `prepare` restores it. Every record's `want_new` is a text the failing test prints only when it fails, never a test or subtest name; for a golden it is `<path> differs from what the code produced`, with the path as the test passes it. An `old` text that occurs more than once in its file is extended with the lines around it until it occurs once. Every record must be CAUGHT. An `old` text below is the code as the section's items write it; when the committed code words it differently, the record is corrected to the committed text before the run, never dropped. A break that no test of its own section sees is named with the reason, and the commit message says so. The commit message lists every break with its result.
|
||||
|
||||
## 1. The displacement rule moves into `internal/entitlements`
|
||||
|
||||
- [x] 1.1 `internal/entitlements/displacement.go` (new, design D17) holds, moved from `internal/fulfillment/reconcile.go:670-933` with their doc comments: `Rung`, `RungsByProduct`, `Displacement`, `DisplacementsFromRows` (exported, was `displacementsFromRows`), `DisplacedProducts`, `ChooseTiers` (was `chooseTiers`), `Outrank` with fields `ByProductID` and `LadderID` (was `outrank`), and the unexported `candidate` and `shared`. Each doc comment that says the organization page and the subscriptions list call the rule also says that the ending acts in this package call it. The bodies are unchanged.
|
||||
- [x] 1.2 `internal/fulfillment/reconcile.go`: `conferralRungs` stays and returns `map[string][]entitlements.Rung` through `entitlements.RungsByProduct`; `productsLeftAlone`, `convergeConferrals` and the outranked log call the moved names (`o.ByProductID`, `o.LadderID`). `internal/server/operator_enrollment.go` (`displacedOnPage`, `displacedByID`, `displacementsBySubscription`) and `internal/server/operator_billing.go:652` name `entitlements.` in place of `fulfillment.`.
|
||||
- [x] 1.3 Tests. `TestDisplacedProducts` and `TestChooseTiers`, with `checkDisplacedProducts`, `checkChooseTiers` and their row types, move from `internal/fulfillment/reconcile_order_test.go` to `internal/entitlements/displacement_test.go` (package `entitlements`), rows unchanged; their failure texts keep their wording with the new names (`ChooseTiers(%s) kept %v, want %v, products in the order %v`). `TestSortedProducts` stays. The server's tests that build `fulfillment.Rung` or `fulfillment.Displacement` values name `entitlements.`.
|
||||
- [x] 1.4 No golden and no test result changes. `deadcode` refuses a moved function the tree no longer calls.
|
||||
- [x] 1.5 Breaks (test records, each proving a moved test runs in its new package):
|
||||
- a bundle read by its first rung only (`for _, r := range rungs[p] {` replaced by `for _, r := range rungs[p][:min(1, len(rungs[p]))] {`): caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(`;
|
||||
- the tie broken by the higher product id in `ChooseTiers` (`return strings.Compare(a.id, b.id)` replaced by `return strings.Compare(b.id, a.id)`): caught by `TestChooseTiers`, `want_new` `ChooseTiers(`.
|
||||
|
||||
## 2. The subscription row mirrors the pause, and the Overview leaves a paused subscription out of its headline
|
||||
|
||||
- [ ] 2.1 `internal/db/migrations/00036_subscription_collection_pause.sql` (design D3, Migration plan): the SPDX header; a header comment in the style of `00026` saying what the three columns record, that every reconcile writes them from the subscription it fetched, and that the console's own pause is the one whose marker column is true; `ALTER TABLE core.subscriptions ADD COLUMN pause_collection_behavior TEXT NULL, ADD COLUMN pause_collection_resumes_at TIMESTAMPTZ NULL, ADD COLUMN pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE;`, with no check on the behavior, as `status` has none (design D3). Down drops the three columns.
|
||||
- [ ] 2.2 `internal/billing/queries/subscriptions.sql`: `CreateSubscription` and `UpdateSubscriptionStatus` stay as they are; a new `UpdateSubscriptionCollection :exec` sets `pause_collection_behavior`, `pause_collection_resumes_at` and `pause_collection_marked` for a `subscription_id`; `ListSubscriptionsPage` selects `s.pause_collection_behavior` after `s.cancel_at_period_end`; `SumMonthlyRecurringByCurrency` adds `AND s.pause_collection_behavior IS NULL` to `WHERE s.status = 'active'` (Copy O4), and its comment says why. `make sqlc-generate`: the generated diff is `internal/billing/models.go`'s `Subscription` gaining the three fields; the column lists of `internal/billing/subscriptions.sql.go` (`CreateSubscription`, `GetSubscriptionByID`, `GetSubscriptionsByBillingAccountID`, `UpdateSubscriptionStatus`) and of `internal/billing/billing_accounts.sql.go` (`GetLatestSubscriptionByBillingAccountID`, a `SELECT * FROM core.subscriptions` at `internal/billing/queries/billing_accounts.sql:69-75`); the new query in `subscriptions.sql.go` and `querier.go`; and `ListSubscriptionsPage`'s column. No existing caller changes, and the test fakes that embed `billing.Querier` still compile, because the embedded interface supplies the new method. The test kit's `Suspend` (`internal/testkit/world/plans.go:377-389`), `CancelAtPeriodEnd` (`:439-446`) and `EndSubscription` (`internal/testkit/world/acts.go:104-113`) and the demo seed (`internal/demoseed/demoseed.go:1065`) call `UpdateSubscriptionStatus`, which leaves the mirror alone, so a `PauseCollection` made before them survives (design D3).
|
||||
- [ ] 2.3 `internal/fulfillment/reconcile.go`, `upsertSubscription`: `collectionMirror(sub *stripe.Subscription) (behavior sql.NullString, resumesAt sql.NullTime, marked bool)`, reading no row, maps `sub.PauseCollection` (nil gives NULL, NULL, and the marker test alone) and `sub.Metadata[collectionMarkerKey] == collectionMarkerValue`; both branches call `UpdateSubscriptionCollection` with its values, directly after `CreateSubscription` or `UpdateSubscriptionStatus` and before the branch's other statements (`UpsertSubscriptionMapping`, `CreateSubscriptionChange`). `collectionMarkerKey = "member_console_collection"` and `collectionMarkerValue = "paused_for_grant"` are constants in a new `internal/fulfillment/collection.go`, with a doc comment naming the schedules' precedent (`findSpentSchedule`).
|
||||
- [ ] 2.4 Reader role: `internal/migrate/testdata/console-reader-columns.txt` gains `read core.subscriptions.pause_collection_behavior`, `read core.subscriptions.pause_collection_marked` and `read core.subscriptions.pause_collection_resumes_at`, in the file's order (the file aligns its columns, as `read core.…` shows, and is written with `-update`); `scripts/db-reader-role.sql` needs no edit if it grants by the file's rule, otherwise its `core.subscriptions` column list gains the three.
|
||||
- [ ] 2.5 Test kit: `(w *World) PauseCollection(s Subscription)` in `internal/testkit/world/billing.go` sets `pause_collection_behavior = 'void'` and `pause_collection_marked = true` on the subscription's row, with a doc comment saying it stands for the reconcile's record of the console's pause; `(w *World) ForeignPause(s Subscription)` sets the behavior alone.
|
||||
- [ ] 2.6 Tests:
|
||||
- `TestSubscriptionCollectionPauseMigrationUpDownUp` (`internal/db/subscription_collection_pause_test.go`): up, down, up on a `dbtest.Scratch` database, with the columns present after each up and absent after the down. Failure text: `after %s, column %s present = %v, want %v`.
|
||||
- `TestReconcile_MirrorsTheCollectionPause` (`internal/fulfillment/collection_test.go`), rows through `checkMirror`: `no pause` (NULL, NULL, false), `the console's pause` (void, NULL, true), `a pause made in the Dashboard` (`mark_uncollectible`, a `resumes_at`, false), `a marker with no pause` (NULL, NULL, true), and `first sight, the console's pause` (void, NULL, true, the subscription's first reconcile, which goes through `CreateSubscription`); each other row reconciles the subscription once with no pause (the create branch) and then once in the row's state (the update branch), reading the row after the second. Failure text: `mirror(%s) = %q, %v, %v, want %q, %v, %v`.
|
||||
- `TestConsoleReaderColumns` passes with the three lines.
|
||||
- `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription` (`internal/server/operator_overview_db_test.go`): three active subscriptions of one currency from the kit, one of them `PauseCollection` and one `ForeignPause` (a pause made in the Dashboard leaves the headline too). The query sums every `active` subscription in the shared test database, so the test reads `SumMonthlyRecurringByCurrency`'s `usd` bucket before it builds the fixture and after it, and the difference equals the third subscription's monthly amount; `recurringCaption(3, 0, nil, 1)`, called with the fixture's own counts and not the global count query, reads "3 active subscriptions". Failure texts: `monthly recurring = %v, want %v: a paused subscription was summed`; `caption = %q, want %q`.
|
||||
- [ ] 2.7 Docs: `docs/models/payments-billing.md`, the subscriptions row of its table and the Reconciler row (`:40`), say that the row records the collection pause Stripe reports, and that the Monthly recurring headline leaves a paused subscription out; the status-classification note (`:83`) gains "except a subscription grants displace, whose collection the console pauses"; `00036` is listed where the model lists its migrations.
|
||||
- [ ] 2.8 Trace goldens, rewritten with `-update` and read: the 39 goldens under `internal/fulfillment/testdata/` whose trace holds `UpdateSubscriptionStatus` or `CreateSubscription` each gain the one line `UpdateSubscriptionCollection` directly after that statement. Their `== rows` sections are unchanged, because the subscriptions dump names its fields. Any other change is a stop. The 39 are every file of `scheduled_change_trace/` (9); in `reconcile_trace/`, `active_again`, `addon_added`, `addon_removed`, `canceled_replay`, `canceled_resumes_grant`, `canceled_to_default`, `first_sight`, `grant_over_subscription`, `grant_over_suspended_recovery`, `incomplete`, `item_replaced`, `item_without_id`, `past_due`, `price_swap`, `product_without_set`, `quantity`, `quantity_zero`, `replay`, `second_subscription_over_first`, `three_ladders_first_sight`, `two_tiers_one_ladder` and `unmapped_price` (22; `fetch_refused`, `no_customer` and `unreachable` do not change); in `sweep_trace/`, `already_canceled`, `already_ended`, `cancellation_refused`, `due_cancellation`, `lost_claim`, `period_end_landed`, `stale_downgrade` and `term_boundary_switch` (8; `quantity_change`, `term_boundary_switch_refused`, `unreachable_item` and `unreachable_target_price` do not change). The demo seed's statement goldens (`internal/demoseed/testdata/`) do not change, because the seed calls `CreateSubscription` and `UpdateSubscriptionStatus` itself.
|
||||
- [ ] 2.9 Breaks:
|
||||
- the headline's predicate dropped (the generated `SumMonthlyRecurringByCurrency` constant without `AND s.pause_collection_behavior IS NULL`): caught by `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription`, `want_new` `a paused subscription was summed`;
|
||||
- the marker not read (`sub.Metadata[collectionMarkerKey] == collectionMarkerValue` replaced by `false` in `collectionMirror`): caught by `TestReconcile_MirrorsTheCollectionPause`, `want_new` `mirror(the console's pause) =`;
|
||||
- the update branch not writing the mirror (the `UpdateSubscriptionCollection` call deleted from the update branch of `upsertSubscription`): caught by the same test, `want_new` `mirror(the console's pause) =`;
|
||||
- the create branch not writing the mirror (the call deleted from the create branch): caught by the `first sight, the console's pause` row, `want_new` `mirror(first sight, the console's pause) =`;
|
||||
- the reader-columns line removed for `pause_collection_marked`: caught by `TestConsoleReaderColumns`, `want_new` `console_reader's columns disagree with` (`internal/migrate/console_reader_test.go:139`);
|
||||
- `pause_collection_resumes_at` mirrored as NULL always: caught by the `a pause made in the Dashboard` row, `want_new` `mirror(a pause made in the Dashboard) =`;
|
||||
- the foreign pause summed (the headline's predicate tested on the marker instead of the behavior): caught by `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription`, `want_new` `a paused subscription was summed`.
|
||||
- [ ] 2.10 `make screens`: no screen changes, because the demo holds no paused subscription.
|
||||
|
||||
## 3. The reconcile decides the pause, and the outbox applies it
|
||||
|
||||
- [ ] 3.1 `internal/entitlements/collection.go` (new): `CollectionPauseWanted(status string, desired []string, left map[string]Displacement) bool`, reading no row, as design D2 states the rule; its doc comment states the four conditions and why a subscription displaced by another subscription keeps billing.
|
||||
- [ ] 3.2 `internal/fulfillment/collection.go`: `collectionAction` (`collectionNone`, `collectionSet`, `collectionClear`) and `decideCollection(wanted bool, sub *stripe.Subscription) (collectionAction, foreign bool)`, reading no row, as design D2's table states; `collectionParams(action) *stripe.SubscriptionParams` builds the set (`PauseCollection: &stripe.SubscriptionPauseCollectionParams{Behavior: stripe.String("void")}` and `AddMetadata(collectionMarkerKey, collectionMarkerValue)`) or the clear (`AddExtra("pause_collection", "")` and `AddMetadata(collectionMarkerKey, "")`).
|
||||
- [ ] 3.3 `internal/fulfillment/reconcile.go`: `ReconcileSubscription`'s body becomes `reconcile(ctx, db, logger, keyMode, stripeSubscriptionID, reason string, applyCollection bool) (called bool, err error)`, which `ReconcileSubscription` calls with `false`, dropping the flag; `called` is true when `applyCollectionAction` made its call. In the active branch, `convergeConferrals` returns its `left` map and the desired products; the branch calls `entitlements.CollectionPauseWanted` and `decideCollection`, logs L1 when `foreign` and the rule wants a pause, and keeps the action for after the commit. A non-empty action with `applyCollection` false calls `entitlements.RequestSubscriptionReconcile(ctx, tx, subscriptionID)` before the commit. After the commit, with `applyCollection` true, `applyCollectionAction(ctx, logger, stripeSubscriptionID, action)` makes the one `subscription.Update` call, logs L2 on success, and returns the error wrapped as `reconcile: apply collection to %s: %w`. `ApplySubscriptionCollection(ctx, db, logger, keyMode, coreSubscriptionID, reason string) error` reads the subscription's Stripe mapping (`GetSubscriptionMappingBySubscriptionID`), returns nil with L3 when there is none or it has no Stripe id, and otherwise calls `reconcile` with `true`; when that run made a call, it runs `reconcile` with `true` once more, so the decision is made again from a fetch taken after its own call, at most twice in all, and every error it returns names the Stripe subscription id. The doc comments state design D1's reasons: a member's move never reports a pause failure, and the decision is a set-to-state, so two runs that cross converge through the echo.
|
||||
- [ ] 3.4 The suspended branch (design D6): `reconcileSuspended` keeps its suspension and then, only when the status is `past_due` or `unpaid`, calls `collectionInputs(ctx, billingQ, stripeQ, entQ, sub, subUUID, poolID)`, which resolves each fetched item through `resolveItem` (no write), groups the products with an entitlement set, and reads the live provisions, the shapes and the displacements under the pool row the branch holds, then `DisplacedProducts`; the branch decides as the active one does. A `paused` subscription is never wanted paused and makes no read; a stale marker on it is cleared.
|
||||
- [ ] 3.5 `internal/entitlements/outbox_requests.go` (new): `RequestSubscriptionReconcile(ctx context.Context, tx integration.DBTX, subscriptionID string) error` calls `integration.Enqueue(ctx, tx, "stripe", "reconcile_subscription", map[string]string{"subscription_id": subscriptionID})`; `ReconcileSubscriptionAction = "reconcile_subscription"` is the action type's one constant, which the executor names too.
|
||||
- [ ] 3.6 `internal/integrations/stripe/workflows/outbox.go`, `executeAction`: the case `entitlements.ReconcileSubscriptionAction` calls `a.executeReconcileSubscription(ctx, entry)`, which parses the payload (a missing or malformed `subscription_id` returns a `temporal.NewNonRetryableApplicationError` naming the entry), and returns `classifyStripeError` over `fulfillment.ApplySubscriptionCollection(ctx, a.DB, a.Logger, sdkKeyMode(), id, fmt.Sprintf("outbox:reconcile_subscription:%d", entry.ID))`. Its doc comment says that the call needs no idempotency key of its own because it sets a state. The comment at `internal/server/operator_integrations_stripe.go:263`, "Today only Stripe enqueues into it (operator_billing.go)", is updated, because core `entitlements` now enqueues a Stripe action too.
|
||||
- [ ] 3.7 Tests:
|
||||
- `TestCollectionPauseWanted` (`internal/entitlements/collection_test.go`, no database), rows through `checkPauseWanted`: `active, every product left alone by grants` (true); `trialing, the same` (true); `past_due` and `unpaid`, the same (true); `paused`, `incomplete`, `canceled` (false); `no product with a set` (false); `one product left alone, one not` (false); `left alone by another subscription` (false); `left alone by a grant and by a purchase` (false). Failure text: `CollectionPauseWanted(%s) = %v, want %v`.
|
||||
- `TestDecideCollection` (`internal/fulfillment/collection_test.go`, no database), one row per line of design D2's table, with the stale marker under both wants and the console's pause with `mark_uncollectible`. Failure text: `decideCollection(%s) = %v, %v, want %v, %v`.
|
||||
- `TestReconcile_AGrantOverTheSubscriptionRequestsThePause` (`internal/fulfillment/displaced_subscription_test.go`): the fixture of `TestReconcile_AGrantOverTheSubscriptionKeepsTheLadder`, reconciled by `ReconcileSubscription`; one `core.outbox` row with `action_type = 'reconcile_subscription'` and the subscription's id, and no `POST /v1/subscriptions/` call. Failure texts: `reconcile_subscription entries for %s = %d, want 1`; `the reconcile called Stripe for the pause: %v`.
|
||||
- `TestApplyCollection_PausesADisplacedSubscription`: `ApplySubscriptionCollection` on the same fixture sends one `POST /v1/subscriptions/<id>` whose form holds `pause_collection[behavior]=void` and `metadata[member_console_collection]=paused_for_grant` and no `pause_collection[resumes_at]`, and writes no outbox row. Failure text: `pause call form = %v, want %v`.
|
||||
- `TestApplyCollection_ClearsTheConsolesPause`: the mock's subscription carries the console's pause and no grant holds the ladder; one update whose form holds `pause_collection=` and `metadata[member_console_collection]=`. Failure text: `clear call form = %v, want %v`.
|
||||
- `TestApplyCollection_LeavesAForeignPause`: a pause without the marker, the grant holding; no update, and L1 logged with `subscription_id` and `behavior`. Failure text: `a pause made outside the console was changed: %v`.
|
||||
- `TestApplyCollection_AgreementCallsNothing`: the console's pause, the grant holding; no update. Failure text: `an agreeing subscription was updated: %v`.
|
||||
- `TestApplyCollection_DecidesAgainAfterItsCall`: the mock applies the pause call; `ApplySubscriptionCollection` fetches the subscription twice, and a second call is sent only when the second fetch still disagrees (a mock that reverts the pause gets a second call, and never a third). Failure text: `fetches = %d, want 2`.
|
||||
- `TestApplyCollection_ReturnsAFailedCall`: the mock refuses the update with a 500; the function returns an error holding `apply collection`, and the transaction's writes committed. Failure text: `ApplySubscriptionCollection = %v, want the update's error`.
|
||||
- `TestApplyCollection_NoMappingIsASkip`: a subscription with no Stripe mapping; nil, no Stripe call, L3. Failure text: `an unmapped subscription = %v, want nil`.
|
||||
- `TestApplyCollection_PausesAPastDueSubscription` (`internal/fulfillment/suspended_subscription_test.go`): a `past_due` subscription a grant displaced; the pause call is sent, and nothing voids its open invoice. Failure text: `the past-due subscription's pause call = %v`.
|
||||
- `TestOutbox_ReconcileSubscriptionAction` (`internal/integrations/stripe/workflows/outbox_activity_test.go`): an entry with the action runs `ApplySubscriptionCollection`'s path against the mock (the pause call sent), a malformed payload is non-retryable, and a 400 from Stripe classifies as non-retryable. Failure texts: `executeAction(reconcile_subscription) sent %v, want the pause`; `a malformed payload is retryable`.
|
||||
- [ ] 3.8 Trace goldens, rewritten with `-update` and read: `internal/fulfillment/testdata/reconcile_trace/grant_over_subscription.golden`, `grant_over_suspended_recovery.golden` and `internal/fulfillment/testdata/scheduled_change_trace/downgrade_lands_while_displaced.golden` each gain the line `INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)` before `commit`, and their `== rows` gain nothing (the trace prints no outbox rows); `reconcile_trace/past_due.golden` gains the suspended branch's reads after the suspension and its `<materialize>` line, before `commit` (`GetPriceMappingByStripeID`, `GetPrice`, `GetProductByID`, `GetLivePoolProvisionsBySubscriptionID`, `ListConferralShapes`, `ListSubscriptionDisplacements`), and no insert, because no grant holds its ladder; it is the only trace whose subscription is `past_due` or `unpaid`. Any other golden's change is a stop.
|
||||
- [ ] 3.9 Docs: `docs/stripe.md`, the restricted-key paragraph after "Plan changes" names `POST /v1/subscriptions/{id}` with `pause_collection` among the calls the console makes, a permission the upgrade already needs; "Do not do in Stripe" gains: **Do not remove the console's collection marker** (metadata `member_console_collection`) or resume collection of a subscription the console paused; the console pauses it again while a grant holds its ladder, and a subscription paused without the marker is left as it is. `test/AGENTS.md:304-305` (the key's scopes list, which reads only) gains the subscription write the pause needs. `docs/database-locks.md`, "Subscription reconcile", gains the suspended branch's reads under the pool row and the outbox's call after the commit with no lock held.
|
||||
- [ ] 3.10 Breaks:
|
||||
- the rule ignoring the holder's source (`d.HolderSource != "grant"` test removed from `CollectionPauseWanted`): caught by `TestCollectionPauseWanted`, `want_new` `CollectionPauseWanted(left alone by another subscription) =`;
|
||||
- the rule satisfied by one product (`return false` for a desired product missing from `left` replaced by `continue`): caught by the same, `want_new` `CollectionPauseWanted(one product left alone, one not) =`;
|
||||
- a foreign pause cleared (the marker test removed from the clear line of `decideCollection`): caught by `TestDecideCollection`, `want_new` `decideCollection(not paused, foreign) =`, and by `TestApplyCollection_LeavesAForeignPause`, `want_new` `a pause made outside the console was changed`;
|
||||
- the marker not sent (`AddMetadata(collectionMarkerKey, collectionMarkerValue)` deleted): caught by `TestApplyCollection_PausesADisplacedSubscription`, `want_new` `pause call form =`;
|
||||
- the clear not removing the marker (`AddMetadata(collectionMarkerKey, "")` deleted): caught by `TestApplyCollection_ClearsTheConsolesPause`, `want_new` `clear call form =`;
|
||||
- the plain reconcile calling Stripe (`applyCollection` forced to `true` in `ReconcileSubscription`): caught by `TestReconcile_AGrantOverTheSubscriptionRequestsThePause`, `want_new` `the reconcile called Stripe for the pause`;
|
||||
- the plain reconcile writing no entry (the `RequestSubscriptionReconcile` call deleted): caught by the same, `want_new` `reconcile_subscription entries for`;
|
||||
- the failed call swallowed (`return fmt.Errorf("reconcile: apply collection to %s: %w", stripeSubscriptionID, err)` replaced by `return nil`): caught by `TestApplyCollection_ReturnsAFailedCall`, `want_new` `ApplySubscriptionCollection = <nil>`;
|
||||
- the suspended branch not deciding (the `collectionInputs` call guarded by `false`): caught by `TestApplyCollection_PausesAPastDueSubscription`, `want_new` `the past-due subscription's pause call =`, and by `TestReconcileTrace/past_due`, `want_new` `testdata/reconcile_trace/past_due.golden differs from what the code produced`;
|
||||
- the second run after the call dropped: caught by `TestApplyCollection_DecidesAgainAfterItsCall`, `want_new` `fetches =`;
|
||||
- the executor's case removed: caught by `TestOutbox_ReconcileSubscriptionAction`, `want_new` `executeAction(reconcile_subscription) sent`.
|
||||
- [ ] 3.11 `make screens`: no change.
|
||||
|
||||
## 4. Every act that can change who holds a ladder asks for a reconcile
|
||||
|
||||
- [ ] 4.1 `internal/entitlements/queries/pool_provision_transitions.sql` (or the package's subscription query file): `ListLiveSubscriptionsOfPool` returns the subscription ids of the pool's organization (its accounts' billing accounts) whose status is `active`, `trialing`, `past_due` or `unpaid`, ordered by subscription id. `RequestPoolSubscriptionReconciles(ctx, tx, poolID, exceptSubscriptionID string) error` in `outbox_requests.go` writes one entry per row but the excepted one, in that order. `make sqlc-generate`.
|
||||
- [ ] 4.2 `entitlements.IssueGrant(ctx, db, in ConferGrantInput) (ConferGrantResult, error)` runs `ConferGrantTx` and `RequestPoolSubscriptionReconciles` (no exception) in one `BeginMaterializing` transaction, as `ConferGrant` does; its doc comment says why `ConferGrantTx` itself does not request (design D4). `internal/server/operator_enrollment.go:828` calls it in place of `ConferGrant`.
|
||||
- [ ] 4.3 `ManageGrantTx`, `RevokeGrantTx` and `ExpireGrantTx` (`internal/entitlements/grant_acts.go`) call `RequestPoolSubscriptionReconciles` after their materialization (an expiry only when it has a pool), with no exception.
|
||||
- [ ] 4.4 `obligationEnactment.enactOutgoing` (`internal/entitlements/plan_act_move.go:174-217`) calls it after the grandfathered `ConferGrantTx`; `removeFromPool` (`internal/entitlements/ladder_acts.go:421-455`) after its materialization, per pool.
|
||||
- [ ] 4.5 `internal/fulfillment/reconcile.go`: `reconcileEnded`, when it ended a provision, calls `entitlements.RequestPoolSubscriptionReconciles(ctx, tx, poolID, subscriptionID)` after its materialization, and the active branch, when `endSurplusConferrals` ended one, calls it after `endSurplusConferrals` and before its materialization, as the design's Locks section orders them.
|
||||
- [ ] 4.6 Docs (design D14): `docs/stripe.md`, the bullet **A grant over a paid plan.** is rewritten: the grant keeps the ladder; the console pauses the subscription's collection at Stripe (`pause_collection` with `behavior=void` and the marker) within seconds, through the outbox; each renewal made while the grant holds is a draft for about an hour and is then voided; when the grant ends, collection resumes and the tier is delivered again; no money moves at either edge, and the costs this accepts are listed as design D14 lists them (the renewal date decides which way a grant that is not whole periods falls; a pause landing after a renewal's finalization lets it be charged and a clear landing before it lets a paused renewal be charged; a late call moves a whole period; the first charge after a grant can come without Stripe's upcoming-renewal reminder; the switch's cost is documented with the switch in 11.5, and Resume's with Resume in 12.9); an item with no entitlement set, such as a donation line added in the Dashboard, stops billing with the tier beside it while the pause holds (design D2); an invoice open before the grant stays due, Stripe keeps retrying it, and the account's dunning setting can cancel the paused subscription. `docs/models/plan-ladders-transitions.md:80` (invariant 20) says that the subscription's collection is paused while a grant holds every ladder it pays for; invariant 12 of `docs/models/payments-billing.md`, which is about Checkout, is left to section 9. `docs/database-locks.md` gains the sentence that an outbox request is an insert in the act's transaction and takes no lock.
|
||||
- [ ] 4.7 Tests:
|
||||
- `TestActsRequestSubscriptionReconciles` (`internal/entitlements/outbox_requests_db_test.go`), rows through `checkActRequests`, each on an organization with two live subscriptions and one canceled one: `issue` (through `IssueGrant`), `manage`, `revoke`, `expire`, `legacy grant of a default change`, `tier removal`; each act writes one `reconcile_subscription` entry per live subscription, in id order, and none for the canceled one. Failure text: `%s wrote entries for %v, want %v`.
|
||||
- `TestConferGrantTxRequestsNothing`: `ConferGrantTx` alone writes no entry. Failure text: `ConferGrantTx wrote %d outbox entries, want 0`.
|
||||
- `TestReconcileEndedRequestsTheOtherSubscriptions` (`internal/fulfillment/displaced_subscription_test.go`): S2 displaced S1, S2 is canceled and reconciled; one entry for S1 and none for S2. Failure text: `entries after S2's end = %v, want S1's alone`.
|
||||
- `TestSurplusEndRequestsTheOtherSubscriptions` (`internal/fulfillment/displaced_subscription_test.go`): S2 is live, holds the ladder over S1, and drops the item; one entry for S1 and none for S2. Failure text: `entries after S2 dropped its item = %v, want S1's alone`.
|
||||
- `TestIssueGrantHandlerRequestsAReconcile` (`internal/server/operator_enrollment_issue_db_test.go` or the issue handler's test file): a posted grant over a subscription's tier writes the entry. Failure text: `the issue handler wrote no reconcile_subscription entry`.
|
||||
- `internal/demoseed/seed_db_test.go`: the seed's revocation and expiry write entries for Carlos's canceling subscription; the existing assertions pass, and a new one asserts each entry names that subscription. Failure text: `the demo seed's entries = %v`.
|
||||
- [ ] 4.8 Trace goldens, rewritten with `-update` and read, each gaining the one statement `ListLiveSubscriptionsOfPool` and no outbox insert, because each fixture holds one subscription, the excepted one. In the ended branch, the line goes directly after `<materialize>` and before `ApplyScheduledChangesForSubscription` (which `UpdateSubscriptionMappingSyncStatus` and `commit` follow): the reconcile traces `internal/fulfillment/testdata/reconcile_trace/canceled_to_default.golden` and `canceled_resumes_grant.golden`, and the sweep traces `internal/fulfillment/testdata/sweep_trace/already_ended.golden`, `already_canceled.golden`, `due_cancellation.golden` and `lost_claim.golden`, which run `reconcileEnded` after a fired cancellation and end a provision (`core.end_conferral`, then `ListResumableGrantsHeldBy`). In the active branch, the line goes directly after `core.end_conferral` and before `<materialize>`: the reconcile trace `reconcile_trace/addon_removed.golden`, the surplus end. `reconcile_trace/canceled_replay.golden` calls `core.end_conferral`, ends nothing and does not change. The tier removal's and the grandfathered grant's requests (4.4) change no plan-act golden (`internal/server/testdata/plan_acts/`): `actStatements` leaves out every `Get`, `List` and `Count` statement (`internal/server/plan_acts_golden_db_test.go:456-477`), and no plan-act fixture that reaches a request holds a subscription, so no outbox insert prints. Any other change is a stop.
|
||||
- [ ] 4.9 Breaks:
|
||||
- `IssueGrant` without its request: caught by `TestActsRequestSubscriptionReconciles`, `want_new` `issue wrote entries for []`, and by `TestIssueGrantHandlerRequestsAReconcile`;
|
||||
- each of Manage, Revoke, Expire, the legacy grant and the tier removal without its request: one record each, `want_new` `<row> wrote entries for []`;
|
||||
- the status filter widened to every status (the generated `ListLiveSubscriptionsOfPool` constant without its `status IN`): caught by the same test, `want_new` `wrote entries for`;
|
||||
- the exception ignored in `RequestPoolSubscriptionReconciles`: caught by `TestSurplusEndRequestsTheOtherSubscriptions`, `want_new` `entries after S2 dropped its item =` (in the ended test the excepted subscription is canceled and never listed, so ignoring the exception changes nothing there);
|
||||
- `ConferGrantTx` requesting (the request moved into it): caught by `TestConferGrantTxRequestsNothing`, `want_new` `ConferGrantTx wrote`.
|
||||
- [ ] 4.10 `make screens`: no change. 4.7 edits `internal/demoseed/seed_db_test.go`, which the demo snapshot's fingerprint covers (`test/reset-app-db.sh:120`), so this section rebuilds the snapshot, and the snapshot then holds the two `pending` entries the seed's revocation and expiry write; every later reset restores them `pending`. They complete as skips, with L3, once the running app's relay (a 15-second poll) reaches them, and `operator-overview`, the first capture, draws the queue's count ("{n} queued", `internal/embeds/templates/operator.html:277`), as the Stripe provider page does, so whether a capture shows them depends on timing. `test/e2e/screens` therefore gains a wait: before the first capture, the utility waits until the application database holds no `pending` row in `core.outbox`, through the admin connection it already opens for the timestamp pin (`browsertest.AppAdminDB`), with a timeout that fails the run.
|
||||
|
||||
## 5. The operator reads the confirmed pause
|
||||
|
||||
- [ ] 5.1 `internal/server/operator_enrollment.go` (design D16): `subscriptionRef` gains `PauseBehavior string` from the row; `displacedSubscription` gains `Paused bool`; `displacedOnPage` (`operator_enrollment.go:495`, whose signature gains the behavior) sets it when the ref's behavior is set and every displacement it picked has `HolderSource == "grant"`. The organization page's subscription read and `ListSubscriptionsPage` carry the behavior (section 2's column).
|
||||
- [ ] 5.2 `displacementTitle(subscriptions int, displaced []displacedSubscription) string` builds the titles of Copy O0, O1, O2 and the existing forms: it splits the displaced subscriptions into paused and not, builds each part's ladders and holder as today, and joins the paused sentence and the continuing sentence with one space; one subscription on the account gives the one-subscription forms. The paused sentence's holder is "a grant holds" when one grant provision holds every ladder it names and "grants hold" when several do, counted by provision as `displacementHolder` counts (design D16). Its doc comment states the three forms, the two holder forms, and that the record, never the rule, decides "paused".
|
||||
- [ ] 5.3 `subscriptionTitlesFor` (`internal/server/operator_billing.go:643`) passes the row's behavior, so a row reads O0 or the existing one-subscription form.
|
||||
- [ ] 5.4 `internal/server/operator_enrollment_forms.go:130-134`: `issueGrantSupersedeWarning` reads Copy W, and its comment says why the grant pauses the subscription's billing.
|
||||
- [ ] 5.5 Tests:
|
||||
- `TestDisplacementTitle` (`internal/server/operator_enrollment_render_test.go:1335`), rows added to `displacementTitleRows`: `one subscription, paused` (O0, "Billing paused while a grant holds Demo Ladder."); `one subscription, pause not confirmed` (the existing form); `three subscriptions, two paused` (O1); `three subscriptions, one paused, one continuing under another subscription` (O2, "Billing paused on 1 of 3 subscriptions while a grant holds Hosting. Billing continues on 1 while another subscription holds Wiki."); `one subscription, paused under two grants` (O0, "Billing paused while grants hold Hosting and Wiki."); `one subscription, paused under one bundle grant on two ladders` (O0, "Billing paused while a grant holds Hosting and Wiki."); `three subscriptions, two paused under two grants` (O1, "Billing paused on 2 of 3 subscriptions while grants hold Hosting and Wiki."); `paused but held by a purchase` (the existing form). Failure text unchanged: `displacementTitle(%s) = %q, want %q`.
|
||||
- `TestDisplacedOnPage` rows: `a recorded pause under grants` (Paused true), `a recorded foreign pause under grants` (the behavior set by `ForeignPause`, Paused true), `a recorded pause under a subscription` (Paused false). Failure text unchanged.
|
||||
- `TestSubscriptionTitlesFor` rows: `a paused row` reads O0. Failure text unchanged.
|
||||
- `TestOrgEnrollmentGolden`: a new state `grant-over-subscription-paused` (the `grant-over-subscription` state with `w.PauseCollection` on its subscription), goldens written with `-update` and read: the badge's title reads O0 and nothing else differs from `grant-over-subscription`.
|
||||
- `TestOrgEnrollmentIssueGrantPanel_Stacked` and `TestOrgEnrollmentProductsSection`: the warning's whole text equals Copy W.
|
||||
- `TestOrgEnrollmentGolden`: the three states whose Issue grant panel shows the warning, `internal/server/testdata/org_enrollment/rich.html`, `rich-history-search.html` and `suspended-subscription.html`, rewritten with `-update` and read: each changes only in the warning's sentence, which reads Copy W. Their `.json` files do not change, because the view model does not carry the warning's text.
|
||||
- `TestSubscriptionsListMarksAPausedSubscription` (`internal/server/operator_subscriptions_displacement_db_test.go`): a displaced subscription from the kit with `PauseCollection` titles O0, and one without it the existing title. Failure text: `subscriptions list title = %q, want %q`.
|
||||
- `TestOperatorPagesReadAFixedNumberOfTimes` passes unedited.
|
||||
- [ ] 5.6 No other golden changes: the subscriptions page's goldens (`internal/server/testdata/operator_billing/subscriptions-all.json` and `subscriptions-default.json`) serialize `SubscriptionViewModel` (`internal/server/operator_billing.go:431`), which gains no field, and their fixture holds no paused subscription; no other organization page state records a pause. Any other change is a stop.
|
||||
- [ ] 5.7 Docs: `docs/stripe.md`'s grant bullet names the badge's paused title, "Billing paused while a grant holds {ladder}." ("grants hold" when several grants hold the ladders), once Stripe confirms the pause, and the existing title while it does not; `docs/plan-management.md:157` and `:164` (the grant over a paid plan and the badge) read the same.
|
||||
- [ ] 5.8 Breaks:
|
||||
- the record ignored (`Paused` forced false in `displacedOnPage`): caught by `TestDisplacedOnPage`, `want_new` `displacedOnPage(a recorded pause under grants) =`, and by `TestOrgEnrollmentGolden/grant-over-subscription-paused`, `want_new` `testdata/org_enrollment/grant-over-subscription-paused.html differs from what the code produced`;
|
||||
- the holder test dropped (a pause under a subscription reads paused): caught by `TestDisplacedOnPage`, `want_new` `displacedOnPage(a recorded pause under a subscription) =`;
|
||||
- the mixed form's second sentence dropped: caught by `TestDisplacementTitle`, `want_new` `displacementTitle(three subscriptions, one paused, one continuing under another subscription) =`;
|
||||
- the paused holder fixed to "a grant holds": caught by the same, `want_new` `displacementTitle(one subscription, paused under two grants) =`;
|
||||
- the paused holder counted by ladder instead of by provision: caught by the same, `want_new` `displacementTitle(one subscription, paused under one bundle grant on two ladders) =`;
|
||||
- the list row ignoring the behavior: caught by `TestSubscriptionTitlesFor`, `want_new` `subscriptionTitlesFor(a paused row) =`;
|
||||
- the warning's old text restored: caught by `TestOrgEnrollmentIssueGrantPanel_Stacked`, `want_new` `the stacked Issue grant panel lacks`;
|
||||
- the list's paused title not rendered: caught by `TestSubscriptionsListMarksAPausedSubscription`, `want_new` `subscriptions list title =`.
|
||||
- [ ] 5.9 `make screens`: the Issue grant captures that show the warning change, at both widths. The paused title is an attribute no capture shows; the golden pins it.
|
||||
|
||||
## 6. An hourly sweep asks again for a subscription whose pause disagrees with the rule
|
||||
|
||||
- [ ] 6.1 Queries (design D5): `ListLiveSubscriptionsForCollectionSweep` (`internal/integrations/stripe/store/queries/subscription_mappings.sql`, Go package `stripe`, which `fulfillment` imports as `internalstripe`, because billing's sqlc does not load the Stripe store's migrations, `internal/billing/sqlc.yaml:4-6`, and the store's sqlc loads both streams, `internal/integrations/stripe/store/sqlc.yaml:4-6`; `subscription_id`, `status`, the three mirror columns, and the mapping's `livemode` and `sync_status`; joined to `stripe.subscription_mappings`, so an unmapped subscription never appears; the statuses `active`, `trialing`, `past_due`, `unpaid` and `paused`; `subscription_id > $1` keyset, `LIMIT $2`, ordered by id; its generated code lands in `internal/integrations/stripe/store/subscription_mappings.sql.go`, which every break of the query edits); `ListCurrentSubscriptionItemsBySubscriptionIDs` if no query of that shape exists (billing; subscription id, product id, quantity, `ended_at IS NULL`); `ListLiveProvisionProductsBySubscriptionIDs` (entitlements; subscription id and product id of non-ended provisions); `ListSubscriptionsWithRecentReconcileEntries` (`internal/integration/queries/outbox.sql`; `payload->>'subscription_id'` of `reconcile_subscription` entries whose status is `pending`, `processing` or `failed`, or `dead_letter` with `updated_at > NOW() - interval '1 day'`, for the listed ids). `make sqlc-generate`.
|
||||
- [ ] 6.2 `internal/fulfillment/collection_sweep.go`: `collectionDrift(subs, items, live, rungs, displacements) []string`, reading no row, applies `CollectionPauseWanted` over the recorded products with a set that have no live provision and compares the mirror (wanted and no behavior, or not wanted and the marker set, drift; a foreign pause never does), returning the drifting ids in id order. `SweepCollectionDrift(ctx, db, logger, keyMode) (int, error)` pages, drops the rows whose mapping fails `MappingReachable` under the key, reads once per page, drops ids with a recent entry, and writes one entry per drifting id in one transaction per page; L5 when the count is above zero, L6 and the error on a failed read.
|
||||
- [ ] 6.3 `internal/workflows/billing/activities.go`: `SweepCollectionDriftActivity` calls it with `a.keyMode`; `sweep_workflow.go`: `SweepScheduledChangesWorkflow` runs it after `SweepScheduledChangesActivity`, each activity's failure logged and the other still run; the activity is registered where the first one is.
|
||||
- [ ] 6.4 Tests:
|
||||
- `TestCollectionDrift` (`internal/fulfillment/collection_sweep_test.go`, no database), rows: `wanted, not recorded` (drifts); `wanted, recorded` (no); `not wanted, the marker recorded` (drifts); `paused, the marker recorded` (drifts); `not wanted, a foreign pause` (no); `displaced by a subscription` (no); and the drifting ids fed in two orders. Failure text: `collectionDrift(%s) = %v, want %v`.
|
||||
- `TestSweepCollectionDrift_AsksForADisplacedSubscription` (database): a grant over a subscription with no recorded pause and no entry; one entry. Failure text: `the sweep wrote %d entries for the displaced subscription, want 1`.
|
||||
- `TestSweepCollectionDrift_SkipsASubscriptionWithAnEntry`, rows `a pending entry`, `a dead letter an hour old` and `a dead letter two days old` (its `updated_at` set by the test), each the same fixture with that entry; entries 0, 0, 1. Failure text: `with %s, the sweep wrote %d entries, want %d`.
|
||||
- `TestSweepCollectionDrift_ReadsOncePerPage`: twelve drifting subscriptions with a page size of five run the same statements per page, counted through the test kit's statement counter. Failure text: `the sweep ran %d statements for %d pages, want %d`.
|
||||
- `TestSweepCollectionDrift_AFailedReadFailsTheRun`: a querier refusing the items read; the error returned and L6 logged. Failure text: `a failed read = %v, want the error`.
|
||||
- `TestSweepCollectionDrift_SkipsAnUnmappedSubscription`, rows `no mapping` (a displaced subscription with no Stripe mapping) and `a mapping for the other key mode`; for either, the sweep returns nil and writes no entry. Failure texts: `with %s, the sweep returned %v`; `with %s, the sweep wrote %d entries, want 0`.
|
||||
- `TestSweepScheduledChangesWorkflowRunsTheCollectionSweepAfterAFailure` (`internal/workflows/billing/sweep_workflow_test.go`, new, Temporal's `testsuite`) asserts both activities run and that a failure of the first still runs the second. Failure text: `the collection sweep did not run after a failed scheduled-change sweep`.
|
||||
- [ ] 6.5 Docs: `docs/models/payments-billing.md`, the Reconciler row, names the hourly drift sweep and the dead letter's one-day wait.
|
||||
- [ ] 6.6 Breaks:
|
||||
- the foreign pause counted as drift: caught by `TestCollectionDrift`, `want_new` `collectionDrift(not wanted, a foreign pause) =`;
|
||||
- the dead-letter window dropped from `ListSubscriptionsWithRecentReconcileEntries`' generated constant (any dead letter skips): caught by `TestSweepCollectionDrift_SkipsASubscriptionWithAnEntry`, `want_new` `with a dead letter two days old, the sweep wrote 0 entries, want 1`;
|
||||
- the recent-entry filter removed: caught by the same, `want_new` `with a pending entry, the sweep wrote 1 entries, want 0`;
|
||||
- a per-subscription read inside the page loop: caught by `TestSweepCollectionDrift_ReadsOncePerPage`, `want_new` `the sweep ran`;
|
||||
- the `MappingReachable` filter deleted: caught by `TestSweepCollectionDrift_SkipsAnUnmappedSubscription`, `want_new` `with a mapping for the other key mode, the sweep wrote 1 entries, want 0`;
|
||||
- the sweep's join made a left join (`JOIN stripe.subscription_mappings` replaced by `LEFT JOIN stripe.subscription_mappings` in the generated `ListLiveSubscriptionsForCollectionSweep` constant, `internal/integrations/stripe/store/subscription_mappings.sql.go`): caught by the same test's `no mapping` row, `want_new` `converting NULL to string is unsupported`. The unmapped row then arrives with a NULL `livemode`, which `MappingReachable` passes (`internal/integrations/stripe/store/mapping_environment.go:70-100`), and a NULL `sync_status`, which is `NOT NULL` in the table and so is generated as a `string`; the page's scan fails, and the row prints the scan error through `with no mapping, the sweep returned`;
|
||||
- the workflow returning on the first activity's failure: caught by the workflow test, `want_new` `the collection sweep did not run`.
|
||||
- [ ] 6.7 `make screens`: no change.
|
||||
|
||||
## 7. The act that ends a holder delivers the subscription again (#270)
|
||||
|
||||
- [ ] 7.1 Query (design D7): `ListRecordedSubscriptionProductsOfPool` (billing or entitlements; subscription id, status, product id, summed quantity of current items for products with an entitlement set, for the pool's organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused`, ordered by subscription id, product id); `ListSubscriptionsSupersededByProvisions(pool_id, provision_ids, subscription_ids)` (`internal/entitlements/queries/pool_provision_transitions.sql`; the listed subscriptions whose latest episode on a ladder of the pool, by `pool_provision_ladders` activation time and then id as `00034_subscription_displacements.sql:41-49` takes it, ended in a `core.supersession_pairs` row whose `successor_provision_id` is one of `provision_ids`, matched on the pool, the ladder, the ended provision and `effective_at = ended_at` as `00033_supersession_pairs.sql:27-43` pairs them; distinct subscription ids, ordered). `make sqlc-generate`.
|
||||
- [ ] 7.2 `internal/entitlements/subscription_delivery.go` (new): `DeliveredProduct{SubscriptionID, ProductID, ProvisionID string}` and `DeliverDisplacedSubscriptionsTx(ctx, tx, poolID, exceptSubscriptionID, reason string, endedProvisionIDs []string) ([]DeliveredProduct, error)`, as design D7 states, the subscriptions the ending plan superseded first (one `ListSubscriptionsSupersededByProvisions` read over the listed subscriptions, with `endedProvisionIDs`) and then the rest, each group in subscription id order, with `deliverInSavepoint` following `resumeInSavepoint` (`grant_resumption.go:146-171`), savepoint `subscription_delivery`, and the conferral at the summed quantity, as `conferOrBound` confers (`reconcile.go:938-972`). L4 for a refused conferral. When the read returns no row other than the excepted subscription, the step makes no further read, including the ordering read `ListSubscriptionsSupersededByProvisions`, and a subscription with no missing product makes no shape or displacement read (design D7). Reason constants `SubscriptionDeliveryRevocation = "subscription-delivery:revocation:"`, `SubscriptionDeliveryExpiration = "subscription-delivery:expiration:"`, `SubscriptionDeliverySubscription = "subscription-delivery:subscription:"`.
|
||||
- [ ] 7.3 `RevokeGrantTx` and `ExpireGrantTx` call it after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, only when the act ended a provision, with the reason, the grant id and the ids of the provisions it ended; `reconcileEnded` and the active branch after `endSurplusConferrals` call it when they ended one, with the ending subscription excepted. `docs/database-locks.md`, "Grant acts" and "Subscription reconcile", gain the step as the design's Locks section states.
|
||||
- [ ] 7.4 `internal/server/operator_tier_changes.go`, `humanizeTransitionReason`: the three prefixes, for actor `system`, read T1, T2 and T3.
|
||||
- [ ] 7.5 Tests (`internal/entitlements/subscription_delivery_db_test.go`):
|
||||
- `TestDeliverDisplaced_ARevocationDeliversTheSubscription`: the revocation's transaction confers Plus sourced by S, and no default is conferred. Failure texts: `after the revocation, S holds %v on the ladder, want Plus`; `the floor conferred the default over a subscription it should have delivered`.
|
||||
- `TestDeliverDisplaced_AnExpiryDeliversTheSubscription`. Failure text: `after the expiry, S holds %v, want Plus`.
|
||||
- `TestDeliverDisplaced_TheEndOfTheHoldingSubscription` (`internal/fulfillment`): S2's ended reconcile confers S1's product. Failure text: `after S2's end, S1 holds %v, want its product`.
|
||||
- `TestDeliverDisplaced_APastDueSubscriptionComesBackSuspended`. Failure text: `S's position status = %q, want suspended`.
|
||||
- `TestDeliverDisplaced_AResumableGrantGoesFirst`. Failure text: `with G0 resumable, S was delivered: %v`.
|
||||
- `TestDeliverDisplaced_ARefusedConferralIsRolledBackAlone`: S's product drafted; the revocation commits, S holds nothing, the floor ran, L4 logged with its four attributes. Failure text: `the refused delivery failed the revocation: %v`.
|
||||
- `TestDeliverDisplaced_AnActThatEndedNothingDeliversNothing`. Failure text: `a replayed revocation delivered %v`.
|
||||
- `TestDeliverDisplaced_SubscriptionsInIdOrder`: two subscriptions displaced on two ladders by one bundle grant, created in both orders; their conferrals' transition ids rise with the subscription ids. Failure text: `delivered %v, want subscription id order`.
|
||||
- `TestDeliverDisplaced_TheSubscriptionTheEndingHolderDisplacedGoesFirst`: S1, the lower id, is displaced by S2, and S2 is displaced by grant G; G is revoked. The ladder holds S2's product and S1 is left alone. Failure text: `after G ended, the ladder holds %v, want S2's product`.
|
||||
- `TestDeliverDisplaced_WaitsForThePoolRow`: a transaction holds the pool row; the revocation waits (`dbtest.AwaitLockWait`), and takes no subscription advisory lock (`pg_locks` shows none for S while it waits). Failure text: `the delivery took S's advisory lock`.
|
||||
- `TestHumanizeTransitionReason` rows for the three prefixes. Failure text unchanged.
|
||||
- [ ] 7.6 Trace goldens, rewritten with `-update` and read: the three reconcile traces `reconcile_trace/canceled_to_default.golden`, `canceled_resumes_grant.golden` and `addon_removed.golden`, and the four sweep traces `sweep_trace/already_ended.golden`, `already_canceled.golden`, `due_cancellation.golden` and `lost_claim.golden`, whose acts all ended a provision, each gain the one statement `ListRecordedSubscriptionProductsOfPool` after the resumption's statements (after `ListResumableGrantsHeldBy` in `canceled_to_default` and the four sweep traces, after `RELEASE SAVEPOINT grant_resumption` in `canceled_resumes_grant`), or after `core.end_conferral` in `addon_removed`, the active branch's surplus end, which resumes nothing (before its `<materialize>` line): the step reads per live subscription, displaced or not, and its short-circuit (7.2) makes no further read when the fixture holds no other subscription. No server golden changes: no fixture under `internal/server/testdata/` revokes or expires a grant in an organization with a subscription, so no T1 to T3 row appears. Any case whose rows change is a stop.
|
||||
- [ ] 7.7 Docs: `docs/stripe.md`'s grant bullet says the tier is delivered in the act that ends the grant; `docs/models/plan-ladders-transitions.md` invariant 20 says the same; `docs/plan-management.md:164` ("the subscription delivers again at its next reconcile after the grant ends") is rewritten, because it is false after this section. `test/seed/member-console-demo/README.md:73-74` is rewritten, because the ledger demo's revocation and expiry now deliver Carlos's canceling subscription (7.9): line 73 (the **Grants** row) says that Carlos Member's organization carries only the default grant its pool was floored with, since no default is restored on it; line 74 (Carlos Member's Tier changes) reads "Started (Subscription delivers again after a grant expired)" and "Started (Subscription delivers again after a revocation)" where it reads "Started (Default restored after a grant expired)" and "Started (Default restored after a revocation)".
|
||||
- [ ] 7.8 Breaks:
|
||||
- the step after the floor (the call moved below `ReapplyDefaultsIfVacant` in `RevokeGrantTx`): caught by `TestDeliverDisplaced_ARevocationDeliversTheSubscription`, `want_new` `the floor conferred the default over a subscription`;
|
||||
- the step before the resumption: caught by `TestDeliverDisplaced_AResumableGrantGoesFirst`, `want_new` `with G0 resumable, S was delivered`;
|
||||
- no savepoint (the conferral's error returned): caught by `TestDeliverDisplaced_ARefusedConferralIsRolledBackAlone`, `want_new` `the refused delivery failed the revocation`;
|
||||
- no suspension for a past-due status: caught by `TestDeliverDisplaced_APastDueSubscriptionComesBackSuspended`, `want_new` `S's position status = "active"`;
|
||||
- the ended-something guard dropped: caught by `TestDeliverDisplaced_AnActThatEndedNothingDeliversNothing`, `want_new` `a replayed revocation delivered`;
|
||||
- the expiry's call deleted: caught by `TestDeliverDisplaced_AnExpiryDeliversTheSubscription`, `want_new` `after the expiry, S holds`;
|
||||
- the ended reconcile's call deleted: caught by `TestDeliverDisplaced_TheEndOfTheHoldingSubscription`, `want_new` `after S2's end, S1 holds`;
|
||||
- the subscriptions walked in reverse: caught by `TestDeliverDisplaced_SubscriptionsInIdOrder`, `want_new` `want subscription id order`;
|
||||
- the ordering by subscription id alone (the superseded-first sort removed): caught by `TestDeliverDisplaced_TheSubscriptionTheEndingHolderDisplacedGoesFirst`, `want_new` `after G ended, the ladder holds`;
|
||||
- the label of T1 changed: caught by `TestHumanizeTransitionReason`, `want_new` `humanizeTransitionReason("subscription-delivery:revocation:`.
|
||||
- [ ] 7.9 `cd test && ./reset-app-db.sh --rebuild`, then `make screens`. The rebuild is needed because the demo snapshot's fingerprint covers the migrations, `internal/demoseed/*.go` and the clock pin (`test/reset-app-db.sh:120`), not `internal/entitlements`, and this section changes none of the three, so a plain reset would restore the snapshot section 4 built. The demo changes: Carlos's canceling subscription records `demo-plan`, a tier of the Demo Ladder, which the revoked grant and the expired grant are on, and holds no provision, so the revocation's delivery step confers `demo-plan` sourced by the subscription instead of restoring the default, and the expiry confers it again. Carlos Member's Tier changes then read T1 and T2 where they read "Default restored after a revocation" and "Default restored after a grant expired", the two restored default grants are not issued, and the subscription holds the ladder. The captures that change, each read and named in the commit: `operator-organization-detail` (it prefers Carlos Member, `test/e2e/screens/manifest.go:60-61`), in each state the utility captures, at both widths; `operator-grants`, at both widths, which loses the two restored default grants; and `operator-overview`'s recent activity, at both widths. Any other change is a stop. The demo seed's goldens under `internal/demoseed/testdata/` do not change: the canceling and grant steps' statement goldens run no ledger act, and `seed/twice.txt` records the steps' counts and the rows a second seed changes, which stay the same. Hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the Tier changes page with a row for each of T1 to T3, on the test stack with the kit's states loaded, are attached to the commit's review.
|
||||
|
||||
## 8. A subscription that pays at or above the grant takes the ladder
|
||||
|
||||
- [ ] 8.1 `internal/db/migrations/00037_displacement_holder_rank.sql` (design D8): the SPDX header; a header comment saying what the two columns add and why the function is dropped and created; `DROP FUNCTION core.subscription_displacements(UUID, UUID);` and the function as in `00034` with `holder_product_id UUID` and `holder_rank INTEGER` after its five columns, selecting `h.product_id` and `t.rank` through `LEFT JOIN core.plan_ladder_tiers t ON t.plan_ladder_id = h.plan_ladder_id AND t.product_id = h.product_id`; the `GRANT EXECUTE`. Down drops it and restores `00034`'s body and grant.
|
||||
- [ ] 8.2 The three queries name seven aliases and select `d.holder_product_id::uuid AS holder_product_id` and `d.holder_rank::int AS holder_rank` after `holder_source`; their comments say the rank decides the exception. `make sqlc-generate`. `Displacement` gains `HolderProductID`, `HolderRank` and `HolderRanked`; `DisplacementsFromRows` and the server's `displacementsBySubscription` fill them.
|
||||
- [ ] 8.3 `DisplacedProducts` takes the exception as design D8 states (`yields(d Displacement, product string, r Rung) bool`, reading no row); its doc comment says that the product the grant displaced never takes the ladder back, and that a subscription's payment at or above the grant ends the grant's hold.
|
||||
- [ ] 8.4 Tests:
|
||||
- `TestDisplacedProducts` rows: `a tier above the grant` (not left alone); `the granted tier itself, not the displaced product` (not left alone); `the displaced product ranked above a lower grant` (left alone); `a tier below the grant` (left alone); `a tier above a subscription holder` (left alone); `a holder product on no tier of the ladder` (left alone); `a bundle whose other ladder does not yield` (left alone). Failure text unchanged.
|
||||
- `TestSubscriptionDisplacements_TheHolderRank` (`internal/db/displacement_holder_rank_test.go`): the function returns the holder's product and rank, and NULL for a holder product on no tier. Failure text: `holder %s, rank %v, want %s, %v`.
|
||||
- `TestDisplacementHolderRankMigrationUpDownUp`: up, down, up; and after the up, the old five-name alias form (`AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)`) still runs and names the first five columns (design, Rollback). Failure texts: `after %s, the function returns %d columns, want %d`; `the five-name alias form failed: %v`.
|
||||
- `TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder` (`internal/fulfillment/displaced_subscription_test.go`), rows `Max above a Pro grant` (an upgrade) and `Pro under a Pro grant over Plus` (a transfer): the reconcile confers the new product over the grant, `core.grant_replacements` pairs the grant with S, and the decision clears nothing because the mock's subscription carries no pause. Failure texts: `%s: S holds %v, want %s`; `%s: the grant is not recorded as replaced by S`.
|
||||
- `TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder`. Failure text: `a Basic grant under S's Plus lost the ladder`.
|
||||
- `TestSweep_ADowngradeThatLandsWhileDisplacedIsAppliedAndNotConferred` passes unedited.
|
||||
- `TestOrgEnrollmentGolden`: a state `grant-under-switched-subscription` is not needed; `TestDisplacedOnPage` gains the row `a subscription switched above the grant` (no displacement). Failure text unchanged.
|
||||
- No golden changes: no trace or page fixture has a grant holding a ladder against a subscription product, other than the one it displaced, ranked at or above the grant, so `yields` changes no answer; `org_enrollment/grant-over-subscription`'s grant is of the subscription's own product, the displaced one, and its badge stays. The function's two new columns change no statement name.
|
||||
- [ ] 8.5 Docs: `docs/models/plan-ladders-transitions.md` invariant 20 states the exception, and the model's table row for `core.subscription_displacements` (`:37`) says that the function also returns the holder's product and its rank on the ladder (NULL when the product is no tier of it), with `00037_displacement_holder_rank.sql` listed beside `00034_subscription_displacements.sql`; `docs/stripe.md`'s grant bullet says that a switch to the granted tier or above ends the grant's hold.
|
||||
- [ ] 8.6 Breaks:
|
||||
- the displaced-product test dropped from `yields`: caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(the displaced product ranked above a lower grant) =`, and by `TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder`, `want_new` `lost the ladder`;
|
||||
- `>=` as `>`: caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(the granted tier itself, not the displaced product) =`;
|
||||
- the source test dropped: caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(a tier above a subscription holder) =`;
|
||||
- `HolderRanked` ignored: caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(a holder product on no tier of the ladder) =`;
|
||||
- the bundle yielding on any ladder: caught by `TestDisplacedProducts`, `want_new` `DisplacedProducts(a bundle whose other ladder does not yield) =`;
|
||||
- the function's join as an inner join (command record, `-run TestSubscriptionDisplacements_TheHolderRank ./internal/db`): `exit` 1;
|
||||
- the rank read as the displaced product's (`t.product_id = d.product_id`, command record): `exit` 1.
|
||||
- [ ] 8.7 `make screens`: no change. Migration `00037` rebuilds the demo snapshot, which the section-7 commit already rebuilt with the same rows.
|
||||
|
||||
## 9. The offer decision knows a subscription that pays without holding (#277)
|
||||
|
||||
- [ ] 9.1 `internal/billing/queries/subscriptions.sql`: `ListSubscriptionRungsByOrg` as design D9 states, with the mirror's behavior and marker, the scheduled cancellation and switch, and each item's price facts; `ListLadderPositionsByPool` (`internal/entitlements/queries/pool_provision_ladders.sql:212-243`) gains `default_sourced`, so that `GrantHolds` is false when the default holds the rung (design D9). `make sqlc-generate`.
|
||||
- [ ] 9.2 `internal/plans/offer.go`: `Paying` with every field of design D9, and `Position.Paying`; reasons `PaidHere` ("a subscription pays for the target on this ladder without holding it") and `PaysOnLadder` ("a subscription pays on the ladder without holding it"); rule 3a ahead of rule 3 in `Offer`, applied when `Paying` is set and the held position is not subscription-backed (`!pos.Subscribed`), with the rules' doc comment renumbered or the rule named 3a there. In this commit its item 1 (the paying product) answers none, reason `PaidHere`, and section 12 adds Resume; its item 2 (a grant holds, the paying subscription is not suspended, the target ranks at or above the held rung and above the paying product) answers none, reason `PaysOnLadder`, and section 11 turns it into Switch; the rank test against the paying product is question 3's answer (design D9). `Across` is unchanged: rule 3a answers no Checkout on any paying ladder, so a product with such a ladder already combines to none (`checkoutOffer`'s existing `Across` call refuses it, `internal/server/billing.go:284-290`).
|
||||
- [ ] 9.3 `internal/server/plan_offer.go`: `positionLoader` reads `ListSubscriptionRungsByOrg` once per request, cached as `predictions` is (`positions()` is not cached); `payingByLadder(rows, positions) map[string]plans.Paying`, reading no row, sets every field as design D9 states, `GrantHolds` being the held position's `grant_id` set and `default_sourced` false; the choice of a ladder's paying subscription is one pure function in `internal/entitlements` beside `PositionsByLadder`, which `payingByLadder` and `resolveSubscriptionOnLadder` (10.2) both call; `onLadder` sets `pos.Paying`. `switchOffer` maps a refusal with `Paying` suspended to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and after that a refusal with `Paying` set and not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on (design D9); its doc comment states the order. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence on such a ladder.
|
||||
- [ ] 9.4 Tests:
|
||||
- `TestOffer` rows (`internal/plans/offer_test.go`): `the paid tier` (none, PaidHere); `a tier between a lower grant and the paid tier` (none, PaysOnLadder); `a tier below the grant with a paying subscription` (none, PaysOnLadder); `a past-due paying subscription` (none for every target); `a paused paying subscription` (none); `a bundle's vacated ladder` (none, PaysOnLadder, no Checkout); `the default holds the rung` (`GrantHolds` false: no Resume and no switch for any target); `a subscription that holds the rung over another one` (rule 3a does not apply: the held subscription's target above it is a switch, with no `PaysOnLadder` reason); and the existing `a higher tier over a grant is Checkout` row, with no `Paying`, unchanged. Failure text unchanged.
|
||||
- `TestAcross` passes unedited: it takes moves, not positions, and rule 3a already answers no Checkout.
|
||||
- `TestPayingByLadder` (`internal/server/plan_offer_test.go`, no database), rows: `the holding subscription` (never paying); `two subscriptions on one ladder` (the lower id); `a bundle` (both ladders, `OtherLadders` set on each); `the default holds the rung` (`GrantHolds` false); `the console's pause recorded` (`ConsolePaused`); `a pause made in the Dashboard` (the behavior without the marker: `ConsolePaused` false); `a marker with no pause` (`ConsolePaused` false); `a cancellation scheduled` and `a downgrade scheduled` (`MoveScheduled`); `paused` (`Suspended` and `Paused`). Failure text: `payingByLadder(%s) = %v, want %v`.
|
||||
- `TestCheckoutRefusesALadderASubscriptionPaysFor` (`internal/server/billing_checkout_offer_db_test.go`), rows `above the grant` and `the vacated ladder of a bundle`: 422 with "That plan is no longer available. Refresh the page and choose a current plan.", no Stripe call. Failure text: `%s: checkout answered %d, want 422, with %d Stripe calls`.
|
||||
- `TestCheckoutRefusesATierBelowOrAtAGrantedRung` and the existing Checkout tests pass unedited; `TestCheckoutAboveAGrantWithNoSubscription` asserts the session is still created. Failure text: `checkout above a grant with no subscription answered %d`.
|
||||
- `TestMemberPlansGolden`: a new state `paid-plus-under-granted-pro` (the kit's `Subscribe(o, plus)`, then `Issue(o, pro)`, then `PauseCollection`), goldens `internal/server/testdata/member_plans/paid-plus-under-granted-pro.html` and `.json` written with `-update` and read: no card offers Checkout and none offers a switch yet. Plus is a tier of Wiki and Duo, so Duo's Plus card draws no line and no control, and Duo Max offers no Checkout. The card's own state comes in section 10 and the switch in section 11, whose goldens change again. No existing state's `.html` or `.json` changes, because no existing state has a subscription that pays on a ladder without holding it.
|
||||
- `TestProductsPageReadsPayingOnce` (`internal/server/member_plans_read_count_db_test.go`, new, counting statements as `TestOperatorPagesReadAFixedNumberOfTimes` does): the page runs one statement more than before, for any number of ladders; its fixture holds no ladder a grant holds against a paying subscription. Failure text: `the Products page ran %d statements, want %d`.
|
||||
- [ ] 9.5 Breaks:
|
||||
- rule 3a applied when the held position is subscription-backed (the `!pos.Subscribed` test dropped): caught by `TestOffer`, `want_new` `Offer(a subscription that holds the rung over another one) =`;
|
||||
- rule 3a's item 4 falling through to the route (a tier of a bundle's vacated ladder answers Checkout, the row `the vacated ladder of a bundle`): caught by `TestCheckoutRefusesALadderASubscriptionPaysFor`, `want_new` `checkout answered 303` (`postReal` sends no `HX-Request`, so a sold Checkout answers 303);
|
||||
- `GrantHolds` read from `grant_id` alone: caught by `TestPayingByLadder`, `want_new` `payingByLadder(the default holds the rung) =`;
|
||||
- the holding subscription counted as paying: caught by `TestPayingByLadder`, `want_new` `payingByLadder(the holding subscription) =`;
|
||||
- `ConsolePaused` read from the behavior alone: caught by the same, `want_new` `payingByLadder(a pause made in the Dashboard) =`;
|
||||
- `MoveScheduled` read from `cancel_at_period_end` alone: caught by the same, `want_new` `payingByLadder(a downgrade scheduled) =`;
|
||||
- the loader reading per ladder: caught by the read-count test, `want_new` `the Products page ran`.
|
||||
- Unseen by any test of the section, named in the commit message: `switchOffer`'s paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted), because no section-9 test posts a switch on a paying ladder; 11.6 records it, caught by `TestPostSwitchFromAPausedSubscription`.
|
||||
- [ ] 9.6 `make screens`: no demo state has a paying subscription, so no capture changes; a change is read and named.
|
||||
- [ ] 9.7 Docs: invariant 19 of `docs/models/plan-ladders-transitions.md` ("from a grant-held rung the only move offered is up, through Checkout") says that on a ladder a subscription pays for without holding, no tier is sold through Checkout, the switch of the paying subscription is offered at or above the grant and above the paid tier, and the paid tier resumes under a lower grant (sections 11 and 12 make both live); invariant 12 of `docs/models/payments-billing.md` (`:65`) says that Checkout refuses a ladder a subscription pays for whether or not the subscription holds it.
|
||||
|
||||
## 10. The paid plan's card, Cancel plan, Keep plan and Pay invoice (#269)
|
||||
|
||||
- [ ] 10.1 Sandbox check, before the code (design, What is unverified): on a Stripe sandbox test clock at the console's pinned API version, with the console's restricted test key, a subscription paused with `behavior=void` and the marker, set to cancel at the period end and then kept (`cancel_at_period_end=false`): Stripe accepts it, creates no invoice, and the pause and the marker stay. The result is recorded in the commit message; a refusal is a stop and goes to the maintainer.
|
||||
- [ ] 10.2 `internal/fulfillment/plan_change.go` (design D11): `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`, with the paying fallback through `ListSubscriptionRungsByOrg`, `holdsLadder`, and the status-derived suspension; every caller named in design D11 calls it. Its doc comment says which subscription it finds when no subscription backs the position. It chooses the paying subscription through the pure function 9.3 names, so the resolver and `payingByLadder` state the rule once.
|
||||
- [ ] 10.3 `internal/server/member_plans.go` (design D10): `buildTier`, for the card whose product is the ladder's `Paying.ProductID` on a ladder a grant holds, calls `setPaidUnderGrant(tier, ladderID, paying, granted)`, which sets `PaidUnderGrant`, `GrantedName`, `CollectionPaused`, the price line's facts (the subscription's own price from the paying row), `CanCancel`, `CanKeep`, `MovesTo`, `MovesOn` and `EndsOn` by D10's table, and `PaysInvoice` for `past_due` or `unpaid`; the current card's `setCurrent` defers to it when the current product is the paying product, and `buildTier` draws the paid card even when its product is not a public plan, as it draws the current and the held rungs (design D10). `setCancelBodies` gives the card's confirmation Copy M2 under a grant of another tier and M9 under a grant of the subscription's own tier, each followed by M7's sentence when the payment is due. `plansOfferPaidMove` (`:589-601`) counts a card with `PaidUnderGrant` and `PaysInvoice()` as well as a `current` card, so the billing facts show for the paid card's Pay invoice. The Note of Keep plan's action trigger (`internal/server/action_triggers.go:94-95`, "the current plan's control, …") is updated, because Keep plan is now drawn on the paid card. The comment at `:750-758` no longer says a grant-held tier has no billing.
|
||||
- [ ] 10.4 `internal/embeds/templates/partials/member_plans.html`: the price line reads M8 when `PaidUnderGrant`, `CollectionPaused` and a downgrade is scheduled, otherwise M0 or M1 when `PaidUnderGrant` and `CollectionPaused`, ahead of the existing branches; a scheduled cancellation keeps M0, its date on the ladder heading's existing badge; M1 draws no suspension line; the controls block draws Pay invoice, Keep plan and Cancel plan for a paid-under-grant card as for the current card. The template's comment states the card's states.
|
||||
- [ ] 10.5 `internal/server/member_hosted_invoice.go` (design D10): `planPosition` falls back to the paying subscription; `unpaidInvoicePage` lists the paying subscription's open invoices (`invoice.List` with `Subscription` and `Status: "open"`, limit 1) and redirects to the first one's hosted page. `internal/stripetest/mock.go` answers `GET /v1/invoices` from its existing `Invoices` map (keyed by invoice id, `mock.go:63-69`), listing the invoices whose subscription and status match the `subscription` and `status` parameters, with a doc comment. `internal/stripetest/testdata/routes.golden`, the row `the invoice list` (`:125-126`, which today records `error: stripetest: unexpected path /v1/invoices`), then records the list's answer; it is rewritten with `-update` and read, and no other row changes.
|
||||
- [ ] 10.6 Tests:
|
||||
- `TestMemberPlansGolden`: states `paid-plus-under-granted-pro` (section 9's, now with M0 and Cancel plan), `paid-plus-under-granted-pro-past-due` (M1, Pay invoice then Cancel plan, no suspension line), `paid-plus-under-granted-pro-unconfirmed` (no `PauseCollection`: the existing renews line), `paid-plus-under-granted-pro-cancellation-scheduled` (M0, Keep plan, and the heading's "cancels on" badge), `paid-plus-under-granted-pro-downgrade-scheduled` (the kit's `ScheduleDowngrade` to Basic before `Issue(o, pro)`: M8, Keep plan then Cancel plan), `paid-plus-paused-under-granted-pro` (status `paused`: M4, no control), and `granted-plus-own-tier` (`Subscribe(o, plus)`, `Issue(o, plus)`, `PauseCollection`: a grant of Plus over the Plus subscription, and the current card carries M0, "Paused while Plus is granted"); each state's `.html` and `.json` under `internal/server/testdata/member_plans/` written with `-update` and read, and `paid-plus-under-granted-pro.html` and `.json` rewritten. Plus is a tier of Wiki and Duo, so in every `paid-plus-*` state Duo's Plus card draws no line and no control, and Duo Max offers no Checkout. No golden shows the billing facts line: `TestMemberPlansGolden` empties `BillingFacts` before it renders (`member_plans_golden_db_test.go:303`).
|
||||
- `TestPlansOfferPaidMoveGate` (`internal/server/billing_facts_render_test.go:128`) gains the case `paidDue`, a paid-under-grant card whose payment is due and whose relation is not `current`, which earns the line. Failure text: `a paid card whose payment is due does not earn the line`.
|
||||
- `TestMemberPlansGolden`: a state `paid-retired-plus-under-granted-pro`, built in a world of its own so that the fixture's shared Plus is never retired: `w.Retire` sets `is_active = false` on the one product row (`internal/testkit/world/plans.go:191-203`), and `buildTier` skips an unlisted tier unless it is current or held (`internal/server/member_plans.go:399-402`), so retiring the shared Plus would drop its card from every other state where Plus is neither current nor held. The test makes a second `world.New` with its own Wiki ladder (Basic, Plus, Pro) and its own organization, its ids named through a normalizer as the first world's are, runs `Subscribe(o, plus)`, `Issue(o, pro)` and `PauseCollection`, then retires that world's Plus, and renders it as the subtest `paid-retired-plus-under-granted-pro`, keeping its ladders apart by that world's suffix as the page filter does (`member_plans_golden_db_test.go:296-301`). Plus's card is drawn with M0 and Cancel plan; `paid-retired-plus-under-granted-pro.html` and `.json` written with `-update` and read.
|
||||
- The `.json` of each of the 22 states that predate section 9 (every `.json` under `internal/server/testdata/member_plans/` at section 9's commit but `paid-plus-under-granted-pro.json`) is rewritten with `-update` and read; each gains only `PaidUnderGrant`, `GrantedName` and `CollectionPaused` at their zero values, and none of those states' `.html` changes; any other diff is a stop.
|
||||
- `TestPaidPlanCardUnderAGrant` (`internal/server/member_plans_paid_under_grant_test.go`, no database), rows per D10 state, among them `unconfirmed`, `downgrade scheduled` and `cancellation scheduled`, comparing the price line's whole text and the controls with the Copy table. Failure text: `%s: price line %q and controls %v, want %q and %v`.
|
||||
- `TestCancelAPausedSubscription` (`internal/fulfillment/plan_change_paid_under_grant_test.go`): `CancelSubscription` at the period end sends `cancel_at_period_end=true` and no `pause_collection`, records the scheduled cancellation and reconciles. The form and the function's error are asserted in one check. Failure text: `cancel call form = %v (error %v), want cancel_at_period_end and no pause change`.
|
||||
- `TestKeepAPausedSubscription`: `KeepCurrentPlan` clears the flag, supersedes the row, and sends no `pause_collection`. Failure text: `keep call form = %v`.
|
||||
- `TestAPastDuePayingSubscriptionIsNotCancelledImmediately`: the immediate cancellation is refused with `ErrImmediateCancelSuspended` before any Stripe call. Failure text: `an immediate cancellation of a past-due paying subscription = %v`.
|
||||
- `TestPlanUnpaidInvoiceForAPausedPlan` (`internal/server/member_hosted_invoice_db_test.go`), rows: `past due with an open invoice` (303 to the mock's hosted URL); `active` (303 to `/billing`, no Stripe call); `no open invoice` (303 to `/billing`); `another organization's ladder` (404). Failure text: `%s: answered %d %q, want %d %q`.
|
||||
- `TestCancelBodyOnThePaidCard`, rows: `a grant of another tier` (M2 with the period end); `a grant of the subscription's own tier` (M9); `a grant of another tier, payment due` (M7 over M2: "Plus ends on Jan 15, 2099; Pro stays granted. The unpaid invoice stays due."); `the own tier, payment due` (M7 over M9). Failure text: `%s: cancel body = %q, want %q`.
|
||||
- [ ] 10.7 Docs: `docs/stripe.md`'s grant bullet names the paid plan's card, Cancel plan at the period end and Pay invoice; `docs/plan-management.md` says what the member sees.
|
||||
- [ ] 10.8 Breaks:
|
||||
- the mirror ignored (the rule's answer used for `CollectionPaused`): caught by `TestPaidPlanCardUnderAGrant`, `want_new` `unconfirmed: price line`, and by `TestMemberPlansGolden/paid-plus-under-granted-pro-unconfirmed`;
|
||||
- M1's suspension line drawn: caught by `TestMemberPlansGolden/paid-plus-under-granted-pro-past-due`, `want_new` `testdata/member_plans/paid-plus-under-granted-pro-past-due.html differs from what the code produced`;
|
||||
- the resolver's fallback removed: caught by `TestCancelAPausedSubscription`, `want_new` `cancel call form =`;
|
||||
- the fallback's suspension taken from a position (none): caught by `TestAPastDuePayingSubscriptionIsNotCancelledImmediately`, `want_new` `an immediate cancellation of a past-due paying subscription =`;
|
||||
- the invoice route reading `latest_invoice` for a paying subscription: caught by `TestPlanUnpaidInvoiceForAPausedPlan`, `want_new` `past due with an open invoice: answered`;
|
||||
- the status gate dropped for a paying subscription: caught by the same, `want_new` `active: answered`;
|
||||
- M2's body as the existing body: caught by `TestCancelBodyOnThePaidCard`, `want_new` `a grant of another tier: cancel body =`;
|
||||
- M2 used under a grant of the subscription's own tier: caught by the same, `want_new` `a grant of the subscription's own tier: cancel body =`;
|
||||
- M7's sentence dropped: caught by the same, `want_new` `a grant of another tier, payment due: cancel body =`;
|
||||
- the paid card's Pay invoice not counted in `plansOfferPaidMove`: caught by `TestPlansOfferPaidMoveGate`, `want_new` `a paid card whose payment is due does not earn the line`;
|
||||
- the paid card skipped when its product is not listed: caught by `TestMemberPlansGolden/paid-retired-plus-under-granted-pro`, `want_new` `testdata/member_plans/paid-retired-plus-under-granted-pro.html differs from what the code produced`;
|
||||
- M8 not drawn (a scheduled downgrade reads M0): caught by `TestPaidPlanCardUnderAGrant`, `want_new` `downgrade scheduled: price line`, and by `TestMemberPlansGolden/paid-plus-under-granted-pro-downgrade-scheduled`, `want_new` `testdata/member_plans/paid-plus-under-granted-pro-downgrade-scheduled.html differs from what the code produced`.
|
||||
- [ ] 10.9 `make screens`: no demo state reaches the paid card; hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the Products page in the states `paid-plus-under-granted-pro`, its past-due form, its cancellation-scheduled form (Keep plan and the badge), its downgrade-scheduled form (M8), its unconfirmed form, `granted-plus-own-tier` (a grant of the subscription's own tier), and the cancellation's confirmation in its M2 and M9 forms, on the test stack with the kit's states loaded, are attached to the commit's review.
|
||||
|
||||
## 11. The switch of a paused subscription (#278)
|
||||
|
||||
- [ ] 11.1 Sandbox check, before the code (design D12, What is unverified): on a Stripe sandbox test clock at the pinned version, with the restricted test key: (a) a subscription paused with the marker, then one update carrying `items`, `proration_behavior=always_invoice`, `proration_date`, `payment_behavior=pending_if_incomplete`, `pause_collection=` and `metadata[member_console_collection]=`; (b) the same on a second subscription whose default payment method declines (`pm_card_chargeCustomerFail`), reading whether the clear is held pending with the item; (c) `invoice.CreatePreview` for the paused subscription with the new item and `subscription_details[proration_behavior]=always_invoice`, recording its `amount_due` and comparing it with the total of the one-update switch's proration invoice on the same clock (200 in the sandbox); (d) if (a) is refused, the same update with `payment_behavior=error_if_incomplete`, which keeps one atomic update and loses the approval path. The results are recorded in the commit message and fix the preview's form. If (a) is refused, both fallbacks, `error_if_incomplete` and the two-call form, go to the maintainer before item 11.2.
|
||||
- [ ] 11.2 `internal/fulfillment/plan_change.go`: `upgradeNow` gains `clearPause bool`, set from the subscription `upgradeNow` fetches first (`:292`) alone: true when it carries the console's pause or a stale marker, whatever holds the ladder, because a subscription that holds its ladder is delivering and clearing its pause is correct; the clear's two parameters ride the one update (with the `payment_behavior` 11.1 and, on a refusal of (a), the maintainer settle), or, if the maintainer picks the two-call form, a separate clear call precedes the unchanged upgrade, its doc comment saying why; in the two-call form, a declined or approval-pending upgrade calls `ReconcileSubscription` (design D12). The preview's form is fixed once, at build time, by 11.1(c): if Stripe refuses the preview or its figure differs from the update's, `PreviewSwitch` returns the unavailable preview for a subscription carrying the console's pause, which it reads from the resolved row's mirror (`ls.sub.PauseCollectionBehavior` set and `ls.sub.PauseCollectionMarked`, carried by `GetSubscriptionByID` from section 2), because it fetches no subscription, and the confirmation uses the existing fallback sentence; if the figures are equal, it returns Stripe's figure, and a refusal by Stripe at run time still gives the unavailable preview.
|
||||
- [ ] 11.3 `internal/server/member_plan_moves.go`: `planMoveMessage` takes `replacesGrant bool`; with it the second paragraph opens "Your subscription replaces the grant." (Copy M3); `GetSwitchPreview` and `PostSwitch` pass it when the offer's position has `Paying` with `GrantHolds`. `plans.Offer` rule 3a item 2 answers Switch in place of section 9's none, with relation `Upgrade` set by the rule itself, because `Offer` sets the current product's relation to `Downgrade` (`offer.go:210`). The granted tier's current card draws the switch through three changes: `buildTier` reads the current card's default price when `pos.Paying` has `GrantHolds` (it builds the current card's target with no price, `member_plans.go:424-428`, so `Offer`'s price rule would answer `NoPrice` and the control would read "Not available for purchase yet"); the current card carries the fields `setMove` sets (`member_plans.go:478-495`), `Relation` kept "current", because without `MoveEnabled` the template draws the control disabled and `plansOfferPaidMove` does not count it (`member_plans.go:593-601`); and the template draws the switch markup inside the current branch (it draws move controls only under `{{ if ne .Relation "current" }}`, `member_plans.html:124`), labelled with the existing "Upgrade" (Copy M6).
|
||||
- [ ] 11.4 Tests:
|
||||
- `TestSwitchAPausedSubscription_OneUpdate` (`internal/fulfillment/plan_change_paid_under_grant_test.go`): the switch to Max sends one update whose form holds the item, `always_invoice`, `pause_collection=` and `metadata[member_console_collection]=`; the reconcile confers Max over the grant. Failure texts: `switch call form = %v, want the item, the clear and the marker removed`; `after the switch, the ladder holds %v, want Max`.
|
||||
- `TestSwitchAPausedSubscription_ToTheGrantedTier`: Pro, a transfer; the grant recorded as replaced by S. Failure text: `the grant is not recorded as replaced by the subscription`.
|
||||
- `TestSwitchAPausedSubscription_ADeclineLeavesItPaused`: the mock answers the update with the pending update (`pending_update` set, the invoice open); the abandoned invoice is voided, the subscription keeps Plus, and no conferral is written. Failure text: `a declined switch changed the ladder: %v`.
|
||||
- `TestSwitchAPausedSubscription_AForeignPauseIsNotCleared`: no `pause_collection` parameter is sent and Stripe's 400 answers the generic failure. Failure text: `a foreign pause was cleared by the switch: %v`.
|
||||
- `TestSwitchAPausedSubscription_AHoldingSubscriptionStillPausedClearsIt`: S holds its ladder again and the mock's subscription still carries the console's pause; its upgrade sends the clear and the marker's removal. Failure text: `a holding subscription's upgrade sent no clear: %v`.
|
||||
- `TestSwitchAPausedSubscription_AnOrdinaryUpgradeSendsNoClear`: an upgrade of a subscription whose Stripe object carries no pause sends no `pause_collection`. Failure text: `an ordinary upgrade sent the clear: %v`.
|
||||
- `TestSwitchAPausedSubscription_AMarkedGrantResumesWhenItEnds`: a grant marked to resume is replaced by the switch, and when S later ends within the grant's term the grant holds the ladder again. Failure text: `after S ended, the marked grant holds %v, want its product`.
|
||||
- `TestPreviewSwitchOfAPausedSubscription`, in the form 11.1(c) found. Unavailable (Stripe refused the preview, or its figure differs from the update's charge): `PreviewSwitch` of a subscription carrying the console's pause returns the unavailable preview. Equal: it returns the mock's figure. Failure text: `paused preview = %+v, want unavailable` (equal form: `paused preview = %+v, want the mock's figure`).
|
||||
- `TestOffer` rows (`internal/plans/offer_test.go`): `a tier above a grant that displaced a subscription` (a switch, enabled, relation Upgrade); `the granted tier over a paying subscription` (a switch, enabled, relation Upgrade); `a tier above the paid tier over a lower grant` (a switch, enabled, relation Upgrade); `the granted tier below the paid tier` (none, reason `Current`). Failure text unchanged.
|
||||
- `TestPlanMoveMessageStatesTheTiming` (`internal/server/plan_move_message_test.go`) row `replaces the grant` equals M3's whole text with an amount, and its fallback row with the prorated-difference sentence. Failure text unchanged.
|
||||
- `TestPostSwitchFromAPausedSubscription` (`internal/server/member_switch_offer_db_test.go`): the posted switch to Max answers the submitted message, and to Plus answers the unavailable-plan sentence. Failure text: `%s: answered %q, want %q`.
|
||||
- `TestMemberPlansGolden`, six states rewritten with `-update` and read, the `.html` and `.json` of each under `internal/server/testdata/member_plans/`, because rule 3a item 2 has no condition on `ConsolePaused` or `MoveScheduled`: `paid-plus-under-granted-pro`, `paid-plus-under-granted-pro-unconfirmed`, `paid-plus-under-granted-pro-cancellation-scheduled`, `paid-plus-under-granted-pro-downgrade-scheduled` and `paid-retired-plus-under-granted-pro`, in each of which Pro's current card draws "Upgrade" and Standard ranks below the granted Pro and draws nothing (the retired state's own ladder, Basic, Plus and Pro, has no Standard); and `granted-plus-own-tier`, in which Standard's and Pro's cards on Wiki, and Duo Max's card on Duo, draw "Upgrade", because the fixture's Plus grant holds both ladders. Each named card's `.json` gains the switch's move fields. `paid-plus-under-granted-pro-past-due` and `paid-plus-paused-under-granted-pro` do not change, because their subscription is suspended.
|
||||
- No other state's `.html` or `.json` changes: `TierViewModel` already carries every field `setMove` sets (`internal/server/member_plans.go:108-139`), so the current card's move adds no field; any other diff is a stop.
|
||||
- `TestProductsPageReadsPayingOnce` passes unedited: its fixture holds no ladder a grant holds against a paying subscription, so 11.3's read of the current card's default price, `computePriceReadiness`'s statements once per such ladder (`internal/server/plan_offer.go:238-261`), adds nothing to its count.
|
||||
- [ ] 11.5 Docs: `docs/stripe.md`, "Plan changes", gains the paused switch: one update that changes the item and clears the pause, why Stripe needs both in one update, and that its proration credits the unused time of the period whose renewal was voided.
|
||||
- [ ] 11.6 Breaks:
|
||||
- the clear not sent: caught by `TestSwitchAPausedSubscription_OneUpdate`, `want_new` `switch call form =`;
|
||||
- the clear sent for a foreign pause: caught by `TestSwitchAPausedSubscription_AForeignPauseIsNotCleared`, `want_new` `a foreign pause was cleared`;
|
||||
- the clear sent when Stripe carries no console pause: caught by `TestSwitchAPausedSubscription_AnOrdinaryUpgradeSendsNoClear`, `want_new` `an ordinary upgrade sent the clear`;
|
||||
- the clear withheld from a subscription that holds its ladder (`clearPause` also tested on the ladder): caught by `TestSwitchAPausedSubscription_AHoldingSubscriptionStillPausedClearsIt`, `want_new` `a holding subscription's upgrade sent no clear`;
|
||||
- in the unavailable form, the preview returning Stripe's figure for a paused subscription; in the equal form, the preview returning the unavailable preview: caught by `TestPreviewSwitchOfAPausedSubscription`, `want_new` `paused preview =`;
|
||||
- the marked grant not recorded as replaced: caught by `TestSwitchAPausedSubscription_AMarkedGrantResumesWhenItEnds`, `want_new` `after S ended, the marked grant holds`;
|
||||
- rule 3a applied after rule 3: caught by `TestOffer`, `want_new` `Offer(the granted tier over a paying subscription) =`;
|
||||
- the paid-tier rank test dropped (a tier between a lower grant and the paid tier is a switch): caught by `TestOffer`, `want_new` `Offer(a tier between a lower grant and the paid tier) =`;
|
||||
- the suspension test dropped: caught by `TestOffer`, `want_new` `Offer(a past-due paying subscription) =`;
|
||||
- `replacesGrant` ignored: caught by `TestPlanMoveMessageStatesTheTiming`, `want_new` `replaces the grant`;
|
||||
- section 8's exception removed for the switch's product: caught by `TestSwitchAPausedSubscription_OneUpdate`, `want_new` `after the switch, the ladder holds`;
|
||||
- a paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted from `switchOffer`, 9.3): caught by `TestPostSwitchFromAPausedSubscription`, `want_new` `answered "There's no active subscription`.
|
||||
- [ ] 11.7 `make screens`: no demo state reaches the switch; hand captures at both widths of the switch's confirmation from the paused subscription (M3) are attached to the commit's review.
|
||||
|
||||
## 12. Resume plan when the grant ranks below the paid tier
|
||||
|
||||
- [ ] 12.1 `internal/plans/offer.go` (design D20): the kind `Resume Kind = "resume"`, whose doc comment says the paying subscription takes the ladder back from a lower grant at its own price; rule 3a item 1 answers Resume, enabled, relation `Upgrade`, when `GrantHolds`, the held rung ranks below `Paying.Rank`, not `Suspended`, `ConsolePaused`, not `MoveScheduled`, and not `OtherLadders`, and none, reason `PaidHere`, otherwise, with no price rule and no member gate, as Keep plan applies none; the rules' doc comment states item 1's conditions and why each holds.
|
||||
- [ ] 12.2 Query: `GetSubscriptionResumeFacts` (`internal/entitlements/queries/`, new: a subscription's `status`, `cancel_at_period_end`, `pause_collection_behavior`, `pause_collection_marked`, and `EXISTS` a `core.subscription_scheduled_changes` row of it whose status is `scheduled`). `make sqlc-generate`.
|
||||
- [ ] 12.3 `internal/entitlements/subscription_resume.go` (new): `ResumeSubscriptionInput{PoolID, LadderID, SubscriptionID, Reason string}`, the refusals `ErrSubscriptionHoldsLadder`, `ErrResumeSuspended`, `ErrResumePaused` and `ErrResumeRefused`, and `ResumeSubscription(ctx, db, in) error`, which runs design D20's seven steps in one `BeginMaterializing` transaction, `LockPools` before any read, each refusal before any write, the conferral through `Confer` (actor `system`, reason `member:resume`, the summed quantity), then `RequestPoolSubscriptionReconciles(ctx, tx, poolID, "")`, then `MaterializePoolEntitlements(ctx, q, poolID)`, because `BeginMaterializing` does not materialize at commit; it refuses a draft product alone. Its doc comment says why it takes no subscription advisory lock and why it makes no Stripe call (design D20).
|
||||
- [ ] 12.4 `internal/fulfillment/plan_change.go`: `ResumePlan(ctx, db, logger, keyMode, orgID, ladderID, reason string) error` resolves through `resolveSubscriptionOnLadder`, answers `ErrSameTier`, `ErrSubscriptionSuspended`, `ErrSubscriptionPaused` or `ErrPriceUnreachable` before any write as design D20 states, calls `entitlements.ResumeSubscription` through the package variable `resumeSubscription`, which holds it and is `TestResumePlan_MapsTheActsRefusals`'s seam, as its doc comment says, and maps its refusals to `ErrSameTier`, `ErrSubscriptionSuspended`, `ErrSubscriptionPaused` and the new `fulfillment` error `ErrResumeUnavailable` for `entitlements.ErrResumeRefused`. It calls no `ReconcileSubscription`: the outbox entry the act wrote runs the reconcile.
|
||||
- [ ] 12.5 `internal/server/member_plan_moves.go`: `PostResume` and `resumeOfferFor` as design D20 states, `resumeOfferFor` answering, in this order: no `Paying` while a subscription backs the held position, `ErrSameTier`; no `Paying` otherwise, `ErrNoActivePaidSubscription`; a suspended `Paying`, `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`; any other refusal, `errPlanNotOffered`; `member_plans.go`'s `RegisterRoutes` gains `POST /partials/member/plans/resume`; `internal/server/action_triggers.go` declares it (`{Label: "Resume plan", Method: "POST", Path: "/partials/member/plans/resume", Modal: true}`); `renderPlansAfterMove` answers `ErrResumeUnavailable` with the unavailable-plan sentence, and the action `resume` shows no banner, its comment saying why, as `keep`'s does. `internal/server/testdata/routes.golden` and `routes-not-ready.golden` gain the `POST /partials/member/plans/resume` line, rewritten with `-update` and read.
|
||||
- [ ] 12.6 `internal/server/member_plans.go` and the template: `setPaidUnderGrant` sets `CanResume`, `ResumeTitle` and `ResumeBody` (Copy M10, M11) from the paid card's move, built from the subscription's own price by `recurringPhrase`; `buildTier` hands the paid card's move to it and never to `setMove`; `plansOfferPaidMove` counts a card with `CanResume`. `member_plans.html` draws Resume plan before Cancel plan on a paid-under-grant card through `#confirmActionModal` (`data-action-url="/partials/member/plans/resume"`, `data-action-method="post"`, `data-action-target="#member-plans"`, `data-action-title` M11's heading, `data-action-body` M11's body, `data-action-confirm-label="Resume plan"`, `data-action-style="primary"`, `data-action-fields` with `ladder_id`), with `aria-describedby` on the billing line when it is shown, the markup copied from Cancel plan's (`member_plans.html:112-121`); the template's comment on the card's states names Resume plan.
|
||||
- [ ] 12.7 Tests:
|
||||
- `TestOffer` rows (`internal/plans/offer_test.go`): `the paid tier above a lower grant` (Resume, enabled, relation Upgrade); `the paid tier above a lower grant, past due` (none, PaidHere); `the paid tier above a lower grant, no console pause` (none, PaidHere); `the paid tier above a lower grant, a move scheduled` (none, PaidHere); `the paid tier above a lower grant, retired` (Resume, enabled, relation Upgrade); `the paid tier above a lower grant, the default holding the rung` (none, PaidHere); `the paid bundle above a lower grant` (none, PaidHere); `the paid tier under a grant of its own tier` (none, PaidHere); `the paid tier below the grant` (none, PaidHere). Each refusal row is the enabled row `the paid tier above a lower grant` with exactly one fact changed, so that each break of 12.8 meets only its own condition. Failure text unchanged.
|
||||
- `TestResumeSubscription_TakesTheLadderFromTheGrant` (`internal/entitlements/subscription_resume_db_test.go`): the kit's ladder of Basic, Plus, Pro and Max; `Subscribe(o, pro)`, `Issue(o, basic)`, `PauseCollection`; the act confers Pro sourced by the subscription as an upgrade with actor `system` and reason `member:resume`, `core.grant_replacements` pairs the grant with the subscription, and one `reconcile_subscription` entry is written per live subscription of the organization, in id order, and the pool's materialized entitlements equal Pro's. Failure texts: `after the resume, the ladder holds %v, want Pro by the subscription`; `the grant is not recorded as replaced by the subscription`; `the resume wrote entries for %v, want %v`; `after the resume, the pool's entitlements = %v, want Pro's`.
|
||||
- `TestResumeSubscription_Refusals`, rows through `checkResumeRefusal`: `no pause recorded`; `a pause made in the Dashboard` (`ForeignPause`); `a marker with no pause`; `a grant of the paid tier`; `a grant above the paid tier`; `held by another subscription`; `a cancellation scheduled` (`CancelAtPeriodEnd`); `a downgrade scheduled` (`ScheduleDowngrade`); `past due` (`Suspend`); `paused` (`Suspend`); `canceled` (`EndSubscription`); `a bundle`; `the product drafted` (`Draft`). Each answers its row's refusal and writes no position, no transition and no outbox entry. Failure text: `%s: resume = %v, want %v, with nothing written`.
|
||||
- `TestResumeSubscription_OverABundleGrantEndsItOnItsOtherLadder`: the grant's product is a tier of two ladders; after the resume the grant's other ladder holds nothing and no default is conferred there (F60). Failure text: `after the resume over a bundle grant, the other ladder holds %v, want nothing`.
|
||||
- `TestResumeSubscription_ASecondSubmitConfersOnce`: two calls in sequence; the second answers `ErrSubscriptionHoldsLadder`, and the ladder has one upgrade transition by the subscription. Failure text: `a second resume = %v with %d transitions, want the holds refusal and 1`.
|
||||
- `TestResumeSubscription_AnEndingActFirst`, rows `revocation` and `expiry`: a transaction runs `RevokeGrantTx` or `ExpireGrantTx` and stays open; the resume waits for the pool row (`dbtest.AwaitLockWait`), and `pg_locks` shows no advisory lock for the subscription while it waits; after the commit, which delivers the subscription (section 7), the resume answers `ErrSubscriptionHoldsLadder` and writes nothing. Failure texts: `after a concurrent %s, resume = %v, want the holds refusal`; `the resume took the subscription's advisory lock`.
|
||||
- `TestResumeSubscription_AMarkedGrantResumesWhenTheSubscriptionEnds`: the grant marked to resume; the resume; then the subscription ends (`EndSubscription` and its reconcile); the ladder holds the grant's Basic again. Failure text: `after the subscription ended, the ladder holds %v, want the marked grant's Basic`.
|
||||
- `TestResumePlan_MakesNoStripeCall` (`internal/fulfillment/plan_change_paid_under_grant_test.go`): `ResumePlan` sends no request to the Stripe mock; `ApplySubscriptionCollection` on the entry it wrote then sends one update whose form holds `pause_collection=` and `metadata[member_console_collection]=` and no `items`. Failure texts: `resume sent %v to Stripe, want nothing`; `the clear after the resume = %v, want the clear alone`.
|
||||
- `TestResumePlan_RefusesAnUnreachableMapping`: the subscription mapped for the other key mode; `ErrPriceUnreachable`, nothing written. Failure text: `resume over an unreachable mapping = %v, want ErrPriceUnreachable`.
|
||||
- `TestResumePlan_MapsTheActsRefusals` (same file): on a subscription `ResumePlan`'s own checks pass, the test sets `resumeSubscription` to a function that returns one `entitlements` refusal, one row per refusal of the design's D20 table, and `ResumePlan` answers its `fulfillment` error; `ResumePlan`'s checks and the decision refuse the holds, suspended and paused cases first, so the database alone reaches these mappings only in a race. Failure text: `%s: ResumePlan = %v, want %v`. `renderPlansAfterMove` gains a row for `ErrResumeUnavailable` (the unavailable-plan sentence), beside `TestMemberPlansSuccessBannerAndCancelsOnBadge` (`internal/server/member_upgrade_render_test.go`).
|
||||
- `TestResumePlan_AFailedClearKeepsTheLadder`: the mock refuses the clear with a 500; `ApplySubscriptionCollection` returns the error, the ladder still holds Pro by the subscription, and `collectionDrift` over the recorded rows names the subscription (not wanted, the marker recorded). Failure text: `after a failed clear, the ladder holds %v and drift is %v`.
|
||||
- `TestPostResume` (`internal/server/member_resume_db_test.go`), rows through `checkPostResume`: `resumes` (the partial draws Pro as the current card, no banner, `HX-Trigger` set); `past due` ("Pay the unpaid invoice before changing this plan."); `paused` ("A paused plan cannot be changed."); `already resumed` ("You're already on that plan."); `a cancellation scheduled` (the unavailable-plan sentence); `a product no longer public` (resumes, as for a listed product: no member gate applies); `held by another subscription` (the kit's second `Subscribe` on the ladder holds the rung over the paying subscription: the unavailable-plan sentence); `no paying subscription` ("There's no active subscription to change on this plan."). Failure text: `%s: answered %q, want %q`.
|
||||
- `TestPaidPlanCardUnderAGrant` rows: `a lower grant` (M0, controls Resume plan then Cancel plan); `a lower grant, unconfirmed` (M5, Cancel plan alone); `a lower grant, downgrade scheduled` (M8, Keep plan then Cancel plan). Failure text unchanged.
|
||||
- `TestResumeConfirmation` (`internal/server/member_plans_paid_under_grant_test.go`, no database): the card's `ResumeTitle` and `ResumeBody` equal M11 with the subscription's price. Failure text: `resume confirmation = %q, %q, want %q, %q`.
|
||||
- `TestMemberPlansGolden`: a state `paid-standard-under-granted-basic` (`Subscribe(o, standard)`, `Issue(o, basic)`, `PauseCollection`), goldens `internal/server/testdata/member_plans/paid-standard-under-granted-basic.html` and `.json` written with `-update` and read: Standard reads M0 with Resume plan and Cancel plan; Basic (current) and Plus draw nothing; Pro draws Upgrade.
|
||||
- `TestPlansOfferPaidMoveGate` gains the case `resumes`, a region whose only money move is a paid card's enabled Resume, which earns the line. Failure text: `an enabled Resume does not earn the line`.
|
||||
- The `.json` of each of the 30 states that predate this section (every `.json` under `internal/server/testdata/member_plans/` at section 11's commit) is rewritten with `-update` and read; each gains only `CanResume`, `ResumeTitle` and `ResumeBody` at their zero values, and none of those states' `.html` changes, because none has a grant ranked below its paid tier; any other diff is a stop.
|
||||
- `TestEveryMutationRouteIsDeclared` passes with the declaration.
|
||||
- [ ] 12.8 Breaks:
|
||||
- the rank test dropped from item 1: caught by `TestOffer`, `want_new` `Offer(the paid tier under a grant of its own tier) =`;
|
||||
- the console-pause test dropped from item 1: caught by the same, `want_new` `Offer(the paid tier above a lower grant, no console pause) =`;
|
||||
- the scheduled-move test dropped from item 1: caught by the same, `want_new` `Offer(the paid tier above a lower grant, a move scheduled) =`;
|
||||
- the bundle test dropped from item 1: caught by the same, `want_new` `Offer(the paid bundle above a lower grant) =`;
|
||||
- item 1's suspension test dropped: caught by `TestOffer`, `want_new` `Offer(the paid tier above a lower grant, past due) =`;
|
||||
- item 1's `GrantHolds` test dropped: caught by `TestOffer`, `want_new` `Offer(the paid tier above a lower grant, the default holding the rung) =`;
|
||||
- the act's status test dropped: caught by `TestResumeSubscription_Refusals`, `want_new` `past due: resume =`;
|
||||
- the resume's materialization dropped: caught by `TestResumeSubscription_TakesTheLadderFromTheGrant`, `want_new` `after the resume, the pool's entitlements =`;
|
||||
- the act's refusal mapping dropped from `ResumePlan`: caught by `TestResumePlan_MapsTheActsRefusals`, `want_new` `: ResumePlan =`;
|
||||
- the act's marker test dropped (a behavior alone passes): caught by `TestResumeSubscription_Refusals`, `want_new` `a pause made in the Dashboard: resume =`;
|
||||
- the act's rank test dropped: caught by the same, `want_new` `a grant of the paid tier: resume =`;
|
||||
- the act's scheduled-change read dropped (`cancel_at_period_end` alone tested): caught by the same, `want_new` `a downgrade scheduled: resume =`;
|
||||
- the act's holds test dropped: caught by `TestResumeSubscription_ASecondSubmitConfersOnce`, `want_new` `a second resume =`;
|
||||
- the act's request dropped: caught by `TestResumeSubscription_TakesTheLadderFromTheGrant`, `want_new` `the resume wrote entries for`;
|
||||
- the act's reads moved above `LockPools`: caught by `TestResumeSubscription_AnEndingActFirst`, `want_new` `after a concurrent revocation, resume =`;
|
||||
- the reachability test dropped from `ResumePlan`: caught by `TestResumePlan_RefusesAnUnreachableMapping`, `want_new` `resume over an unreachable mapping =`;
|
||||
- the trigger's declaration removed: caught by `TestEveryMutationRouteIsDeclared`, `want_new` `is neither a registered form's path nor a declared action trigger`;
|
||||
- the confirmation's first sentence dropped: caught by `TestResumeConfirmation`, `want_new` `resume confirmation =`;
|
||||
- the control not drawn (`CanResume` ignored by the template): caught by `TestMemberPlansGolden/paid-standard-under-granted-basic`, `want_new` `testdata/member_plans/paid-standard-under-granted-basic.html differs from what the code produced`;
|
||||
- `CanResume` not counted in `plansOfferPaidMove`: caught by `TestPlansOfferPaidMoveGate`, `want_new` `an enabled Resume does not earn the line`;
|
||||
- the handler's decision gate dropped (`PostResume` calling `ResumePlan` directly): caught by `TestPostResume`, `want_new` `held by another subscription: answered`.
|
||||
- Unseen by any test of the section, named in the commit message: the supersession of a bundle grant's other ladder, which `core.confer` owns, so no line of the act can be broken to change it (`TestResumeSubscription_OverABundleGrantEndsItOnItsOtherLadder` pins the outcome).
|
||||
- [ ] 12.9 Docs: `docs/stripe.md`'s grant bullet says that under a grant ranked below the paid tier the member resumes the paid tier at its own price, that the console then clears the pause through the outbox, and that nothing is charged until the next renewal, so the rest of a period whose renewal was voided is free, up to one whole period (nearly a year on an annual price), at a moment the member picks, the end edge's cost of design D14; `docs/plan-management.md` says what the member sees on the paid card; `docs/models/plan-ladders-transitions.md` invariant 20 says that the member's Resume plan supersedes a lower grant and is the one act that takes a ladder back for the product a grant displaced; `docs/database-locks.md` gains Resume plan's transaction under the pool row, with no subscription advisory lock (design, Locks and transactions).
|
||||
- [ ] 12.10 `make screens`: no demo state reaches the paid card; hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the Products page in `paid-standard-under-granted-basic`, of the Resume confirmation (M11), and of the page after the resume, on the test stack with the kit's states loaded, are attached to the commit's review.
|
||||
|
||||
## 13. Landing
|
||||
|
||||
- [ ] 13.1 `make test` on section 12's tree with the test stack up passes; `openspec validate grant-pauses-subscription-billing --strict` passes.
|
||||
- [ ] 13.2 Every section's break list reads CAUGHT or names its unseen breaks with the reason in its commit message; items 10.1 and 11.1 are recorded in theirs.
|
||||
- [ ] 13.3 The read-only count (design D19), run before the push that deploys, on each deployment's database as `console_reader` (`docs/database-management.md`, "The `console_reader` role"); the result goes to the maintainer and nothing is fixed by hand. The count has two forms, because a deployment whose schema predates `00034` has no `core.subscription_displacements`: run `SELECT to_regprocedure('core.subscription_displacements(uuid,uuid)') IS NULL;` first, and use the inline form when it answers true, the function form otherwise.
|
||||
|
||||
The function form:
|
||||
|
||||
```sql
|
||||
-- Live subscriptions displaced by a grant on a ladder one of their current items names.
|
||||
SELECT count(DISTINCT s.subscription_id)
|
||||
FROM core.subscriptions s
|
||||
JOIN core.accounts a ON a.billing_account_id = s.billing_account_id
|
||||
JOIN core.resource_pools rp ON rp.org_id = a.org_id AND rp.pool_type = 'default' AND rp.status = 'active'
|
||||
CROSS JOIN LATERAL core.subscription_displacements(s.subscription_id, rp.pool_id)
|
||||
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)
|
||||
WHERE s.status IN ('active', 'trialing', 'past_due', 'unpaid')
|
||||
AND d.holder_source = 'grant';
|
||||
```
|
||||
|
||||
The inline form, for a schema that predates `00034`. It inlines the pairs view and the function's rule, with `grants.grant_reason = 'default'` standing in for `default_sourced`:
|
||||
|
||||
```sql
|
||||
WITH pairs AS (
|
||||
SELECT e.pool_id, e.plan_ladder_id, e.effective_at,
|
||||
e.provision_id AS ended_provision_id, n.provision_id AS successor_provision_id
|
||||
FROM core.pool_provision_transitions e
|
||||
JOIN core.pool_provision_transitions n
|
||||
ON n.pool_id = e.pool_id AND n.plan_ladder_id = e.plan_ladder_id
|
||||
AND n.effective_at = e.effective_at AND n.actor_type = e.actor_type
|
||||
AND n.actor_id IS NOT DISTINCT FROM e.actor_id
|
||||
WHERE e.transition_type = 'end'
|
||||
AND n.transition_type IN ('initiate','upgrade','downgrade','transfer')
|
||||
AND n.from_rank IS NOT NULL
|
||||
),
|
||||
latest AS (
|
||||
SELECT DISTINCT ON (p.subscription_id, l.plan_ladder_id)
|
||||
p.subscription_id, l.pool_id, l.plan_ladder_id, l.provision_id, l.status, l.ended_at
|
||||
FROM core.pool_provision_ladders l
|
||||
JOIN core.pool_provisions p ON p.provision_id = l.provision_id
|
||||
WHERE p.subscription_id IS NOT NULL
|
||||
ORDER BY p.subscription_id, l.plan_ladder_id, l.activated_at DESC, l.provision_ladder_id DESC
|
||||
),
|
||||
displaced AS (
|
||||
SELECT lt.* FROM latest lt
|
||||
WHERE lt.status = 'ended'
|
||||
AND EXISTS (SELECT 1 FROM pairs sp
|
||||
JOIN core.pool_provisions succ ON succ.provision_id = sp.successor_provision_id
|
||||
WHERE sp.pool_id = lt.pool_id AND sp.plan_ladder_id = lt.plan_ladder_id
|
||||
AND sp.ended_provision_id = lt.provision_id AND sp.effective_at = lt.ended_at
|
||||
AND succ.subscription_id IS DISTINCT FROM lt.subscription_id)
|
||||
)
|
||||
SELECT count(DISTINCT s.subscription_id)
|
||||
FROM displaced d
|
||||
JOIN core.subscriptions s ON s.subscription_id = d.subscription_id
|
||||
JOIN core.pool_provision_ladders h
|
||||
ON h.pool_id = d.pool_id AND h.plan_ladder_id = d.plan_ladder_id
|
||||
AND h.status IN ('active','suspended')
|
||||
JOIN core.pool_provisions hp ON hp.provision_id = h.provision_id
|
||||
LEFT JOIN core.grants hg ON hg.grant_id = hp.grant_id
|
||||
WHERE s.status IN ('active', 'trialing', 'past_due', 'unpaid')
|
||||
AND hp.grant_id IS NOT NULL
|
||||
AND hp.subscription_id IS DISTINCT FROM d.subscription_id
|
||||
AND hg.grant_reason IS DISTINCT FROM 'default';
|
||||
```
|
||||
|
||||
The tracked text names no deployment.
|
||||
- [ ] 13.4 The console sandbox walk, on the test stack with the app built from section 12's tree, Stripe sandbox and test keys, `stripe listen` forwarding (`test/AGENTS.md`), captures at 1280 desktop width and 390 mobile width:
|
||||
1. a member buys Plus through Checkout with `4242 4242 4242 4242`;
|
||||
2. an operator issues a Pro grant over it, with the warning W shown on the form;
|
||||
3. the `reconcile_subscription` entry completes, and the subscription at Stripe carries `pause_collection.behavior=void` and the marker (read with the Stripe CLI);
|
||||
4. the organization page's badge title reads "Billing paused while a grant holds {ladder}.";
|
||||
5. the member's Products page shows M0 with Cancel plan, Pro's and Max's cards offer the switch, and no card offers Checkout; a Checkout posted from an older tab is refused;
|
||||
6. a renewal while the grant holds: a Checkout-made customer has no test clock, so the walk forces one with `billing_cycle_anchor=now` and `proration_behavior=none`; Stripe may refuse that update on a paused subscription, since it creates an invoice, and then the walk records the refusal and the renewal rests on the design's Context; otherwise the renewal is a draft, then void about an hour later, and is listed with its Void badge on the member's Billing page;
|
||||
7. the grant is revoked: the Tier changes list shows T1 in the same instant as the revocation, the pause is cleared at Stripe within seconds, and the next forced renewal is paid;
|
||||
8. steps 2 to 7 again with a grant that expires (a short `valid_until`), the list showing T2;
|
||||
9. Cancel plan on the paused card sets `cancel_at_period_end` with the pause kept, and Keep plan clears it;
|
||||
10. the switch to Max from the paused subscription shows M3, charges the proration at once, clears the pause, and the organization holds Max by the subscription; the grant is recorded as replaced;
|
||||
11. a second member buys Pro, and an operator issues a Basic grant over it: once the pause is confirmed, Pro's card reads M0 with Resume plan and Cancel plan, Plus's card offers nothing and Max's offers Upgrade; Resume plan shows M11, and after it the organization holds Pro by the subscription at once, the pause is cleared at Stripe within seconds with no invoice and no proration (read with the Stripe CLI), the grant is recorded as replaced, and the member's Entitlements panel shows Pro's entitlements;
|
||||
12. a third member buys Plus through Checkout; before any grant, the walk attaches `pm_card_chargeCustomerFail` to the customer and sets it as the subscription's `default_payment_method` (`stripe post /v1/subscriptions/sub_… -d default_payment_method=pm_…`), then forces the renewal with `billing_cycle_anchor=now`, so the subscription is `past_due` with an open invoice; an operator then issues a Pro grant and the pause is confirmed; the card reads M1, "Paused while Pro is granted, payment due", and Pay invoice opens the hosted page of that open invoice, not of the voided renewal.
|
||||
The captures and the Stripe objects' ids go to the maintainer's review.
|
||||
- [ ] 13.5 After the push, post these comments under `CONTRIBUTING.md`'s rules for forge text (item 1: each reads for someone who has never opened the repository, explains the console's terms once, and names no decision number, change name, date as narrative, deployment or count). Comments need no go.
|
||||
- On #269, then close it, with the commits filled in:
|
||||
|
||||
> A subscription now stops being charged while an operator's grant covers the plan it pays for. (A plan ladder is an ordered list of plan tiers; an organization holds one tier of a ladder at a time, through a subscription, a grant or the organization type's default. An operator's grant over a tier a subscription pays for takes the ladder from the subscription.)
|
||||
>
|
||||
> While grants hold every ladder a subscription pays for, the console pauses the subscription's payment collection at Stripe, with Stripe's "void" behaviour: each renewal made during the grant is voided about an hour after it is created, and nothing is charged. When the grant ends or is revoked, collection resumes and the next renewal is charged as usual. The pause is applied through the console's outbox, so a failed call is retried for a day and then shows on the Stripe provider page, and an hourly check asks again for any subscription whose pause disagrees with its grants. A pause made by hand in the Stripe Dashboard is left alone.
|
||||
>
|
||||
> On the Products page, the paid plan's card reads "Paused while Pro is granted" and offers Cancel plan, which ends the subscription at its period end. While an invoice from before the grant is still open, the card reads "Paused while Pro is granted, payment due" and offers Pay invoice first. On the organization page, the Not delivering badge reads "Billing paused while a grant holds {ladder}." once Stripe confirms the pause, and the Overview's Monthly recurring headline leaves a paused subscription out.
|
||||
>
|
||||
> Not changed here: no money moves when the grant starts or ends, so a grant that is not a whole number of billing periods can cost the member or the operator up to one period; #280 is the exact rule. An invoice open before the grant stays due, and Stripe's retry settings can still cancel the subscription during the grant.
|
||||
>
|
||||
> Commits: …
|
||||
|
||||
- On #270, then close it:
|
||||
|
||||
> When a grant that took a subscription's ladder ends, whether it is revoked, expires, or was itself a subscription that ended, the subscription's tier is now delivered again in the same step, before the organization type's default would be put back. Nothing waits for the subscription's next event at Stripe. A subscription whose payment is due gets its tier back suspended, as it would at its own renewal. A grant that was marked to come back after a later plan replaced it still comes back first, and the subscription then waits for that grant.
|
||||
>
|
||||
> Commits: …
|
||||
|
||||
- On #277, then close it:
|
||||
|
||||
> The Products page no longer offers, and Checkout refuses, any tier of a ladder that one of the organization's subscriptions pays for while a grant holds that ladder. Buying there would have started a second subscription on the ladder while the first kept existing. The tiers at or above the grant and above the paid plan now offer a switch of the existing subscription instead, and when the grant is of a lower tier than the paid plan, the paid plan's own card offers to resume it. Checkout above a grant with no subscription behind it is unchanged.
|
||||
>
|
||||
> Commits: …
|
||||
|
||||
- On #278, then close it:
|
||||
|
||||
> A member whose subscription is paused behind a grant can now switch it to the granted tier or a higher one from the Products page. The switch is charged at once for the rest of the period, clears the pause in the same Stripe update, and the subscription takes the ladder from the grant; a grant marked to come back returns when the subscription ends, while its own term lasts. The confirmation reads "Switch to Max?" and "Your subscription replaces the grant." before the amount. Stripe's charge credits the unused part of the period whose renewal was voided, so the member pays the price difference rather than the new price for that period; #280 covers it.
|
||||
>
|
||||
> When the grant is of a lower tier than the paid plan, the paid plan's card offers Resume plan instead, and the tiers between the grant and the paid plan offer nothing. Resuming takes the ladder back from the grant for the plan the subscription already pays for, at its own price: nothing is charged at that moment, the pause is lifted at Stripe within seconds, and the next renewal is charged as usual. A downgrade the member scheduled before the grant, landing at or above the grant's tier, also takes the ladder back, and billing resumes at the lower price.
|
||||
>
|
||||
> Commits: …
|
||||
|
||||
- On #271, a note, not a close:
|
||||
|
||||
> A note from the grant pause work. When a subscription pays for a product that is a tier of two ladders and a grant takes one of them, the subscription stops delivering that product on both ladders, and the other ladder is left with nothing on it. If the subscription pays for nothing else, its billing is now paused while the grant holds. Checkout now refuses every tier of the other ladder, because buying there would start a second subscription while the first still exists, and the paid tier's card on that ladder shows no price or control. What the member should see or be offered on that ladder is still this issue's open question.
|
||||
|
||||
- #279 and #280 stay open and get no comment.
|
||||
- [ ] 13.6 After a deploy applies `00036` and `00037`, re-run `scripts/db-reader-role.sql` on that deployment (`docs/database-management.md`, "Running the script").
|
||||
- [ ] 13.7 The archive waits for the maintainer's go. Nothing in this change writes to a production host: item 13.3's count is a read under the reader role.
|
||||
- [ ] 13.8 The answer to the design repository's open question on the cross-source supersession residue (the commercial layer, not conferral, pauses billing, which is the separation that question asked for) is one entry in `status/design-feedback.md`, for the upstream design sync; `design/` is not edited.
|
||||
Reference in New Issue
Block a user