Let a subscription that pays at or above a grant's tier take the ladder

Eighth section of #269's change. A grant held a ladder against every
subscription tier on it, so a member who switched to a higher tier
while a grant held the ladder kept paying for a tier the grant still
supplied. Now a grant yields a ladder to a subscription product ranked
at or above the grant's own tier, other than the product the grant
displaced: that product never takes the ladder back, and a payment at
or above the grant ends the grant (it is recorded as replaced). A
subscription holder never yields, a holder product on no tier of the
ladder never yields, and a bundle stays left alone while any of its
displaced ladders does not yield.

Migration 00037 replaces core.subscription_displacements with two more
columns after its five, the holder's product and its rank on the
ladder (NULL when the product is no tier of it); the old five-name
alias form still names the first five. The three queries over it read
the rank as COALESCE(holder_rank, 0) with a holder_ranked flag, because
sqlc types a cast column as NOT NULL and cannot override a function's
column; a second read of the tiers table would state the rank twice.
entitlements.Displacement gains HolderProductID, HolderRank and
HolderRanked, and DisplacedProducts takes the exception (yields).

docs/models/plan-ladders-transitions.md (invariant 20 and the
function's row) and docs/stripe.md state the exception.

Tests: TestDisplacedProducts rows (above, at, below the grant, the
displaced product, a subscription holder, a holder on no tier, bundles,
including an extra row where both of a bundle's ladders yield);
TestSubscriptionDisplacements_TheHolderRank, whose failure text carries
a row prefix; TestDisplacementHolderRankMigrationUpDownUp, which
compares the function's result type after each step;
TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder,
TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder,
TestSweep_ADowngradeThatLandsAtALowerGrantsTierTakesTheLadder, and
TestDisplacementRowsCarryTheHolder for both row conversions, ranked
and unranked.

Review: round 1, three majors (the rank read through a second join of
the tiers table; section 7's three breaks of the function still edited
00034, which 00037 now overrides; the account rows' new fields
untested) and three minors, all fixed; round 2, no major. Section 7's
break lists now edit 00037.

Breaks: 16 of 16 caught (10 in code, 6 in migration 00037 on reset
test databases). Full suite on reset databases: 4838 pass, 14 skip.
make screens: no change beyond the captures every run redraws.

The change's text also takes the ruling on the grant form's warning,
for task 5.10: the sentence becomes the Product field's hint, shown
once a product marked with the warning sign is chosen, and reads "This
grant would supersede a tier a subscription pays for; its billing
pauses until the grant ends." (proposal, design Copy W, the
plan-enrollment-administration delta, and the task).
This commit is contained in:
2026-10-28 12:53:29 -05:00
parent dacb8b57a9
commit 56d801e36a
15 changed files with 630 additions and 49 deletions
+2 -2
View File
@@ -34,7 +34,7 @@ Database objects sit in the `core` schema; the baseline DDL is `internal/db/migr
| `core.product_conferral_shapes` | The view conferral reads for a product's ladder positions and availability facts (introduced in the Product Catalog card) | `00004_doc41_schema_and_data.sql` |
| `core.supersession_pairs` | The one statement of a supersession: an `end` row and the typed row with a from side of the conferral that caused it, in the same pool, on the same ladder, at the same `effective_at`, by the same actor, whatever the two provisions' sources; reads no `reason` | `00033_supersession_pairs.sql` |
| `core.grant_replacements` | A view of which source replaced a grant: it reads its pairs from `core.supersession_pairs` and keeps those whose ended provision is a grant's and whose successor is the grant or subscription that took the rung, leaving out extensions and a grant's own re-conferral | `00023_grant_resumption.sql`; `00033_supersession_pairs.sql` |
| `core.subscription_displacements` | The ladders of a pool on which a subscription is displaced and another plan holds the ladder (invariant 20): per ladder, the product the subscription lost, the instant, and the holder's provision and source. Displaced means the subscription's latest episode on the ladder ended in a supersession (a pair in `core.supersession_pairs`) whose successor belongs to another subscription or to no subscription; held means an active or suspended position of a non-default source other than the subscription sits on the ladder. The subscription reconcile, the organization page and the operator's subscriptions list read it; it reads no `reason` | `00034_subscription_displacements.sql` |
| `core.subscription_displacements` | The ladders of a pool on which a subscription is displaced and another plan holds the ladder (invariant 20): per ladder, the product the subscription lost, the instant, the holder's provision and source, and the holder's product and its rank on the ladder (NULL when the product is no tier of it). Displaced means the subscription's latest episode on the ladder ended in a supersession (a pair in `core.supersession_pairs`) whose successor belongs to another subscription or to no subscription; held means an active or suspended position of a non-default source other than the subscription sits on the ladder. The subscription reconcile, the organization page and the operator's subscriptions list read it; it reads no `reason` | `00034_subscription_displacements.sql`; `00037_displacement_holder_rank.sql` |
| `core.transition_change_kind` | The kind of change one transition records, which the Tier changes Change badge and the recent-activity line name: `resumption` for a resumption's start, `extension` for an extension's transfer or a legacy `extend` row, otherwise the row's type. A machine reason counts only from the writer that writes it, because Issue grant copies the operator's note into the reason | `00025_superseded_transitions.sql` |
| `core.superseded_ends` | A view of the `end` rows a typed row of the same act states: an `end` and a typed row with a from side in the same pool, at the same `effective_at`, by the same actor, with the same reason, on any ladder, since supersession ends every rung of the incumbent. The Tier changes list leaves out every one; the recent-activity feed leaves out only those an extension's transfer states (`by_extension`). A grant that a plan act creates already points at its act in `core.grants.act_id` (the [Acts card](acts.md)), but a transition row has no such column, so the view still matches the rows by pool, instant, actor and reason. When the writers of transitions record their act (#179), the view reads that pointer and only its body changes. The reader role cannot read it, since it reads the reason | `00025_superseded_transitions.sql` |
| `core.extension_handoffs` | A view of the transitions that record an extension, each with the grant it handed the position to. The recent-activity feed leaves those grants' rows out: the transfer, which reads "Extended", is the extension's one row. The reader role cannot read it, since it reads the reason | `00025_superseded_transitions.sql` |
@@ -77,7 +77,7 @@ An invariant is a rule the model guarantees everywhere; code that would break on
17. **[app]** Every plan act's transition reason comes from one function, `PlanActReason` (`internal/entitlements/plan_act_runner.go`), which builds it from the act's detail row so the wording lives in one place. The three tier acts that write transitions (add, removal, reorder) name the ladder: `tier added to ladder <name>`, `tier removal (<product> from <ladder>)` and `plan-ladder tier reorder (<ladder>)`. The default change names the org type's key: `org-type default change (<org type>)`. `DeleteTier` records its act (cause `tier_removed`) but writes no transition, because no one holds the tier, so it builds no reason; a Retry moves no position and has no reason. A move that a drain settles later builds the reason from the original act's detail row, so it reads as the act's own, and a migrated or grandfathered position appends what was done to it (`MigratedReason`, `GrandfatheredReason`). The reason is stored on the transition rows, so it is a write-time snapshot: it records the name as it read then, and a later rename does not rewrite it. An act that cannot read the ladder's row refuses at the read of names and records nothing.
18. **[app]** When a subscription's end, a grant's revocation or a grant's expiry ends at least one provision of that plan, every grant `core.resumable_grants(now())` names with that plan as holder re-confers from its own row, with the reason `grant-resumption:subscription:`, `grant-resumption:revocation:` or `grant-resumption:expiration:` followed by the ending plan's id. The chain rule: a marked grant waits on the nearest plan above it in its chain of replacements that has not ended, and resumes when that plan ends; a plan between them that ends first (it expires, is revoked, or is unmarked while it waits) is passed over. A grant and its extensions are one plan, named by the lineage's head. `core.grant_waits` is the one statement of the walk and the conditions (marked, active, valid at the instant, delivering nothing, its product on at least one ladder whose rungs no source but the holder holds, and first in resumption order among grants sharing a ladder), and the operator's delivery states and the member's held rung read it through the two functions. No other ending path resumes a grant: not a suspension, not a subscription dropping an item, not an extension, not an org-type migration and not a tier removal.
19. **[app]** On a ladder of the product it buys or switches to, a member's own move never takes a pool below a rung a grant delivers: from a grant-held rung the only move offered is up, through Checkout. Checkout never supersedes a position on another ladder of the product unless that ladder offers Checkout too: Checkout of a product refuses unless every ladder it is a tier of offers it. Two exceptions are open (#88), because the decision reads a position only on the ladders it is asked about. The plan switch: a switch to a product that is a tier of several ladders can supersede a position on another of them, a grant's included, because deciding it needs the subscription that holds each ladder. And a rung on a ladder the product is not a tier of: supersession is whole-bundle (invariant 7), so Checkout that supersedes a grant's position on a ladder of the product also ends that grant's rungs on ladders the product is not a tier of, and no default is restored there while the pool holds the product (invariant 11). `plans.Offer` and `plans.Across` state the rule; the Products page, Checkout and the switch read it.
20. **[db-code]** and **[app]** A subscription's reconcile does not take back a ladder another plan took from it. While a position of a non-default source other than the subscription holds a ladder on which the subscription's latest episode ended in a supersession by another source, the reconcile confers none of the subscription's products whose shape names that ladder; the subscription delivers nothing there. When the plan that holds the ladder ends and the act ended at least one of its provisions (a grant's revocation or expiry, the holding subscription's end, or a live subscription dropping the item that held the ladder), that act confers each such subscription's recorded products in its own transaction, after resumption (invariant 18) and before default restoration, with the reason `subscription-delivery:revocation:`, `subscription-delivery:expiration:`, `subscription-delivery:subscription:` or `subscription-delivery:dropped:` followed by the ending plan's id; a subscription the ending plan superseded goes first, then the rest in subscription id order, a past-due, unpaid or paused subscription comes back suspended, and a refused conferral is logged and leaves that subscription undelivered. In any other case the subscription's next reconcile after no such plan holds the ladder confers it again. While every conferring product the subscription pays for is left alone and every plan holding those ladders is a grant, the subscription's collection is paused at Stripe. A default-sourced position never holds a ladder against a subscription (invariant 11). `core.subscription_displacements` is the one statement of which ladders those are; the reconcile, the organization page and the operator's subscriptions list read it.
20. **[db-code]** and **[app]** A subscription's reconcile does not take back a ladder another plan took from it. While a position of a non-default source other than the subscription holds a ladder on which the subscription's latest episode ended in a supersession by another source, the reconcile confers none of the subscription's products whose shape names that ladder; the subscription delivers nothing there. When the plan that holds the ladder ends and the act ended at least one of its provisions (a grant's revocation or expiry, the holding subscription's end, or a live subscription dropping the item that held the ladder), that act confers each such subscription's recorded products in its own transaction, after resumption (invariant 18) and before default restoration, with the reason `subscription-delivery:revocation:`, `subscription-delivery:expiration:`, `subscription-delivery:subscription:` or `subscription-delivery:dropped:` followed by the ending plan's id; a subscription the ending plan superseded goes first, then the rest in subscription id order, a past-due, unpaid or paused subscription comes back suspended, and a refused conferral is logged and leaves that subscription undelivered. In any other case the subscription's next reconcile after no such plan holds the ladder confers it again. While every conferring product the subscription pays for is left alone and every plan holding those ladders is a grant, the subscription's collection is paused at Stripe. The exception: a grant's hold ends when the subscription pays at or above the grant. The reconcile confers a product of the subscription whose shape names such a ladder when the holder is a grant, the product is not the one the grant displaced, and its rank on the ladder is at or above the rank of the grant's product; the grant is then replaced by the subscription. The product the grant displaced never takes the ladder back, whatever its rank. A grant product that is no tier of the ladder never yields. A default-sourced position never holds a ladder against a subscription (invariant 11). `core.subscription_displacements` is the one statement of which ladders those are; the reconcile, the organization page and the operator's subscriptions list read it.
## Dimensions
+1 -1
View File
@@ -211,7 +211,7 @@ A member moves between the paid tiers of a plan ladder on the Products page, and
- **Cancellation.** Every paid plan offers **Cancel plan** on its card. Access continues until the end of the paid period (`cancel_at_period_end`), after which the organization moves to its type's default plan, when one is configured, or leaves the ladder.
- **Taking a scheduled move back.** While a downgrade or a cancellation is scheduled, the plan's card offers **Keep plan**, which releases the schedule or clears `cancel_at_period_end` at no charge. While a downgrade is scheduled, **Cancel plan** follows it and replaces the downgrade; while a cancellation is scheduled, **Keep plan** is the only control.
- **A plan whose payment is due.** A subscription Stripe holds as `past_due` or `unpaid` keeps its card on the Products page, shown as the current plan with its state, while its entitlements are suspended. No switch is offered in either direction and a posted one is refused before any Stripe call, because a switch would invoice while the failed invoice is still open. **Keep plan** and **Cancel plan** at the period end work as on an active plan. A posted immediate cancellation is refused, because Stripe's immediate cancellation stops automatic collection of the customer's finalized invoices, and a **Keep plan** over a downgrade that Stripe has already applied is refused, because there is nothing left to take back. The unpaid invoice stays due after a cancellation: once the cancellation takes effect, Stripe stops retrying that subscription's open invoice and leaves the customer's other subscriptions collecting, so the member pays it through the invoice's **Pay invoice**. A paused subscription shows its state and is refused every act; only a subscription made outside the console reaches `paused`, which follows a trial that ends without a payment method, because the console's Checkout creates no trial.
- **A grant over a paid plan.** An operator's grant over a tier a subscription pays for keeps the ladder until it ends or is revoked, and the subscription delivers nothing there. The console pauses the subscription's collection at Stripe (`pause_collection` with `behavior=void`, and the marker `member_console_collection=paused_for_grant` in the subscription's metadata) within seconds, through the outbox, and sets no `resumes_at`. Each renewal Stripe makes while the grant holds is a draft for about an hour and is then voided, so nothing is charged. When the grant ends, the tier is delivered again in the act that ends the grant, and the console clears the pause and the marker within seconds; no money moves at either edge. While the grant holds the ladder, the organization page's Billing card and the subscription's row in the operator's subscriptions list carry a **Not delivering** badge. Once Stripe confirms the pause, which the subscription row records, its title reads "Billing paused while a grant holds {ladder}." ("grants hold" when several grants hold the ladders); until it does, and while the pause has failed, it reads "Billing continues while a grant holds {ladder}." When the ladder is left to the default or to nothing in another way, such as a tier removal, the subscription's next reconcile delivers its tier again. A new purchase over a grant still replaces the grant. What this accepts until the exact money rule (#280): the renewal date decides which way a grant that is not whole periods falls, because a period's renewal is voided or charged whole; a pause landing after a renewal's finalization lets that renewal be charged, and a clear landing before the finalization of a renewal made while paused lets it be charged; a pause or clear that lands late moves a whole period one way or the other, and a void cannot be undone; the first charge after a grant can come without Stripe's upcoming-renewal reminder. A subscription 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. An invoice open before the grant stays due: Stripe keeps retrying it, and the account's dunning setting can cancel the paused subscription.
- **A grant over a paid plan.** An operator's grant over a tier a subscription pays for keeps the ladder until it ends or is revoked, and the subscription delivers nothing there. The console pauses the subscription's collection at Stripe (`pause_collection` with `behavior=void`, and the marker `member_console_collection=paused_for_grant` in the subscription's metadata) within seconds, through the outbox, and sets no `resumes_at`. Each renewal Stripe makes while the grant holds is a draft for about an hour and is then voided, so nothing is charged. When the grant ends, the tier is delivered again in the act that ends the grant, and the console clears the pause and the marker within seconds; no money moves at either edge. While the grant holds the ladder, the organization page's Billing card and the subscription's row in the operator's subscriptions list carry a **Not delivering** badge. Once Stripe confirms the pause, which the subscription row records, its title reads "Billing paused while a grant holds {ladder}." ("grants hold" when several grants hold the ladders); until it does, and while the pause has failed, it reads "Billing continues while a grant holds {ladder}." When the ladder is left to the default or to nothing in another way, such as a tier removal, the subscription's next reconcile delivers its tier again. A new purchase over a grant still replaces the grant. A switch to the granted tier or above ends the grant's hold, and the subscription delivers the new tier. What this accepts until the exact money rule (#280): the renewal date decides which way a grant that is not whole periods falls, because a period's renewal is voided or charged whole; a pause landing after a renewal's finalization lets that renewal be charged, and a clear landing before the finalization of a renewal made while paused lets it be charged; a pause or clear that lands late moves a whole period one way or the other, and a void cannot be undone; the first charge after a grant can come without Stripe's upcoming-renewal reminder. A subscription 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. An invoice open before the grant stays due: Stripe keeps retrying it, and the account's dunning setting can cancel the paused subscription.
- **Pay invoice.** The card of a plan whose payment is due, and the detail of an open invoice, link to Stripe's hosted invoice page. The console reads the page's URL from Stripe when the member opens the link and redirects there; it never stores or logs the URL, which is a bearer link, and it needs no key permission beyond the reads of subscriptions and invoices that the reconciles already make. Paying there makes the new card the customer's default for invoices but leaves the subscription's own default on the card that failed, which Stripe charges first, so the next renewal charges the failed card again. Stripe's page still takes payment for an invoice Stripe has marked uncollectible, which the console shows as open until the invoice sweep reads it again.
A restricted key needs permission for the calls these moves make, beyond those the console already uses: `POST /v1/subscription_schedules`, `POST /v1/subscription_schedules/{id}`, `POST /v1/subscription_schedules/{id}/release` and `POST /v1/invoices/{id}/void`. The console also updates a subscription with `POST /v1/subscriptions/{id}` to set `pause_collection` while a grant holds its ladder and to clear it when the grant no longer does, which is the Subscriptions write the plan moves already need. Stripe names the missing permission in the error a key without it receives.
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
package db_test
// Migration 00037 (openspec change grant-pauses-subscription-billing, design
// D8): core.subscription_displacements returns the holder's product and its
// rank on the ladder after its five columns, and the old five-name alias form
// still runs.
import (
"database/sql"
"testing"
"github.com/google/uuid"
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/world"
)
const (
holderRankVersion = 37
holderRankPrevious = 36
displacementColumnsBefore = 5
displacementColumnsAfter = 7
readDisplacements = `
SELECT d.holder_product_id, d.holder_rank
FROM core.subscription_displacements($1::uuid, $2::uuid) d`
displacementColumnCount = `
SELECT count(*) FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace, unnest(p.proargmodes) m
WHERE n.nspname = 'core' AND p.proname = 'subscription_displacements' AND m = 't'`
displacementResult = `
SELECT pg_catalog.pg_get_function_result(p.oid) FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'core' AND p.proname = 'subscription_displacements'`
displacementResultBefore = "TABLE(plan_ladder_id uuid, displaced_product_id uuid, displaced_at timestamp with time zone, holder_provision_id uuid, holder_source text)"
displacementResultAfter = "TABLE(plan_ladder_id uuid, displaced_product_id uuid, displaced_at timestamp with time zone, holder_provision_id uuid, holder_source text, holder_product_id uuid, holder_rank integer)"
fiveNameAliasForm = `
SELECT d.plan_ladder_id, d.displaced_product_id, d.displaced_at, d.holder_provision_id, d.holder_source
FROM core.subscription_displacements($1::uuid, $2::uuid)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)`
)
// holderRankRow is one case of TestSubscriptionDisplacements_TheHolderRank:
// whether the granted product stays a tier of the ladder, and the rank the
// function must return for it.
type holderRankRow struct {
name string
untiered bool
rank sql.NullInt32
}
// checkHolderRank displaces a subscription on the Small tier with a grant of
// Big (rank 1), optionally removes Big from the ladder, and reads the
// function's holder columns.
func checkHolderRank(t *testing.T, row holderRankRow) {
t.Helper()
d := dbtest.Open(t)
w := world.New(t, d)
org := w.Org("Holder", w.OrgType("hr"), w.Person("Owner"))
small, big := w.Product("Small"), w.Product("Big")
w.Price(small, 1000)
w.Price(big, 2000)
ladder := w.Ladder("Box", small, big)
w.BillingAccount(org, "Account")
sub := w.Subscribe(org, world.SubOpts{}, small)
w.Issue(org, big, world.IssueOpts{})
if row.untiered {
dbtest.On(t, d).Exec(`DELETE FROM core.plan_ladder_tiers WHERE plan_ladder_id = $1 AND product_id = $2`, ladder.ID, big.ID)
}
var product string
var rank sql.NullInt32
dbtest.On(t, d).Scan([]any{&product, &rank}, readDisplacements, sub.ID, org.PoolID)
if product != big.ID || rank != row.rank {
t.Errorf("%s: holder %s, rank %v, want %s, %v", row.name, product, rank, big.ID, row.rank)
}
}
func TestSubscriptionDisplacements_TheHolderRank(t *testing.T) {
for _, row := range []holderRankRow{
{name: "a holder product on the ladder", rank: sql.NullInt32{Int32: 1, Valid: true}},
{name: "a holder product on no tier of the ladder", untiered: true},
} {
checkHolderRank(t, row)
}
}
func TestDisplacementHolderRankMigrationUpDownUp(t *testing.T) {
scratch := dbtest.Connect(t, dbtest.Scratch(t))
core := db.BaseSources()[0]
q := dbtest.On(t, scratch)
dbtest.UpTo(t, scratch, core, holderRankPrevious)
requireDisplacementColumns(t, q, "migrating to 36", displacementColumnsBefore, displacementResultBefore)
dbtest.ApplyVersion(t, scratch, core, holderRankVersion, true)
requireDisplacementColumns(t, q, "the first up", displacementColumnsAfter, displacementResultAfter)
requireFiveNameAliasForm(t, scratch)
dbtest.ApplyVersion(t, scratch, core, holderRankVersion, false)
requireDisplacementColumns(t, q, "the down", displacementColumnsBefore, displacementResultBefore)
dbtest.ApplyVersion(t, scratch, core, holderRankVersion, true)
requireDisplacementColumns(t, q, "the second up", displacementColumnsAfter, displacementResultAfter)
requireFiveNameAliasForm(t, scratch)
}
func requireDisplacementColumns(t *testing.T, q *dbtest.Q, after string, want int64, wantResult string) {
t.Helper()
if got := q.Int(displacementColumnCount); got != want {
t.Errorf("after %s, the function returns %d columns, want %d", after, got, want)
}
if got := q.String(displacementResult); got != wantResult {
t.Errorf("after %s, the function returns %s, want %s", after, got, wantResult)
}
}
// requireFiveNameAliasForm runs the alias list the earlier queries wrote; it
// names the first five columns of the new function.
func requireFiveNameAliasForm(t *testing.T, scratch *sql.DB) {
t.Helper()
if _, err := scratch.Exec(fiveNameAliasForm, uuid.NewString(), uuid.NewString()); err != nil {
t.Errorf("the five-name alias form failed: %v", err)
}
}
@@ -0,0 +1,129 @@
-- SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
-- SPDX-FileCopyrightText: 2025-2026 Christian Galo
-- +goose Up
-- ---------------------------------------------------------------------------
-- The holder's product and rank (openspec change
-- grant-pauses-subscription-billing, D8). core.subscription_displacements
-- gains two columns after its five: holder_product_id, the product of the
-- holding episode, and holder_rank, that product's rank on the ladder, NULL
-- when the product is no tier of the ladder. A subscription that pays for a
-- tier at or above the grant's rank takes the ladder, and the rule reads the
-- rank here. The return type changes, so the function is dropped and created.
-- The old five-name column alias list still names the first five columns.
-- ---------------------------------------------------------------------------
DROP FUNCTION core.subscription_displacements(UUID, UUID);
-- +goose StatementBegin
CREATE FUNCTION core.subscription_displacements(p_subscription_id UUID, p_pool_id UUID)
RETURNS TABLE (
plan_ladder_id UUID,
displaced_product_id UUID,
displaced_at TIMESTAMPTZ,
holder_provision_id UUID,
holder_source TEXT,
holder_product_id UUID,
holder_rank INTEGER
)
LANGUAGE sql
STABLE
AS $$
WITH latest AS (
SELECT DISTINCT ON (l.plan_ladder_id)
l.plan_ladder_id, l.provision_id, l.product_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 l.pool_id = p_pool_id
AND p.subscription_id = p_subscription_id
ORDER BY l.plan_ladder_id, l.activated_at DESC, l.provision_ladder_id DESC
),
displaced AS (
SELECT lt.plan_ladder_id, lt.product_id, lt.ended_at
FROM latest lt
WHERE lt.status = 'ended'
AND EXISTS (
SELECT 1
FROM core.supersession_pairs sp
JOIN core.pool_provisions succ ON succ.provision_id = sp.successor_provision_id
WHERE sp.pool_id = p_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 p_subscription_id)
)
SELECT d.plan_ladder_id, d.product_id, d.ended_at, h.provision_id,
CASE WHEN hp.grant_id IS NOT NULL THEN 'grant'
WHEN hp.subscription_id IS NOT NULL THEN 'subscription'
ELSE 'purchase' END,
h.product_id, t.rank
FROM displaced d
JOIN core.pool_provision_ladders h
ON h.pool_id = p_pool_id
AND h.plan_ladder_id = d.plan_ladder_id
AND h.status IN ('active', 'suspended')
AND NOT h.default_sourced
JOIN core.pool_provisions hp ON hp.provision_id = h.provision_id
LEFT JOIN core.plan_ladder_tiers t
ON t.plan_ladder_id = h.plan_ladder_id AND t.product_id = h.product_id
WHERE hp.subscription_id IS DISTINCT FROM p_subscription_id
ORDER BY d.plan_ladder_id, h.provision_id;
$$;
-- +goose StatementEnd
GRANT EXECUTE ON FUNCTION core.subscription_displacements(UUID, UUID) TO core_reader, core_writer, core_owner;
-- +goose Down
DROP FUNCTION core.subscription_displacements(UUID, UUID);
-- +goose StatementBegin
CREATE FUNCTION core.subscription_displacements(p_subscription_id UUID, p_pool_id UUID)
RETURNS TABLE (
plan_ladder_id UUID,
displaced_product_id UUID,
displaced_at TIMESTAMPTZ,
holder_provision_id UUID,
holder_source TEXT
)
LANGUAGE sql
STABLE
AS $$
WITH latest AS (
SELECT DISTINCT ON (l.plan_ladder_id)
l.plan_ladder_id, l.provision_id, l.product_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 l.pool_id = p_pool_id
AND p.subscription_id = p_subscription_id
ORDER BY l.plan_ladder_id, l.activated_at DESC, l.provision_ladder_id DESC
),
displaced AS (
SELECT lt.plan_ladder_id, lt.product_id, lt.ended_at
FROM latest lt
WHERE lt.status = 'ended'
AND EXISTS (
SELECT 1
FROM core.supersession_pairs sp
JOIN core.pool_provisions succ ON succ.provision_id = sp.successor_provision_id
WHERE sp.pool_id = p_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 p_subscription_id)
)
SELECT d.plan_ladder_id, d.product_id, d.ended_at, h.provision_id,
CASE WHEN hp.grant_id IS NOT NULL THEN 'grant'
WHEN hp.subscription_id IS NOT NULL THEN 'subscription'
ELSE 'purchase' END
FROM displaced d
JOIN core.pool_provision_ladders h
ON h.pool_id = p_pool_id
AND h.plan_ladder_id = d.plan_ladder_id
AND h.status IN ('active', 'suspended')
AND NOT h.default_sourced
JOIN core.pool_provisions hp ON hp.provision_id = h.provision_id
WHERE hp.subscription_id IS DISTINCT FROM p_subscription_id
ORDER BY d.plan_ladder_id, h.provision_id;
$$;
-- +goose StatementEnd
GRANT EXECUTE ON FUNCTION core.subscription_displacements(UUID, UUID) TO core_reader, core_writer, core_owner;
+36 -9
View File
@@ -37,13 +37,18 @@ func RungsByProduct(rows []ListConferralShapesRow) map[string][]Rung {
// 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.
// product, and the holder's provision, source, product and rank on the ladder.
// HolderRanked is false when the holder's product is no tier of the ladder,
// and HolderRank is then zero and means nothing.
type Displacement struct {
LadderID string
LadderName string
DisplacedProductID string
HolderProvisionID string
HolderSource string
HolderProductID string
HolderRank int32
HolderRanked bool
}
// DisplacementsFromRows turns the displacement query's rows into
@@ -57,6 +62,9 @@ func DisplacementsFromRows(rows []ListSubscriptionDisplacementsRow) []Displaceme
DisplacedProductID: r.DisplacedProductID,
HolderProvisionID: r.HolderProvisionID,
HolderSource: r.HolderSource,
HolderProductID: r.HolderProductID,
HolderRank: r.HolderRank,
HolderRanked: r.HolderRanked,
})
}
return out
@@ -75,6 +83,9 @@ func DisplacementsBySubscription(rows []ListAccountSubscriptionDisplacementsRow)
DisplacedProductID: d.DisplacedProductID,
HolderProvisionID: d.HolderProvisionID,
HolderSource: d.HolderSource,
HolderProductID: d.HolderProductID,
HolderRank: d.HolderRank,
HolderRanked: d.HolderRanked,
})
}
return by
@@ -82,13 +93,18 @@ func DisplacementsBySubscription(rows []ListAccountSubscriptionDisplacementsRow)
// 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.
// whose ladder the subscription is displaced on and whose displacement does
// not yield to the product (yields). The check is per ladder, so another
// product of a displaced ladder is left alone too, except a tier at or above
// the grant that holds the ladder: a subscription's payment at or above the
// grant ends the grant's hold. The product the grant displaced never takes the
// ladder back, whatever its rank. A bundle is left alone when any of its
// displaced ladders does not yield, since a conferral places the whole
// product. 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 {
@@ -99,7 +115,7 @@ func DisplacedProducts(missing []string, rungs map[string][]Rung, displacements
left := make(map[string]Displacement)
for _, p := range missing {
for _, r := range rungs[p] {
if d, ok := byLadder[r.LadderID]; ok {
if d, ok := byLadder[r.LadderID]; ok && !yields(d, p, r) {
left[p] = d
break
}
@@ -108,6 +124,17 @@ func DisplacedProducts(missing []string, rungs map[string][]Rung, displacements
return left
}
// yields reports whether the displacement gives way to product on rung r: its
// holder is a grant whose product ranks on the ladder, the product is not the
// one the grant displaced, and the rung ranks at or above the holder's. It
// reads no row.
func yields(d Displacement, product string, r Rung) bool {
return d.HolderSource == "grant" &&
d.HolderRanked &&
product != d.DisplacedProductID &&
r.Rank >= d.HolderRank
}
// Outrank is the product that outranked another and the ladder they share.
type Outrank struct {
ByProductID string
@@ -31,6 +31,14 @@ func checkDisplacedProducts(t *testing.T, row displacedProductsRow) {
// 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"}
grantOnL1 := Displacement{LadderID: "L1", DisplacedProductID: "A", HolderProvisionID: "H",
HolderSource: "grant", HolderProductID: "G", HolderRank: 2, HolderRanked: true}
grantOnL2 := Displacement{LadderID: "L2", DisplacedProductID: "X", HolderProvisionID: "H2",
HolderSource: "grant", HolderProductID: "G2", HolderRank: 2, HolderRanked: true}
subscriptionOnL1 := grantOnL1
subscriptionOnL1.HolderSource = "subscription"
unrankedOnL1 := grantOnL1
unrankedOnL1.HolderRanked = false
for _, row := range []displacedProductsRow{
{
name: "a missing product on a displaced ladder is left out",
@@ -60,6 +68,62 @@ func TestDisplacedProducts(t *testing.T) {
displacements: []Displacement{onL1},
want: map[string]Displacement{"C": onL1},
},
{
name: "a tier above the grant",
missing: []string{"M"},
rungs: map[string][]Rung{"M": {{LadderID: "L1", Rank: 3}}},
displacements: []Displacement{grantOnL1},
want: map[string]Displacement{},
},
{
name: "the granted tier itself, not the displaced product",
missing: []string{"G"},
rungs: map[string][]Rung{"G": {{LadderID: "L1", Rank: 2}}},
displacements: []Displacement{grantOnL1},
want: map[string]Displacement{},
},
{
name: "the displaced product ranked above a lower grant",
missing: []string{"A"},
rungs: map[string][]Rung{"A": {{LadderID: "L1", Rank: 3}}},
displacements: []Displacement{grantOnL1},
want: map[string]Displacement{"A": grantOnL1},
},
{
name: "a tier below the grant",
missing: []string{"B"},
rungs: map[string][]Rung{"B": {{LadderID: "L1", Rank: 1}}},
displacements: []Displacement{grantOnL1},
want: map[string]Displacement{"B": grantOnL1},
},
{
name: "a tier above a subscription holder",
missing: []string{"M"},
rungs: map[string][]Rung{"M": {{LadderID: "L1", Rank: 3}}},
displacements: []Displacement{subscriptionOnL1},
want: map[string]Displacement{"M": subscriptionOnL1},
},
{
name: "a holder product on no tier of the ladder",
missing: []string{"M"},
rungs: map[string][]Rung{"M": {{LadderID: "L1", Rank: 3}}},
displacements: []Displacement{unrankedOnL1},
want: map[string]Displacement{"M": unrankedOnL1},
},
{
name: "a bundle whose other ladder does not yield",
missing: []string{"C"},
rungs: map[string][]Rung{"C": {{LadderID: "L1", Rank: 3}, {LadderID: "L2", Rank: 1}}},
displacements: []Displacement{grantOnL1, grantOnL2},
want: map[string]Displacement{"C": grantOnL2},
},
{
name: "a bundle whose ladders both yield",
missing: []string{"C"},
rungs: map[string][]Rung{"C": {{LadderID: "L2", Rank: 3}, {LadderID: "L1", Rank: 3}}},
displacements: []Displacement{grantOnL1, grantOnL2},
want: map[string]Displacement{},
},
{
name: "an add-on is kept",
missing: []string{"D"},
@@ -153,3 +217,27 @@ func TestChooseTiers(t *testing.T) {
checkChooseTiers(t, row)
}
}
// TestDisplacementRowsCarryTheHolder pins that both row conversions carry the
// holder's product and rank, which DisplacedProducts' exception reads on the
// reconcile's path and on the organization page's, the list's and the sweep's.
func TestDisplacementRowsCarryTheHolder(t *testing.T) {
want := []Displacement{{LadderID: "L1", LadderName: "Hosting", DisplacedProductID: "A", HolderProvisionID: "H",
HolderSource: "grant", HolderProductID: "G", HolderRank: 2, HolderRanked: true},
{LadderID: "L2", LadderName: "Wiki", DisplacedProductID: "B", HolderProvisionID: "H2",
HolderSource: "grant", HolderProductID: "G2", HolderRank: 0, HolderRanked: false}}
one := DisplacementsFromRows([]ListSubscriptionDisplacementsRow{{PlanLadderID: "L1", LadderName: "Hosting",
DisplacedProductID: "A", HolderProvisionID: "H", HolderSource: "grant", HolderProductID: "G", HolderRank: 2, HolderRanked: true},
{PlanLadderID: "L2", LadderName: "Wiki",
DisplacedProductID: "B", HolderProvisionID: "H2", HolderSource: "grant", HolderProductID: "G2", HolderRank: 0, HolderRanked: false}})
if !slices.Equal(one, want) {
t.Errorf("DisplacementsFromRows = %+v, want %+v", one, want)
}
by := DisplacementsBySubscription([]ListAccountSubscriptionDisplacementsRow{{SubscriptionID: "S", PlanLadderID: "L1", LadderName: "Hosting",
DisplacedProductID: "A", HolderProvisionID: "H", HolderSource: "grant", HolderProductID: "G", HolderRank: 2, HolderRanked: true},
{SubscriptionID: "S", PlanLadderID: "L2", LadderName: "Wiki",
DisplacedProductID: "B", HolderProvisionID: "H2", HolderSource: "grant", HolderProductID: "G2", HolderRank: 0, HolderRanked: false}})
if !slices.Equal(by["S"], want) {
t.Errorf("DisplacementsBySubscription = %+v, want %+v", by["S"], want)
}
}
@@ -24,10 +24,14 @@ SELECT s.subscription_id::uuid AS subscription_id,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
FROM core.subscriptions s
CROSS JOIN LATERAL core.subscription_displacements(s.subscription_id, $1::uuid)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
WHERE s.billing_account_id = $2::uuid
ORDER BY s.subscription_id, pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid
@@ -46,13 +50,18 @@ type ListAccountSubscriptionDisplacementsRow struct {
DisplacedAt time.Time `json:"displaced_at"`
HolderProvisionID string `json:"holder_provision_id"`
HolderSource string `json:"holder_source"`
HolderProductID string `json:"holder_product_id"`
HolderRank int32 `json:"holder_rank"`
HolderRanked bool `json:"holder_ranked"`
}
// core.subscription_displacements applied to every subscription of the billing
// account on the pool (displaced-subscription-waits D4), for the organization
// page's Billing card: one statement for the account, never one per
// subscription. The aliases repeat the function's columns because sqlc cannot
// read a function's RETURNS TABLE. The status filter stays in Go.
// read a function's RETURNS TABLE. The holder's rank decides the exception for
// a subscription that pays at or above a grant (D8). The status filter stays
// in Go.
func (q *Queries) ListAccountSubscriptionDisplacements(ctx context.Context, arg ListAccountSubscriptionDisplacementsParams) ([]ListAccountSubscriptionDisplacementsRow, error) {
rows, err := q.db.QueryContext(ctx, listAccountSubscriptionDisplacements, arg.PoolID, arg.BillingAccountID)
if err != nil {
@@ -70,6 +79,9 @@ func (q *Queries) ListAccountSubscriptionDisplacements(ctx context.Context, arg
&i.DisplacedAt,
&i.HolderProvisionID,
&i.HolderSource,
&i.HolderProductID,
&i.HolderRank,
&i.HolderRanked,
); err != nil {
return nil, err
}
@@ -274,9 +286,13 @@ SELECT d.plan_ladder_id::uuid AS plan_ladder_id,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
FROM core.subscription_displacements($1::uuid, $2::uuid)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
ORDER BY pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid
`
@@ -293,13 +309,20 @@ type ListSubscriptionDisplacementsRow struct {
DisplacedAt time.Time `json:"displaced_at"`
HolderProvisionID string `json:"holder_provision_id"`
HolderSource string `json:"holder_source"`
HolderProductID string `json:"holder_product_id"`
HolderRank int32 `json:"holder_rank"`
HolderRanked bool `json:"holder_ranked"`
}
// The ladders of the pool on which the subscription is displaced and another
// plan holds the ladder (displaced-subscription-waits D1, D2), with the
// ladder's name. core.subscription_displacements is the rule's one
// statement; the aliases repeat its columns because sqlc cannot read a
// function's RETURNS TABLE. The reconcile calls it under the pool row.
// function's RETURNS TABLE. The reconcile calls it under the pool row. The
// holder's product and rank decide the exception for a subscription that pays
// at or above a grant (grant-pauses-subscription-billing D8). sqlc types every
// cast column NOT NULL, so the function's NULL rank, for a holder product on no
// tier of the ladder, reads as holder_ranked false and holder_rank 0.
func (q *Queries) ListSubscriptionDisplacements(ctx context.Context, arg ListSubscriptionDisplacementsParams) ([]ListSubscriptionDisplacementsRow, error) {
rows, err := q.db.QueryContext(ctx, listSubscriptionDisplacements, arg.SubscriptionID, arg.PoolID)
if err != nil {
@@ -316,6 +339,9 @@ func (q *Queries) ListSubscriptionDisplacements(ctx context.Context, arg ListSub
&i.DisplacedAt,
&i.HolderProvisionID,
&i.HolderSource,
&i.HolderProductID,
&i.HolderRank,
&i.HolderRanked,
); err != nil {
return nil, err
}
@@ -337,13 +363,17 @@ SELECT s.subscription_id::uuid AS subscription_id,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
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)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
WHERE s.subscription_id = ANY($1::uuid[])
ORDER BY s.subscription_id, pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid
@@ -357,6 +387,9 @@ type ListSubscriptionDisplacementsBySubscriptionIDsRow struct {
DisplacedAt time.Time `json:"displaced_at"`
HolderProvisionID string `json:"holder_provision_id"`
HolderSource string `json:"holder_source"`
HolderProductID string `json:"holder_product_id"`
HolderRank int32 `json:"holder_rank"`
HolderRanked bool `json:"holder_ranked"`
}
// core.subscription_displacements applied to each listed subscription with
@@ -364,7 +397,9 @@ type ListSubscriptionDisplacementsBySubscriptionIDsRow struct {
// states and the reconcile resolves its pool by, in one statement for the
// operator's subscriptions list (displaced-subscription-waits D4), never one
// per row. The aliases repeat the function's columns because sqlc cannot read
// a function's RETURNS TABLE. The status filter stays in Go.
// a function's RETURNS TABLE. The holder's rank decides the exception for a
// subscription that pays at or above a grant (D8). The status filter stays in
// Go.
func (q *Queries) ListSubscriptionDisplacementsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListSubscriptionDisplacementsBySubscriptionIDsRow, error) {
rows, err := q.db.QueryContext(ctx, listSubscriptionDisplacementsBySubscriptionIDs, pq.Array(subscriptionIds))
if err != nil {
@@ -382,6 +417,9 @@ func (q *Queries) ListSubscriptionDisplacementsBySubscriptionIDs(ctx context.Con
&i.DisplacedAt,
&i.HolderProvisionID,
&i.HolderSource,
&i.HolderProductID,
&i.HolderRank,
&i.HolderRanked,
); err != nil {
return nil, err
}
+11 -3
View File
@@ -235,7 +235,9 @@ type Querier interface {
// account on the pool (displaced-subscription-waits D4), for the organization
// page's Billing card: one statement for the account, never one per
// subscription. The aliases repeat the function's columns because sqlc cannot
// read a function's RETURNS TABLE. The status filter stays in Go.
// read a function's RETURNS TABLE. The holder's rank decides the exception for
// a subscription that pays at or above a grant (D8). The status filter stays
// in Go.
ListAccountSubscriptionDisplacements(ctx context.Context, arg ListAccountSubscriptionDisplacementsParams) ([]ListAccountSubscriptionDisplacementsRow, error)
ListActiveEntitlementSets(ctx context.Context) ([]EntitlementSet, error)
// Read-only per-pool boolean state for a batch of pools, the boolean half of
@@ -590,14 +592,20 @@ type Querier interface {
// plan holds the ladder (displaced-subscription-waits D1, D2), with the
// ladder's name. core.subscription_displacements is the rule's one
// statement; the aliases repeat its columns because sqlc cannot read a
// function's RETURNS TABLE. The reconcile calls it under the pool row.
// function's RETURNS TABLE. The reconcile calls it under the pool row. The
// holder's product and rank decide the exception for a subscription that pays
// at or above a grant (grant-pauses-subscription-billing D8). sqlc types every
// cast column NOT NULL, so the function's NULL rank, for a holder product on no
// tier of the ladder, reads as holder_ranked false and holder_rank 0.
ListSubscriptionDisplacements(ctx context.Context, arg ListSubscriptionDisplacementsParams) ([]ListSubscriptionDisplacementsRow, error)
// core.subscription_displacements applied to each listed subscription with
// its organization's active default pool, the predicate GetDefaultPoolByOrgID
// states and the reconcile resolves its pool by, in one statement for the
// operator's subscriptions list (displaced-subscription-waits D4), never one
// per row. The aliases repeat the function's columns because sqlc cannot read
// a function's RETURNS TABLE. The status filter stays in Go.
// a function's RETURNS TABLE. The holder's rank decides the exception for a
// subscription that pays at or above a grant (D8). The status filter stays in
// Go.
ListSubscriptionDisplacementsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListSubscriptionDisplacementsBySubscriptionIDsRow, error)
// Of the listed subscriptions, those whose latest episode on a ladder of the
// pool ended in a supersession pair whose successor is one of the listed
@@ -72,15 +72,23 @@ LIMIT $1;
-- plan holds the ladder (displaced-subscription-waits D1, D2), with the
-- ladder's name. core.subscription_displacements is the rule's one
-- statement; the aliases repeat its columns because sqlc cannot read a
-- function's RETURNS TABLE. The reconcile calls it under the pool row.
-- function's RETURNS TABLE. The reconcile calls it under the pool row. The
-- holder's product and rank decide the exception for a subscription that pays
-- at or above a grant (grant-pauses-subscription-billing D8). sqlc types every
-- cast column NOT NULL, so the function's NULL rank, for a holder product on no
-- tier of the ladder, reads as holder_ranked false and holder_rank 0.
SELECT d.plan_ladder_id::uuid AS plan_ladder_id,
pl.name AS ladder_name,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
FROM core.subscription_displacements(sqlc.arg(subscription_id)::uuid, sqlc.arg(pool_id)::uuid)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
ORDER BY pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid;
@@ -89,17 +97,23 @@ ORDER BY pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid;
-- account on the pool (displaced-subscription-waits D4), for the organization
-- page's Billing card: one statement for the account, never one per
-- subscription. The aliases repeat the function's columns because sqlc cannot
-- read a function's RETURNS TABLE. The status filter stays in Go.
-- read a function's RETURNS TABLE. The holder's rank decides the exception for
-- a subscription that pays at or above a grant (D8). The status filter stays
-- in Go.
SELECT s.subscription_id::uuid AS subscription_id,
d.plan_ladder_id::uuid AS plan_ladder_id,
pl.name AS ladder_name,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
FROM core.subscriptions s
CROSS JOIN LATERAL core.subscription_displacements(s.subscription_id, sqlc.arg(pool_id)::uuid)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
WHERE s.billing_account_id = sqlc.arg(billing_account_id)::uuid
ORDER BY s.subscription_id, pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid;
@@ -110,20 +124,26 @@ ORDER BY s.subscription_id, pl.name, d.plan_ladder_id::uuid, d.holder_provision_
-- states and the reconcile resolves its pool by, in one statement for the
-- operator's subscriptions list (displaced-subscription-waits D4), never one
-- per row. The aliases repeat the function's columns because sqlc cannot read
-- a function's RETURNS TABLE. The status filter stays in Go.
-- a function's RETURNS TABLE. The holder's rank decides the exception for a
-- subscription that pays at or above a grant (D8). The status filter stays in
-- Go.
SELECT s.subscription_id::uuid AS subscription_id,
d.plan_ladder_id::uuid AS plan_ladder_id,
pl.name AS ladder_name,
d.displaced_product_id::uuid AS displaced_product_id,
d.displaced_at::timestamptz AS displaced_at,
d.holder_provision_id::uuid AS holder_provision_id,
d.holder_source::text AS holder_source
d.holder_source::text AS holder_source,
d.holder_product_id::uuid AS holder_product_id,
COALESCE(d.holder_rank, 0)::int AS holder_rank,
(d.holder_rank IS NOT NULL)::boolean AS holder_ranked
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)
AS d(plan_ladder_id, displaced_product_id, displaced_at, holder_provision_id, holder_source,
holder_product_id, holder_rank)
JOIN core.plan_ladders pl ON pl.plan_ladder_id = d.plan_ladder_id::uuid
WHERE s.subscription_id = ANY(sqlc.arg(subscription_ids)::uuid[])
ORDER BY s.subscription_id, pl.name, d.plan_ladder_id::uuid, d.holder_provision_id::uuid;
@@ -13,6 +13,7 @@ package fulfillment_test
import (
"context"
"database/sql"
"errors"
"strings"
"testing"
"time"
@@ -391,6 +392,40 @@ func TestSweep_ADowngradeThatLandsWhileDisplacedIsAppliedAndNotConferred(t *test
}
}
// F27: a downgrade scheduled before a grant ranked below the subscription's
// tier lands at the grant's tier, takes the ladder, and the grant is replaced.
func TestSweep_ADowngradeThatLandsAtALowerGrantsTierTakesTheLadder(t *testing.T) {
database, fx, mock, _, _, _ := onTier2(t)
ctx := context.Background()
if err := fulfillment.SwitchPlan(ctx, database, discardLogger(), stripetest.KeyMode(), fx.orgID, fx.ladderID, fx.priceID, time.Time{}, "member:switch"); err != nil {
t.Fatalf("downgrade: %v", err)
}
g := issueGrant(t, database, fx, fx.productID, false)
core := coreSubID(t, database, fx.stripeSubID)
if _, err := database.ExecContext(ctx, `UPDATE core.subscription_scheduled_changes
SET effective_at = NOW() - interval '1 minute'
WHERE subscription_id=$1 AND status='scheduled'`, core); err != nil {
t.Fatalf("make the row due: %v", err)
}
landed := fx.activeSub(fx.planItem())
landed.Schedule = mock.Sub.Schedule
mock.Sub = landed
if _, err := fulfillment.SweepDueScheduledChanges(ctx, database, discardLogger(), stripetest.KeyMode()); err != nil {
t.Fatalf("sweep: %v", err)
}
if got := subscriptionHolds(t, database, fx); got != fx.productID {
t.Errorf("the downgrade that landed at the grant's tier: S holds %v, want %s", got, fx.productID)
}
if grantDelivers(t, database, g.GrantID) {
t.Error("the grant kept the ladder after the downgrade landed at its tier")
}
if n := scalarInt(t, database, `SELECT count(*) FROM core.grant_replacements WHERE grant_id = $1 AND replacing_subscription_id = $2`,
g.GrantID, core); n != 1 {
t.Errorf("the grant is not recorded as replaced by S: %d replacements", n)
}
}
// secondSubscription is a second Stripe subscription of the fixture's customer
// on the product priced at stripePrice, with a Stripe item id of its own.
func secondSubscription(fx fixture, stripePrice string) *stripe.Subscription {
@@ -646,3 +681,87 @@ func TestSurplusEndRequestsTheOtherSubscriptions(t *testing.T) {
t.Errorf("entries after S2 dropped its item = S1 %d, S2 %d, want S1's alone", got1, got2)
}
}
// subscriptionHolds is the product the subscription holds on the fixture's
// ladder, "" when it holds none.
func subscriptionHolds(t *testing.T, database *sql.DB, fx fixture) string {
t.Helper()
var product string
err := database.QueryRowContext(context.Background(), `
SELECT l.product_id FROM core.pool_provision_ladders l
JOIN core.pool_provisions p ON p.provision_id = l.provision_id
WHERE p.subscription_id = $1 AND l.plan_ladder_id = $2 AND l.status = 'active'`,
coreSubID(t, database, fx.stripeSubID), fx.ladderID).Scan(&product)
if errors.Is(err, sql.ErrNoRows) {
return ""
}
if err != nil {
t.Fatalf("read the product the subscription holds: %v", err)
}
return product
}
// tierAtOrAboveRow is one case of
// TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder: the subscription on the
// fixture's tier (rank 0), a grant of the second tier (rank 1) over it, and
// the tier the subscription's item then moves to.
type tierAtOrAboveRow struct {
name string
// target names the tier the item moves to: "pro" is the granted tier,
// "max" the tier above it.
target string
}
// checkTierAtOrAbove runs one row.
func checkTierAtOrAbove(t *testing.T, row tierAtOrAboveRow) {
t.Helper()
database, fx, mock := subscribed(t)
pro, _, stripePro := secondTier(t, database, fx)
g := issueGrant(t, database, fx, pro, false)
want, stripeTarget := pro, stripePro
if row.target == "max" {
want, _, stripeTarget = addTier(t, database, fx, "max", 6000)
}
mock.Sub = fx.activeSub(item("si_plan_"+fx.sfx, stripeTarget))
reconcile(t, database, fx.stripeSubID, "stripe:customer.subscription.updated")
if got := subscriptionHolds(t, database, fx); got != want {
t.Errorf("%s: S holds %v, want %s", row.name, got, want)
}
if n := scalarInt(t, database, `SELECT count(*) FROM core.grant_replacements WHERE grant_id = $1 AND replacing_subscription_id = $2`,
g.GrantID, coreSubID(t, database, fx.stripeSubID)); n != 1 {
t.Errorf("%s: the grant is not recorded as replaced by S", row.name)
}
}
// A subscription whose item moves to the granted tier or above takes the
// ladder from the grant (openspec change grant-pauses-subscription-billing,
// design D8). The mock's subscription carries no pause, so the decision that
// follows has nothing to clear.
func TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder(t *testing.T) {
for _, row := range []tierAtOrAboveRow{
{name: "Max above a Pro grant", target: "max"},
{name: "Pro under a Pro grant over Plus", target: "pro"},
} {
checkTierAtOrAbove(t, row)
}
}
// The product a grant displaced never takes the ladder back, whatever its
// rank: a grant below the subscription's tier keeps the ladder.
func TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder(t *testing.T) {
database := dbtest.Open(t)
fx := seedFixture(t, database)
plus, _, stripePlus := secondTier(t, database, fx)
mock := &stripetest.MockBackend{Sub: fx.activeSub(item("si_plan_"+fx.sfx, stripePlus))}
t.Cleanup(stripetest.Install(mock))
reconcile(t, database, fx.stripeSubID, "test:created")
if got := subscriptionHolds(t, database, fx); got != plus {
t.Fatalf("precondition: S holds %v, want %s", got, plus)
}
basic := issueGrant(t, database, fx, fx.productID, false)
if !grantDelivers(t, database, basic.GrantID) {
t.Fatalf("precondition: the Basic grant does not deliver after it was issued over S's Plus")
}
reconcileLeavesTheGrant(t, database, fx, mock, basic, "a Basic grant under S's Plus lost the ladder")
}
@@ -1433,6 +1433,11 @@ func displacedOnPageRows() []displacedOnPageRow {
[]string{"tier"}, map[string][]entitlements.Rung{"tier": {{LadderID: "l-hosting", Rank: 1}}},
[]entitlements.Displacement{{LadderID: "l-hosting", LadderName: "Hosting", HolderProvisionID: "p-sub", HolderSource: "subscription"}},
displacedSubscription{Ladders: []displacedLadder{hosting}, Holders: []displacedHolder{{ProvisionID: "p-sub", Source: "subscription"}}}},
{"a subscription switched above the grant", "",
[]string{"tier"}, map[string][]entitlements.Rung{"tier": {{LadderID: "l-hosting", Rank: 3}}},
[]entitlements.Displacement{{LadderID: "l-hosting", LadderName: "Hosting", DisplacedProductID: "old", HolderProvisionID: "p-grant",
HolderSource: "grant", HolderProductID: "granted", HolderRank: 2, HolderRanked: true}},
displacedSubscription{}},
}
}
@@ -198,7 +198,7 @@ What (a) also decides, beyond the member's switch:
- 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`.
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, after `holder_source`, `d.holder_product_id::uuid AS holder_product_id`, `COALESCE(d.holder_rank, 0)::int AS holder_rank` and `(d.holder_rank IS NOT NULL)::boolean AS holder_ranked`, so the list's row type still converts to the account's. sqlc types a cast column as NOT NULL and offers no override for a function's column, so a bare `::int` would fail to scan a NULL rank; the flag carries the NULL instead of a second read of `core.plan_ladder_tiers`, which would state the rank twice. `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.
@@ -328,7 +328,7 @@ Stripe accepts the pause on a subscription a schedule manages, and keeps it thro
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 grant form's warning, `issueGrantSupersedeWarning`, reads "This grant would supersede a tier a subscription pays for; its billing pauses until the grant ends." It is the Product field's hint line, shown only once the operator chooses a product marked ⚠ (a form-level alert shown whenever the select offers a marked product read as a standing warning on every opening of the form, so the sentence sits with the choice it describes). 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.
@@ -519,7 +519,7 @@ Reused unchanged: "Cancel plan", "Keep plan", "Pay invoice", "Your plan change h
| 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 |
| W | Issue grant, the Product field's hint once a product marked ⚠ is chosen | `This grant 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; the holding subscription ended |
@@ -20,7 +20,7 @@ The decisions are recorded on #269 and #278: while a grant holds a ladder agains
- **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.
- **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}.". Once the operator chooses a product the grant form marks ⚠, the Product field's hint reads "This grant would supersede a tier a subscription pays for; its billing pauses until the grant ends."; the form shows no warning before that. 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
@@ -2,7 +2,7 @@
### 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.
When an operator's grant submission would cause `confer` to supersede a position currently held by a subscription-sourced provision, active or suspended, the Product select SHALL mark each such product with ⚠, and once the operator chooses a marked product, and not before, the Product field SHALL show, as its one hint line and not as an alert, an advisory warning stating that the subscription's billing pauses until the grant ends: "This grant would supersede a tier a subscription pays for; its billing pauses until the grant ends." A refused submission whose chosen product is marked SHALL render the hint shown (`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
@@ -13,14 +13,19 @@ When an operator's grant submission would cause `confer` to supersede a position
#### 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
- **THEN** the form SHALL mark the products that are tiers of that ladder as superseding a subscription and SHALL show the advisory warning once one of them is chosen
#### 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."
- **WHEN** an operator opens Issue grant and chooses a product marked ⚠
- **THEN** the Product field's hint reads "This grant would supersede a tier a subscription pays for; its billing pauses until the grant ends."
- **AND** it names no billing view
#### Scenario: No warning before a marked product is chosen
- **WHEN** an operator opens Issue grant on an organization whose Product select offers a product marked ⚠, and has chosen no product or an unmarked one
- **THEN** the form shows no supersession warning, and the ⚠ on each marked option is the only sign
### 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:
@@ -128,6 +128,11 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
- the list's paused title not rendered: caught by `TestSubscriptionsListMarksAPausedSubscription`, `want_new` `subscriptions list title =`.
- [x] 5.9 `make screens`: no change. No capture shows the warning: the captured organization's one subscription, Carlos's, holds no tier, so no product the Issue grant select offers carries the marker; the goldens of 5.5 pin the warning's text. The paused title is an attribute no capture shows; the golden pins it.
- [ ] 5.10 The supersession warning follows the choice (design Copy W; the spec's "Advisory warning when a grant would supersede a subscription-sourced position"). `issueGrantFormView` no longer adds the warning to the form's message; the lead stays. The Product field renders Copy W as its one hint line, hidden at rest and shown while the chosen option is one marked ⚠ (`IssuanceProductOption.SupersedesSubscription`), in the field's hint style, never an alert. A refused submission whose chosen product is marked renders it shown. The toggle is a general-purpose behaviour keyed by data attributes (a select names the hint it controls, and each marked option carries the attribute), in an external script under `internal/embeds/static/` loaded with `defer` (the CSP refuses inline scripts), so another form can reuse it; read `internal/forms` for how a field's hint and slots render and extend it there rather than writing markup in the handler. `issueGrantSupersedeWarning` keeps its name and reads Copy W.
- Tests: the render tests that compare the warning (`TestOrgEnrollmentIssueGrantPanel_Stacked`, `TestOrgEnrollmentProductsSection`, `rule_less_warning_test.go`) assert the hint is present and hidden at rest when a marked product is offered, absent when none is, shown in a refused submission that chose a marked product, and that the message holds the lead alone. A browser test (the walkthrough package's pattern, `test/e2e/operator-walkthroughs`) chooses a marked product and sees the hint, then an unmarked one and sees it hidden. The goldens `rich.html`, `rich-history-search.html` and `suspended-subscription.html`, rewritten with `-update` and read, change only in the message and the field's hint. Failure texts name the state (`at rest`, `after choosing a marked product`, `after choosing an unmarked product`, `in a refused submission`).
- Breaks: the hint rendered shown at rest; the hint rendered absent; the warning kept in the message; the script not loaded; the toggle inverted.
- `make screens`: `operator-organization-detail-open` and `-invalid` change, at both widths: since section 7, Carlos Member's canceling subscription holds the Demo Ladder, so his form offers marked products and the accepted baseline shows the alert; hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the open form with a marked product chosen, beside the change's screens.
## 6. An hourly sweep asks again for a subscription whose pause disagrees with the rule
- [x] 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; the join also requires `m.stripe_subscription_id IS NOT NULL`, because `ApplySubscriptionCollection` skips a mapping with no Stripe id with L3 (3.3), so such a subscription would drift every hour; its generated code lands in `internal/integrations/stripe/store/subscription_mappings.sql.go`, which every break of the query edits); `ListCurrentConferringProductsBySubscriptionIDs` (billing, new: the subscription id and product id of each current item, `ended_at IS NULL`, whose product's `entitlement_set_id IS NOT NULL`, for the listed ids, ordered by subscription id and product id; the sweep reads it in place of an items read, and `ListCurrentSubscriptionItemsBySubscriptionIDs` stays as it is, because a column added to it would break `productsBySubscription`'s row-type conversion, `internal/server/operator_enrollment.go:1847-1853`); `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`.
@@ -211,28 +216,35 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
## 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 `entitlements.DisplacementsBySubscription` (6.2) 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:
- [x] 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.
- [x] 8.2 The three queries name seven aliases and select `d.holder_product_id::uuid AS holder_product_id`, `COALESCE(d.holder_rank, 0)::int AS holder_rank` and `(d.holder_rank IS NOT NULL)::boolean AS holder_ranked` after `holder_source` (design D8: a bare `::int` is typed NOT NULL and cannot scan a NULL rank); their comments say the rank decides the exception. `make sqlc-generate`. `Displacement` gains `HolderProductID`, `HolderRank` and `HolderRanked`; `DisplacementsFromRows` and `entitlements.DisplacementsBySubscription` (6.2) fill them.
- [x] 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.
- [x] 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.
- `TestSweep_ADowngradeThatLandsAtALowerGrantsTierTakesTheLadder` (F27): a scheduled downgrade lands at the tier of a lower grant that holds the ladder; the subscription takes the ladder and the grant is recorded as replaced. Failure texts: `the downgrade that landed at the grant's tier: S holds %v, want %s`; `the grant kept the ladder after the downgrade landed at its tier`; `the grant is not recorded as replaced by S: %d replacements`.
- `TestDisplacementRowsCarryTheHolder` (`internal/entitlements/displacement_test.go`): `DisplacementsFromRows` and `DisplacementsBySubscription` carry the holder's product, rank and ranked flag, which the organization page, the subscriptions list and the drift sweep read. Failure texts: `DisplacementsFromRows = %+v, want %+v`; `DisplacementsBySubscription = %+v, want %+v`.
- `TestDisplacementHolderRankMigrationUpDownUp` also compares `pg_get_function_result` after each step, so the five-name alias form is shown to name the first five columns. Failure text: `after %s, the function returns %s, want %s`.
- `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:
- [x] 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.
- [x] 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.
- the rank read as the displaced product's (`t.product_id = d.product_id`, command record): `exit` 1;
- `HolderRanked` not read from the reconcile's rows: caught by `TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder`, `want_new` `Max above a Pro grant: S holds`; and from the account's rows: caught by `TestDisplacementRowsCarryTheHolder`, `want_new` `DisplacementsBySubscription =`;
- the holder's rank not carried by the reconcile's query (`0::int AS holder_rank` in the generated constant): caught by `TestSweep_ADowngradeThatLandsWhileDisplacedIsAppliedAndNotConferred`, `want_new` `the downgrade was conferred over the grant`; the ranked flag not carried (`false::boolean AS holder_ranked`): caught by `TestSweep_ADowngradeThatLandsAtALowerGrantsTierTakesTheLadder`, `want_new` `the downgrade that landed at the grant's tier: S holds`;
- the two columns placed first in the function (command record): caught by `TestDisplacementHolderRankMigrationUpDownUp`, `want_new` `the function returns TABLE(holder_product_id`;
- section 7's three breaks of `core.subscription_displacements` (`AND NOT h.default_sourced` removed, an `ended` position counted as a holder, the holder required to be the displacement's own successor), which edited migration 00034 and now edit 00037, since 00037 drops and recreates the function; section 7's lists carry the same forms.
- [x] 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)