Record the collection pause Stripe reports on each subscription row
Second section of #269's change. Migration 00036 adds three columns to core.subscriptions: pause_collection_behavior (NULL when collection is not paused, with no check so a behavior a later API version adds does not stop the reconcile), pause_collection_resumes_at, and pause_collection_marked (true when the pause carries the console's own marker). Every reconcile writes them from the subscription it fetched, in both branches of upsertSubscription (recordCollectionMirror), through the new UpdateSubscriptionCollection query, so the status writers cannot erase them. The operator Overview's Monthly recurring headline leaves a paused subscription out, as it does a trialing one; the caption still counts it by status. The reader role's column list gains the three columns. The test kit gains PauseCollection and ForeignPause. The 39 subscription trace goldens each gain the UpdateSubscriptionCollection line after the statement that writes the row; console-reader-columns.txt gains three lines. ListSubscriptionsPage's pause_collection_behavior has no reader in this section; section 5's TestSubscriptionsListMarksAPausedSubscription reads it. Tests: TestSubscriptionCollectionPauseMigrationUpDownUp, TestReconcile_MirrorsTheCollectionPause (six rows, a cleared pause among them), TestOverviewMonthlyRecurringLeavesOutAPausedSubscription. Review: one major, the migration header and the design claimed status had no check (it has chk_subscriptions_status_valid); corrected in the header, design D3 and item 2.1. Added the row proving a cleared pause is recorded and its break; writer renamed recordCollectionMirror; doc comments and the payments model's sentence reworded. Breaks: 8 of 8 caught. Full suite on reset databases: 4740 pass, 14 skip. make screens: only regenerated ids on the person and invoice pages. The change's text also takes the fifth review round of its draft: the missing spec deltas for plan-move controls, the demo ledger and the Tier changes labels, and the refusal tests beside the switch.
This commit is contained in:
@@ -23,7 +23,7 @@ Database objects sit in the `core` schema (defined in `internal/db/migrations/00
|
||||
| Piece | What it is | Where |
|
||||
|---|---|---|
|
||||
| `core.accounts` | Billing accounts, each owned by exactly one organization; a default account is created during signup provisioning. Its `status` column (default `active`) renders as a badge on the operator billing-accounts list; the org-detail billing summary also reads it into its view model but never renders it. No application code path changes the column after creation: the update query exists in the generated querier and nothing calls it, so every account reads `active` today regardless of what happens to its subscriptions. `next_invoice_number` [db] is the account's invoice-numbering counter (default `1`): `AssignNextInvoiceNumber` increments it and returns the prior value in one statement, called inside the same transaction that projects the invoice, so a rolled-back projection leaves no gap | `00001_init.sql`; `00013_invoice_numbers.sql`; `internal/provisioning/provisioning.go` |
|
||||
| `core.subscriptions` | The standing agreement projected from Stripe: status (CHECK-pinned to Stripe's eight-value vocabulary), billing-period start/end, `cancel_at_period_end`, and the three commitment columns (see the commitment gloss under Invariants) | `00001_init.sql`; `00010_schema_hardening.sql` |
|
||||
| `core.subscriptions` | The standing agreement projected from Stripe: status (CHECK-pinned to Stripe's eight-value vocabulary), billing-period start/end, `cancel_at_period_end`, the collection pause Stripe reports (`pause_collection_behavior`, `pause_collection_resumes_at`, and `pause_collection_marked`, true when the subscription's metadata carries the console's own marker), and the three commitment columns (see the commitment gloss under Invariants). The Monthly recurring headline leaves out an `active` subscription whose pause is recorded | `00001_init.sql`; `00010_schema_hardening.sql`; `00036_subscription_collection_pause.sql` |
|
||||
| `core.subscription_items` | The per-product, per-price lines of a subscription, with quantity. `ended_at` is set by the reconciler when the line's Stripe item is no longer on the subscription (a schedule's phase change replaces the item); the row stays because invoice lines reference it, and every reader of a subscription's current lines skips it | `00001_init.sql`; `00021_subscription_item_ended.sql` |
|
||||
| `core.subscription_changes` | Append-only history of status transitions (`previous_status` → `new_status`), each carrying an attribution string saying what triggered it | `00001_init.sql` |
|
||||
| `core.subscription_scheduled_changes` | The intent ledger: future plan switches, quantity changes, and cancellations, with when they fire and their lifecycle status | `00001_init.sql` |
|
||||
@@ -37,7 +37,7 @@ Database objects sit in the `core` schema (defined in `internal/db/migrations/00
|
||||
| Invoice reconcile | `ReconcileInvoice`: reads the invoice, its lines and the charges of its payment intent back from the Stripe API at the SDK's version, takes a per-invoice lock, and converges the invoice (created and numbered by the first run that finds it issued, then only moved forward), its lines (inserted once), and one payment per settled charge | `internal/integrations/stripe/workflows/invoice_reconcile.go` |
|
||||
| Invoice sweep | The hourly Temporal schedule (`stripe-invoice-sweep`), also triggered at every boot, that reads back invoice mappings never read back, open invoices last read more than a day ago, and invoices named by dead-lettered invoice events, then fills payment methods and subscription links mapped since; it never renumbers, deletes, or reconciles a subscription. The Stripe provider page states when it last finished | `internal/integrations/stripe/workflows/invoice_sweep.go` |
|
||||
| Outbox drainer | The recurring worker that executes outbox rows (create Stripe product / price / customer), retrying with backoff until a cap parks the row as `dead_letter` for operator-driven retry | `internal/integrations/stripe/workflows/outbox.go` |
|
||||
| Reconciler | `ReconcileSubscription`: refetches the subscription from the Stripe API and converges console records and provisions to match. It runs on `customer.subscription.created`, `.updated` and `.deleted`, on `checkout.session.completed` for a subscription, on the checkout return (for the customer's most recent subscription), in the scheduled-change sweeper when it reaches a period-end downgrade or fires a term-boundary switch or cancellation, after each member plan change, and from an invoice event's reconcile when the invoice's subscription or one of its line items has no mapping yet. A desired product whose ladder another plan took from the subscription and holds is left alone and logged, while the subscription keeps billing; a subscription that pays for two tiers of one ladder gets the higher-ranked one, the other logged as a warning and not conferred (a subscription that alternated between the two before the reconcile chose by rank moves to the higher-ranked tier at its next reconcile and stays there); the reconcile writes in product id order under the pool row | `internal/fulfillment/reconcile.go` |
|
||||
| Reconciler | `ReconcileSubscription`: refetches the subscription from the Stripe API and converges console records and provisions to match. It runs on `customer.subscription.created`, `.updated` and `.deleted`, on `checkout.session.completed` for a subscription, on the checkout return (for the customer's most recent subscription), in the scheduled-change sweeper when it reaches a period-end downgrade or fires a term-boundary switch or cancellation, after each member plan change, and from an invoice event's reconcile when the invoice's subscription or one of its line items has no mapping yet. The reconcile writes the collection pause Stripe reports onto the subscription row on every run. A desired product whose ladder another plan took from the subscription and holds is left alone and logged, while the subscription keeps billing; a subscription that pays for two tiers of one ladder gets the higher-ranked one, the other logged as a warning and not conferred (a subscription that alternated between the two before the reconcile chose by rank moves to the higher-ranked tier at its next reconcile and stays there); the reconcile writes in product id order under the pool row | `internal/fulfillment/reconcile.go` |
|
||||
| Plan-change mechanics | Member-initiated switch and cancel, a preview of the price difference before switching, the commitment gating, and the scheduled-change bookkeeping | `internal/fulfillment/plan_change.go` |
|
||||
| Scheduled-change sweeper | The hourly backstop that fires due scheduled changes Stripe itself cannot fire | `internal/fulfillment/sweep.go`; `internal/workflows/billing/` |
|
||||
| Checkout | Runs the guard checks and starts the Stripe Checkout session; also creates the Stripe customer synchronously if the organization has none yet | `internal/server/billing.go` |
|
||||
@@ -80,5 +80,5 @@ These axes are independent; most billing bugs come from reading one as another:
|
||||
- **Eager vs asynchronous fulfillment** — the checkout return page reconciles immediately so the member sees their purchase land; the webhook pipeline reconciles the same subscription again later. Safe only because the reconciler is serialized and convergent (invariant 4).
|
||||
- **Recorded vs happened** — an invoice's or payment's `created_at` is when the console wrote the row, which for an invoice projected late by the sweep can be days after Stripe issued it; `issued_at`, `paid_at`, `voided_at` and `failed_at` are when it happened, as Stripe reports it. Lists and the activity timeline read the second kind, never `created_at`.
|
||||
- **Money representation** — integer minor units plus a per-row ISO currency code, always; cross-currency totals stay per-currency buckets and are never converted.
|
||||
- **Status classification** — Stripe's many subscription statuses collapse into four behavioral buckets: entitlement-bearing (active, trialing); suspended (past due, unpaid, paused — the provisions pause delivery without ending, and the member surfaces show the plan as the current plan with its state); ended (canceled, incomplete-expired — the conferrals end, and the organization's baseline default plan is restored if nothing else covers it); ignored (incomplete — recorded without provisioning). Pausing a subscription's payment collection in Stripe (`pause_collection`) does not make it `paused`: Stripe leaves the status unchanged, so an active subscription keeps delivering. A subscription becomes `paused` when its trial ends without a payment method and its trial settings say to pause (the console sets none), and Stripe creates no invoice for it while it is paused, where it keeps invoicing a past-due or unpaid one; text that says a suspended subscription keeps billing is false for a paused one.
|
||||
- **Status classification** — Stripe's many subscription statuses collapse into four behavioral buckets: entitlement-bearing (active, trialing); suspended (past due, unpaid, paused — the provisions pause delivery without ending, and the member surfaces show the plan as the current plan with its state); ended (canceled, incomplete-expired — the conferrals end, and the organization's baseline default plan is restored if nothing else covers it); ignored (incomplete — recorded without provisioning). Pausing a subscription's payment collection in Stripe (`pause_collection`) does not make it `paused`: Stripe leaves the status unchanged, so an active subscription keeps delivering. A subscription that grants displace delivers nothing while they hold its ladders, and the console pauses its collection. A subscription becomes `paused` when its trial ends without a payment method and its trial settings say to pause (the console sets none), and Stripe creates no invoice for it while it is paused, where it keeps invoicing a past-due or unpaid one; text that says a suspended subscription keeps billing is false for a paused one.
|
||||
- **Projected data carries a recency, not a completeness guarantee** — invoices, payments, and subscription state are projections from processed webhook events (see "Sync authority per entity" above), so an unchanged or empty view is never proof that nothing happened, only that nothing has been projected yet. The operator billing surfaces name the most recent processed-event time so stale data is visibly stale; the member invoice history states the same fact in plain language, without exposing a timestamp.
|
||||
|
||||
@@ -162,7 +162,7 @@ func (q *Queries) GetLatestInvoiceByBillingAccountID(ctx context.Context, billin
|
||||
}
|
||||
|
||||
const getLatestSubscriptionByBillingAccountID = `-- name: GetLatestSubscriptionByBillingAccountID :one
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy FROM core.subscriptions
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy, pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked FROM core.subscriptions
|
||||
WHERE billing_account_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
@@ -187,6 +187,9 @@ func (q *Queries) GetLatestSubscriptionByBillingAccountID(ctx context.Context, b
|
||||
&i.CommitmentEnd,
|
||||
&i.CommitmentRenewal,
|
||||
&i.EarlyTerminationPolicy,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.PauseCollectionResumesAt,
|
||||
&i.PauseCollectionMarked,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
+16
-13
@@ -153,19 +153,22 @@ type Product struct {
|
||||
}
|
||||
|
||||
type Subscription struct {
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
BillingAccountID string `json:"billing_account_id"`
|
||||
Status string `json:"status"`
|
||||
CurrentPeriodStart sql.NullTime `json:"current_period_start"`
|
||||
CurrentPeriodEnd sql.NullTime `json:"current_period_end"`
|
||||
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
|
||||
CanceledAt sql.NullTime `json:"canceled_at"`
|
||||
EndedAt sql.NullTime `json:"ended_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CommitmentEnd sql.NullTime `json:"commitment_end"`
|
||||
CommitmentRenewal sql.NullString `json:"commitment_renewal"`
|
||||
EarlyTerminationPolicy sql.NullString `json:"early_termination_policy"`
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
BillingAccountID string `json:"billing_account_id"`
|
||||
Status string `json:"status"`
|
||||
CurrentPeriodStart sql.NullTime `json:"current_period_start"`
|
||||
CurrentPeriodEnd sql.NullTime `json:"current_period_end"`
|
||||
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
|
||||
CanceledAt sql.NullTime `json:"canceled_at"`
|
||||
EndedAt sql.NullTime `json:"ended_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CommitmentEnd sql.NullTime `json:"commitment_end"`
|
||||
CommitmentRenewal sql.NullString `json:"commitment_renewal"`
|
||||
EarlyTerminationPolicy sql.NullString `json:"early_termination_policy"`
|
||||
PauseCollectionBehavior sql.NullString `json:"pause_collection_behavior"`
|
||||
PauseCollectionResumesAt sql.NullTime `json:"pause_collection_resumes_at"`
|
||||
PauseCollectionMarked bool `json:"pause_collection_marked"`
|
||||
}
|
||||
|
||||
type SubscriptionChange struct {
|
||||
|
||||
@@ -492,7 +492,9 @@ type Querier interface {
|
||||
// explicitly out of scope: forge issue #79). Monthly-normalized: month prices at
|
||||
// face value, year at one-twelfth, each times item quantity. Active only —
|
||||
// trialing subscriptions pay nothing today and counting their money would
|
||||
// overstate. Current items only: an item Stripe replaced is no longer billed.
|
||||
// overstate. A subscription whose collection is paused (any pause, the console's
|
||||
// or the Dashboard's) is left out: Stripe collects nothing on it. Current items
|
||||
// only: an item Stripe replaced is no longer billed.
|
||||
SumMonthlyRecurringByCurrency(ctx context.Context) ([]SumMonthlyRecurringByCurrencyRow, error)
|
||||
// A new scheduled change (or an immediate action) supersedes any still-pending
|
||||
// intent on the same subscription.
|
||||
@@ -505,6 +507,9 @@ type Querier interface {
|
||||
UpdatePaymentMethodSafeFields(ctx context.Context, arg UpdatePaymentMethodSafeFieldsParams) (PaymentMethod, error)
|
||||
UpdatePlanLadder(ctx context.Context, arg UpdatePlanLadderParams) (PlanLadder, error)
|
||||
UpdateProduct(ctx context.Context, arg UpdateProductParams) (Product, error)
|
||||
// Records the collection pause Stripe reports for the subscription; every
|
||||
// reconcile writes it from the subscription it fetched.
|
||||
UpdateSubscriptionCollection(ctx context.Context, arg UpdateSubscriptionCollectionParams) error
|
||||
// Converge a core item row after an in-place Stripe price modification (paid->paid
|
||||
// switch): the Stripe item id is unchanged but it now carries a new price/product.
|
||||
UpdateSubscriptionItemPriceProduct(ctx context.Context, arg UpdateSubscriptionItemPriceProductParams) (SubscriptionItem, error)
|
||||
|
||||
@@ -23,6 +23,15 @@ SET status = $2,
|
||||
WHERE subscription_id = $1
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateSubscriptionCollection :exec
|
||||
-- Records the collection pause Stripe reports for the subscription; every
|
||||
-- reconcile writes it from the subscription it fetched.
|
||||
UPDATE core.subscriptions
|
||||
SET pause_collection_behavior = $2,
|
||||
pause_collection_resumes_at = $3,
|
||||
pause_collection_marked = $4
|
||||
WHERE subscription_id = $1;
|
||||
|
||||
-- name: ListSubscriptionsPage :many
|
||||
-- Operator subscriptions view, paged/searched/filtered (operator-list-scale
|
||||
-- UX-4; operator-billing-views D8). Carries ba.org_id so the handler can
|
||||
@@ -57,6 +66,7 @@ SELECT
|
||||
s.current_period_start,
|
||||
s.current_period_end,
|
||||
s.cancel_at_period_end,
|
||||
s.pause_collection_behavior,
|
||||
s.canceled_at,
|
||||
s.ended_at,
|
||||
s.created_at,
|
||||
@@ -109,7 +119,9 @@ FROM core.subscriptions;
|
||||
-- explicitly out of scope: forge issue #79). Monthly-normalized: month prices at
|
||||
-- face value, year at one-twelfth, each times item quantity. Active only —
|
||||
-- trialing subscriptions pay nothing today and counting their money would
|
||||
-- overstate. Current items only: an item Stripe replaced is no longer billed.
|
||||
-- overstate. A subscription whose collection is paused (any pause, the console's
|
||||
-- or the Dashboard's) is left out: Stripe collects nothing on it. Current items
|
||||
-- only: an item Stripe replaced is no longer billed.
|
||||
SELECT p.currency,
|
||||
SUM(
|
||||
CASE p.recurring_interval
|
||||
@@ -121,6 +133,6 @@ SELECT p.currency,
|
||||
FROM core.subscriptions s
|
||||
JOIN core.subscription_items si ON si.subscription_id = s.subscription_id
|
||||
JOIN core.prices p ON p.price_id = si.price_id
|
||||
WHERE s.status = 'active' AND si.ended_at IS NULL AND p.recurring_interval IS NOT NULL
|
||||
WHERE s.status = 'active' AND s.pause_collection_behavior IS NULL AND si.ended_at IS NULL AND p.recurring_interval IS NOT NULL
|
||||
GROUP BY p.currency
|
||||
ORDER BY monthly_cents DESC;
|
||||
|
||||
@@ -81,7 +81,7 @@ func (q *Queries) CountSubscriptionsPage(ctx context.Context, arg CountSubscript
|
||||
const createSubscription = `-- name: CreateSubscription :one
|
||||
INSERT INTO core.subscriptions (billing_account_id, status, current_period_start, current_period_end)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy
|
||||
RETURNING subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy, pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked
|
||||
`
|
||||
|
||||
type CreateSubscriptionParams struct {
|
||||
@@ -113,12 +113,15 @@ func (q *Queries) CreateSubscription(ctx context.Context, arg CreateSubscription
|
||||
&i.CommitmentEnd,
|
||||
&i.CommitmentRenewal,
|
||||
&i.EarlyTerminationPolicy,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.PauseCollectionResumesAt,
|
||||
&i.PauseCollectionMarked,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSubscriptionByID = `-- name: GetSubscriptionByID :one
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy FROM core.subscriptions
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy, pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked FROM core.subscriptions
|
||||
WHERE subscription_id = $1
|
||||
`
|
||||
|
||||
@@ -139,12 +142,15 @@ func (q *Queries) GetSubscriptionByID(ctx context.Context, subscriptionID string
|
||||
&i.CommitmentEnd,
|
||||
&i.CommitmentRenewal,
|
||||
&i.EarlyTerminationPolicy,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.PauseCollectionResumesAt,
|
||||
&i.PauseCollectionMarked,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSubscriptionsByBillingAccountID = `-- name: GetSubscriptionsByBillingAccountID :many
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy FROM core.subscriptions
|
||||
SELECT subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy, pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked FROM core.subscriptions
|
||||
WHERE billing_account_id = $1
|
||||
ORDER BY created_at DESC
|
||||
`
|
||||
@@ -172,6 +178,9 @@ func (q *Queries) GetSubscriptionsByBillingAccountID(ctx context.Context, billin
|
||||
&i.CommitmentEnd,
|
||||
&i.CommitmentRenewal,
|
||||
&i.EarlyTerminationPolicy,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.PauseCollectionResumesAt,
|
||||
&i.PauseCollectionMarked,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -195,6 +204,7 @@ SELECT
|
||||
s.current_period_start,
|
||||
s.current_period_end,
|
||||
s.cancel_at_period_end,
|
||||
s.pause_collection_behavior,
|
||||
s.canceled_at,
|
||||
s.ended_at,
|
||||
s.created_at,
|
||||
@@ -223,19 +233,20 @@ type ListSubscriptionsPageParams struct {
|
||||
}
|
||||
|
||||
type ListSubscriptionsPageRow struct {
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
BillingAccountID string `json:"billing_account_id"`
|
||||
OrgID string `json:"org_id"`
|
||||
Status string `json:"status"`
|
||||
CurrentPeriodStart sql.NullTime `json:"current_period_start"`
|
||||
CurrentPeriodEnd sql.NullTime `json:"current_period_end"`
|
||||
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
|
||||
CanceledAt sql.NullTime `json:"canceled_at"`
|
||||
EndedAt sql.NullTime `json:"ended_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
BillingAccountName string `json:"billing_account_name"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
BillingAccountID string `json:"billing_account_id"`
|
||||
OrgID string `json:"org_id"`
|
||||
Status string `json:"status"`
|
||||
CurrentPeriodStart sql.NullTime `json:"current_period_start"`
|
||||
CurrentPeriodEnd sql.NullTime `json:"current_period_end"`
|
||||
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
|
||||
PauseCollectionBehavior sql.NullString `json:"pause_collection_behavior"`
|
||||
CanceledAt sql.NullTime `json:"canceled_at"`
|
||||
EndedAt sql.NullTime `json:"ended_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
BillingAccountName string `json:"billing_account_name"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
}
|
||||
|
||||
// Operator subscriptions view, paged/searched/filtered (operator-list-scale
|
||||
@@ -287,6 +298,7 @@ func (q *Queries) ListSubscriptionsPage(ctx context.Context, arg ListSubscriptio
|
||||
&i.CurrentPeriodStart,
|
||||
&i.CurrentPeriodEnd,
|
||||
&i.CancelAtPeriodEnd,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.CanceledAt,
|
||||
&i.EndedAt,
|
||||
&i.CreatedAt,
|
||||
@@ -319,7 +331,7 @@ SELECT p.currency,
|
||||
FROM core.subscriptions s
|
||||
JOIN core.subscription_items si ON si.subscription_id = s.subscription_id
|
||||
JOIN core.prices p ON p.price_id = si.price_id
|
||||
WHERE s.status = 'active' AND si.ended_at IS NULL AND p.recurring_interval IS NOT NULL
|
||||
WHERE s.status = 'active' AND s.pause_collection_behavior IS NULL AND si.ended_at IS NULL AND p.recurring_interval IS NOT NULL
|
||||
GROUP BY p.currency
|
||||
ORDER BY monthly_cents DESC
|
||||
`
|
||||
@@ -334,7 +346,9 @@ type SumMonthlyRecurringByCurrencyRow struct {
|
||||
// explicitly out of scope: forge issue #79). Monthly-normalized: month prices at
|
||||
// face value, year at one-twelfth, each times item quantity. Active only —
|
||||
// trialing subscriptions pay nothing today and counting their money would
|
||||
// overstate. Current items only: an item Stripe replaced is no longer billed.
|
||||
// overstate. A subscription whose collection is paused (any pause, the console's
|
||||
// or the Dashboard's) is left out: Stripe collects nothing on it. Current items
|
||||
// only: an item Stripe replaced is no longer billed.
|
||||
func (q *Queries) SumMonthlyRecurringByCurrency(ctx context.Context) ([]SumMonthlyRecurringByCurrencyRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, sumMonthlyRecurringByCurrency)
|
||||
if err != nil {
|
||||
@@ -358,6 +372,33 @@ func (q *Queries) SumMonthlyRecurringByCurrency(ctx context.Context) ([]SumMonth
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const updateSubscriptionCollection = `-- name: UpdateSubscriptionCollection :exec
|
||||
UPDATE core.subscriptions
|
||||
SET pause_collection_behavior = $2,
|
||||
pause_collection_resumes_at = $3,
|
||||
pause_collection_marked = $4
|
||||
WHERE subscription_id = $1
|
||||
`
|
||||
|
||||
type UpdateSubscriptionCollectionParams struct {
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
PauseCollectionBehavior sql.NullString `json:"pause_collection_behavior"`
|
||||
PauseCollectionResumesAt sql.NullTime `json:"pause_collection_resumes_at"`
|
||||
PauseCollectionMarked bool `json:"pause_collection_marked"`
|
||||
}
|
||||
|
||||
// Records the collection pause Stripe reports for the subscription; every
|
||||
// reconcile writes it from the subscription it fetched.
|
||||
func (q *Queries) UpdateSubscriptionCollection(ctx context.Context, arg UpdateSubscriptionCollectionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, updateSubscriptionCollection,
|
||||
arg.SubscriptionID,
|
||||
arg.PauseCollectionBehavior,
|
||||
arg.PauseCollectionResumesAt,
|
||||
arg.PauseCollectionMarked,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateSubscriptionStatus = `-- name: UpdateSubscriptionStatus :one
|
||||
UPDATE core.subscriptions
|
||||
SET status = $2,
|
||||
@@ -367,7 +408,7 @@ SET status = $2,
|
||||
canceled_at = $6,
|
||||
ended_at = $7
|
||||
WHERE subscription_id = $1
|
||||
RETURNING subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy
|
||||
RETURNING subscription_id, billing_account_id, status, current_period_start, current_period_end, cancel_at_period_end, canceled_at, ended_at, created_at, updated_at, commitment_end, commitment_renewal, early_termination_policy, pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked
|
||||
`
|
||||
|
||||
type UpdateSubscriptionStatusParams struct {
|
||||
@@ -405,6 +446,9 @@ func (q *Queries) UpdateSubscriptionStatus(ctx context.Context, arg UpdateSubscr
|
||||
&i.CommitmentEnd,
|
||||
&i.CommitmentRenewal,
|
||||
&i.EarlyTerminationPolicy,
|
||||
&i.PauseCollectionBehavior,
|
||||
&i.PauseCollectionResumesAt,
|
||||
&i.PauseCollectionMarked,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
-- SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
-- SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
-- +goose Up
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- A subscription row records the collection pause Stripe reports. Every
|
||||
-- reconcile writes the three columns from the subscription it fetched:
|
||||
-- * pause_collection_behavior: the behavior of Stripe's pause_collection,
|
||||
-- NULL when collection is not paused. No check constrains it, so a behavior
|
||||
-- a later API version adds does not stop the reconcile of every
|
||||
-- subscription.
|
||||
-- * pause_collection_resumes_at: the pause's resumes_at, NULL when unset.
|
||||
-- * pause_collection_marked: true when the subscription's metadata carries
|
||||
-- the console's own marker, so the console's pause is the one whose
|
||||
-- marker column is true and a pause made in the Dashboard is the one
|
||||
-- whose marker column is false.
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
ALTER TABLE core.subscriptions
|
||||
ADD COLUMN pause_collection_behavior TEXT NULL,
|
||||
ADD COLUMN pause_collection_resumes_at TIMESTAMPTZ NULL,
|
||||
ADD COLUMN pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE core.subscriptions
|
||||
DROP COLUMN pause_collection_marked,
|
||||
DROP COLUMN pause_collection_resumes_at,
|
||||
DROP COLUMN pause_collection_behavior;
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package db_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/db"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
const (
|
||||
collectionPauseVersion = 36
|
||||
collectionPausePrevious = 35
|
||||
)
|
||||
|
||||
var collectionPauseColumns = []string{
|
||||
"pause_collection_behavior",
|
||||
"pause_collection_resumes_at",
|
||||
"pause_collection_marked",
|
||||
}
|
||||
|
||||
func TestSubscriptionCollectionPauseMigrationUpDownUp(t *testing.T) {
|
||||
scratch := dbtest.Connect(t, dbtest.Scratch(t))
|
||||
core := db.BaseSources()[0]
|
||||
q := dbtest.On(t, scratch)
|
||||
|
||||
dbtest.UpTo(t, scratch, core, collectionPausePrevious)
|
||||
requireCollectionPauseColumns(t, q, "migrating to 35", false)
|
||||
|
||||
dbtest.ApplyVersion(t, scratch, core, collectionPauseVersion, true)
|
||||
requireCollectionPauseColumns(t, q, "the first up", true)
|
||||
|
||||
dbtest.ApplyVersion(t, scratch, core, collectionPauseVersion, false)
|
||||
requireCollectionPauseColumns(t, q, "the down", false)
|
||||
|
||||
dbtest.ApplyVersion(t, scratch, core, collectionPauseVersion, true)
|
||||
requireCollectionPauseColumns(t, q, "the second up", true)
|
||||
}
|
||||
|
||||
func requireCollectionPauseColumns(t *testing.T, q *dbtest.Q, after string, want bool) {
|
||||
t.Helper()
|
||||
for _, column := range collectionPauseColumns {
|
||||
got := q.Int(`SELECT count(*) FROM information_schema.columns
|
||||
WHERE table_schema = 'core' AND table_name = 'subscriptions' AND column_name = $1`, column) == 1
|
||||
if got != want {
|
||||
t.Errorf("after %s, column %s present = %v, want %v", after, column, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package fulfillment
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
|
||||
"github.com/stripe/stripe-go/v81"
|
||||
)
|
||||
|
||||
// The metadata key and value that mark a collection pause as the console's.
|
||||
// A subscription whose pause_collection carries the marker was paused by the
|
||||
// console; one without it was paused elsewhere, in the Dashboard, and stays as
|
||||
// its maker left it. The schedules follow the same precedent: the console
|
||||
// releases only a schedule carrying its own metadata (findSpentSchedule).
|
||||
const (
|
||||
collectionMarkerKey = "member_console_collection"
|
||||
collectionMarkerValue = "paused_for_grant"
|
||||
)
|
||||
|
||||
// collectionMirror maps the fetched subscription's pause to the three columns
|
||||
// of its row: the pause's behavior and resumes_at (NULL for no pause) and
|
||||
// whether the metadata carries the console's marker. It reads no row.
|
||||
func collectionMirror(sub *stripe.Subscription) (behavior sql.NullString, resumesAt sql.NullTime, marked bool) {
|
||||
marked = sub.Metadata[collectionMarkerKey] == collectionMarkerValue
|
||||
if sub.PauseCollection == nil {
|
||||
return sql.NullString{}, sql.NullTime{}, marked
|
||||
}
|
||||
return sql.NullString{String: string(sub.PauseCollection.Behavior), Valid: true},
|
||||
unixToNullTime(sub.PauseCollection.ResumesAt), marked
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package fulfillment_test
|
||||
|
||||
// The subscription row mirrors the collection pause Stripe reports (openspec
|
||||
// change grant-pauses-subscription-billing, design D3, tasks 2.3 and 2.6).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stripe "github.com/stripe/stripe-go/v81"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/stripetest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
)
|
||||
|
||||
type mirrorRow struct {
|
||||
name string
|
||||
pause *stripe.SubscriptionPauseCollection
|
||||
marked bool
|
||||
before *stripe.SubscriptionPauseCollection // the pause of the first reconcile
|
||||
beforeMarked bool
|
||||
firstSight bool // the row's state is the subscription's first reconcile
|
||||
behavior string
|
||||
hasResume bool
|
||||
wantMark bool
|
||||
}
|
||||
|
||||
func mirrorRows(resumesAt time.Time) []mirrorRow {
|
||||
return []mirrorRow{
|
||||
{name: "no pause"},
|
||||
{name: "the console's pause", pause: &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorVoid},
|
||||
marked: true, behavior: "void", wantMark: true},
|
||||
{name: "a pause made in the Dashboard", pause: &stripe.SubscriptionPauseCollection{
|
||||
Behavior: stripe.SubscriptionPauseCollectionBehaviorMarkUncollectible, ResumesAt: resumesAt.Unix()},
|
||||
behavior: "mark_uncollectible", hasResume: true},
|
||||
{name: "a marker with no pause", marked: true, wantMark: true},
|
||||
{name: "the console's pause cleared", before: &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorVoid},
|
||||
beforeMarked: true},
|
||||
{name: "first sight, the console's pause", pause: &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorVoid},
|
||||
marked: true, firstSight: true, behavior: "void", wantMark: true},
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcile_MirrorsTheCollectionPause(t *testing.T) {
|
||||
resumesAt := time.Now().Add(72 * time.Hour).Truncate(time.Second)
|
||||
for _, row := range mirrorRows(resumesAt) {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
checkMirror(t, row, resumesAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func checkMirror(t *testing.T, row mirrorRow, resumesAt time.Time) {
|
||||
t.Helper()
|
||||
database := dbtest.Open(t)
|
||||
fx := seedFixture(t, database)
|
||||
mock := &stripetest.MockBackend{Sub: fx.activeSub(fx.planItem())}
|
||||
t.Cleanup(stripetest.Install(mock))
|
||||
if !row.firstSight {
|
||||
first := fx.activeSub(fx.planItem())
|
||||
first.PauseCollection = row.before
|
||||
if row.beforeMarked {
|
||||
first.Metadata = map[string]string{"member_console_collection": "paused_for_grant"}
|
||||
}
|
||||
mock.Sub = first
|
||||
reconcile(t, database, fx.stripeSubID, "test:created")
|
||||
}
|
||||
sub := fx.activeSub(fx.planItem())
|
||||
sub.PauseCollection = row.pause
|
||||
if row.marked {
|
||||
sub.Metadata = map[string]string{"member_console_collection": "paused_for_grant"}
|
||||
}
|
||||
mock.Sub = sub
|
||||
reconcile(t, database, fx.stripeSubID, "test:state")
|
||||
|
||||
gotBehavior, gotResume, gotMarked := readMirror(t, database, coreSubID(t, database, fx.stripeSubID))
|
||||
wantBehavior := sql.NullString{String: row.behavior, Valid: row.behavior != ""}
|
||||
if gotBehavior != wantBehavior || gotResume.Valid != row.hasResume || gotMarked != row.wantMark ||
|
||||
(row.hasResume && !gotResume.Time.Equal(resumesAt)) {
|
||||
t.Errorf("mirror(%s) = %q, %v, %v, want %q, %v, %v", row.name,
|
||||
gotBehavior.String, gotResume, gotMarked, row.behavior, sql.NullTime{Time: resumesAt, Valid: row.hasResume}, row.wantMark)
|
||||
}
|
||||
}
|
||||
|
||||
func readMirror(t *testing.T, database *sql.DB, subID string) (sql.NullString, sql.NullTime, bool) {
|
||||
t.Helper()
|
||||
var (
|
||||
behavior sql.NullString
|
||||
resume sql.NullTime
|
||||
marked bool
|
||||
)
|
||||
err := database.QueryRowContext(context.Background(),
|
||||
`SELECT pause_collection_behavior, pause_collection_resumes_at, pause_collection_marked FROM core.subscriptions WHERE subscription_id = $1`,
|
||||
subID).Scan(&behavior, &resume, &marked)
|
||||
if err != nil {
|
||||
t.Fatalf("read the mirror of %s: %v", subID, err)
|
||||
}
|
||||
return behavior, resume, marked
|
||||
}
|
||||
@@ -327,7 +327,8 @@ func ReconcileLatestSubscriptionForCustomer(ctx context.Context, db *sql.DB, log
|
||||
}
|
||||
|
||||
// upsertSubscription creates the core subscription + mapping on first sight, or
|
||||
// updates status/period fields on a subsequent reconcile. It appends a
|
||||
// updates status/period fields on a subsequent reconcile; both branches record
|
||||
// the collection pause Stripe reports (recordCollectionMirror). It appends a
|
||||
// subscription_changes row only on a real status change. Returns the core
|
||||
// subscription UUID (as a string).
|
||||
func upsertSubscription(
|
||||
@@ -354,6 +355,9 @@ func upsertSubscription(
|
||||
if cerr != nil {
|
||||
return "", fmt.Errorf("reconcile: create subscription: %w", cerr)
|
||||
}
|
||||
if cerr := recordCollectionMirror(ctx, billingQ, created.SubscriptionID, sub); cerr != nil {
|
||||
return "", cerr
|
||||
}
|
||||
// The console never creates a subscription, so the environment stamp
|
||||
// rides this read-back: sub is what subscription.Get just returned,
|
||||
// and its Livemode is the environment the id lives in
|
||||
@@ -395,6 +399,9 @@ func upsertSubscription(
|
||||
}); uerr != nil {
|
||||
return "", fmt.Errorf("reconcile: update subscription: %w", uerr)
|
||||
}
|
||||
if cerr := recordCollectionMirror(ctx, billingQ, existing.SubscriptionID, sub); cerr != nil {
|
||||
return "", cerr
|
||||
}
|
||||
if status != existing.Status {
|
||||
if _, cerr := billingQ.CreateSubscriptionChange(ctx, billing.CreateSubscriptionChangeParams{
|
||||
SubscriptionID: existing.SubscriptionID,
|
||||
@@ -409,6 +416,21 @@ func upsertSubscription(
|
||||
}
|
||||
}
|
||||
|
||||
// recordCollectionMirror records the fetched subscription's collection pause on its
|
||||
// row (collectionMirror).
|
||||
func recordCollectionMirror(ctx context.Context, billingQ *billing.Queries, subscriptionID string, sub *stripe.Subscription) error {
|
||||
behavior, resumesAt, marked := collectionMirror(sub)
|
||||
if err := billingQ.UpdateSubscriptionCollection(ctx, billing.UpdateSubscriptionCollectionParams{
|
||||
SubscriptionID: subscriptionID,
|
||||
PauseCollectionBehavior: behavior,
|
||||
PauseCollectionResumesAt: resumesAt,
|
||||
PauseCollectionMarked: marked,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("reconcile: record collection pause: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconcileItems converges the subscription's core item rows, then reconciles
|
||||
// pool entitlements as a diff (design D4): desired = subscription items grouped
|
||||
// by product (quantities summed); live = the subscription's non-ended
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
SELECT EXISTS (
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
commit
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -12,6 +12,7 @@ GetBillingAccountByID
|
||||
GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
CreateSubscription
|
||||
UpdateSubscriptionCollection
|
||||
UpsertSubscriptionMapping
|
||||
CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
Vendored
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -17,6 +17,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
ListResumableGrantsHeldBy
|
||||
|
||||
@@ -17,6 +17,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
|
||||
@@ -18,6 +18,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -18,6 +18,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
|
||||
@@ -18,6 +18,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
CreateSubscriptionChange
|
||||
SELECT core.end_conferral($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
LockResourcePool
|
||||
|
||||
@@ -18,6 +18,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -18,6 +18,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -23,6 +23,7 @@ GetDefaultPoolByOrgID
|
||||
GetSubscriptionMappingByStripeID
|
||||
GetSubscriptionByID
|
||||
UpdateSubscriptionStatus
|
||||
UpdateSubscriptionCollection
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
GetPriceMappingByStripeID
|
||||
|
||||
@@ -549,6 +549,9 @@ read core.subscriptions.current_period_end
|
||||
read core.subscriptions.current_period_start
|
||||
read core.subscriptions.early_termination_policy
|
||||
read core.subscriptions.ended_at
|
||||
read core.subscriptions.pause_collection_behavior
|
||||
read core.subscriptions.pause_collection_marked
|
||||
read core.subscriptions.pause_collection_resumes_at
|
||||
read core.subscriptions.status
|
||||
read core.subscriptions.subscription_id
|
||||
read core.subscriptions.updated_at
|
||||
|
||||
@@ -217,7 +217,8 @@ func peopleCaption(joined int64, err error) string {
|
||||
}
|
||||
|
||||
// recurringCaption pairs the money headline with the subscriptions behind
|
||||
// it. Trialing subscriptions contribute no money (they are not paying yet)
|
||||
// it. A subscription whose collection is paused is counted here by its status,
|
||||
// though the headline leaves its money out. Trialing subscriptions contribute no money (they are not paying yet)
|
||||
// but stay visible here so the pipeline is never invisible. otherBuckets
|
||||
// counts the currency buckets the headline could not show; conversion is
|
||||
// out of scope (forge issue #79).
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package server
|
||||
|
||||
// The Monthly recurring headline leaves out a subscription whose collection
|
||||
// is paused, whoever paused it (openspec change
|
||||
// grant-pauses-subscription-billing, design D16, task 2.6).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/billing"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/world"
|
||||
)
|
||||
|
||||
func usdMonthlyCents(t *testing.T, q billing.Querier) int64 {
|
||||
t.Helper()
|
||||
rows, err := q.SumMonthlyRecurringByCurrency(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("sum the monthly recurring: %v", err)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if r.Currency == "usd" {
|
||||
return r.MonthlyCents
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func TestOverviewMonthlyRecurringLeavesOutAPausedSubscription(t *testing.T) {
|
||||
db := dbtest.Open(t)
|
||||
q := billing.New(db)
|
||||
before := usdMonthlyCents(t, q)
|
||||
|
||||
w := world.New(t, db)
|
||||
const monthly = 1300
|
||||
orgType := w.OrgType("rec")
|
||||
subscribe := func(name string) world.Subscription {
|
||||
plan := w.Product(name)
|
||||
w.Price(plan, monthly)
|
||||
org := w.Org(name, orgType, w.Person(name))
|
||||
return w.Subscribe(org, world.SubOpts{}, plan)
|
||||
}
|
||||
subscribe("Counted")
|
||||
w.PauseCollection(subscribe("Paused"))
|
||||
w.ForeignPause(subscribe("Foreign"))
|
||||
|
||||
if got := usdMonthlyCents(t, q) - before; got != monthly {
|
||||
t.Errorf("monthly recurring = %v, want %v: a paused subscription was summed", got, int64(monthly))
|
||||
}
|
||||
if got, want := recurringCaption(3, 0, nil, 1), "3 active subscriptions"; got != want {
|
||||
t.Errorf("caption = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -166,6 +166,31 @@ func (w *World) BareSubscription(a Account, start, end time.Time) Subscription {
|
||||
return Subscription{ID: row.SubscriptionID, BillingAccountID: a.ID}
|
||||
}
|
||||
|
||||
// PauseCollection stands for the reconcile's record of the console's own
|
||||
// collection pause on s: behavior void and the console's marker.
|
||||
func (w *World) PauseCollection(s Subscription) {
|
||||
w.TB.Helper()
|
||||
w.setCollectionMirror(s, true)
|
||||
}
|
||||
|
||||
// ForeignPause records a collection pause on s without the console's marker,
|
||||
// as a pause made in the Dashboard reads.
|
||||
func (w *World) ForeignPause(s Subscription) {
|
||||
w.TB.Helper()
|
||||
w.setCollectionMirror(s, false)
|
||||
}
|
||||
|
||||
func (w *World) setCollectionMirror(s Subscription, marked bool) {
|
||||
w.TB.Helper()
|
||||
if err := billing.New(w.DB).UpdateSubscriptionCollection(w.Ctx, billing.UpdateSubscriptionCollectionParams{
|
||||
SubscriptionID: s.ID,
|
||||
PauseCollectionBehavior: sql.NullString{String: "void", Valid: true},
|
||||
PauseCollectionMarked: marked,
|
||||
}); err != nil {
|
||||
w.TB.Fatalf("record a collection pause on %s: %v", s.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// MapAccount gives a a synced Stripe customer mapping with no recorded
|
||||
// environment, which every key mode shows; see MapInvoice. The Stripe id is a's
|
||||
// id behind "cus_".
|
||||
|
||||
@@ -103,7 +103,7 @@ Reasons:
|
||||
Options: three columns on `core.subscriptions` written by every reconcile; or no mirror, the pages saying "paused" whenever the rule says so.
|
||||
|
||||
Pick: the columns, migration `00036_subscription_collection_pause.sql`:
|
||||
- `pause_collection_behavior TEXT NULL`, with no check: `core.subscriptions.status` mirrors Stripe's enum with no check (`00001_init.sql`), and a behavior value a later API version adds must not stop every reconcile of the subscription;
|
||||
- `pause_collection_behavior TEXT NULL`, with no check, so a behavior value a later API version adds does not stop every reconcile of the subscription (unlike `status`, which `chk_subscriptions_status_valid` pins to Stripe's eight values, `00010_schema_hardening.sql:63-66`);
|
||||
- `pause_collection_resumes_at TIMESTAMPTZ NULL`;
|
||||
- `pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE`, true when the subscription's metadata carries the console's marker.
|
||||
|
||||
@@ -145,7 +145,7 @@ Pick: the sweep, `fulfillment.SweepCollectionDrift(ctx, db, logger, keyMode) (in
|
||||
|
||||
Reason: a dead-lettered entry is never retried, and a path that forgets to request a reconcile is otherwise invisible. It is also the deploy's backfill: within an hour of the deploy every subscription already in this state is paused.
|
||||
|
||||
Shape: it pages the live subscriptions (`active`, `trialing`, `past_due`, `unpaid` and `paused`) by id, 500 at a time (`ListLiveSubscriptionsForCollectionSweep`: id, status, the three mirror columns, keyset `subscription_id > $after`, joined to `stripe.subscription_mappings` so that a subscription with no Stripe mapping never appears). The query lives in `internal/integrations/stripe/store/queries/subscription_mappings.sql` (Go package `stripe`, which `fulfillment` imports as `internalstripe`), because billing's sqlc loads `internal/db/migrations/` and `internal/db/sqlc_schemas.sql` only, which declare no `stripe` table, while the store's sqlc loads both streams; `FillInvoiceSubscriptionLinks` (`invoice_mappings.sql:66-82`) is the precedent of a store query that joins `core.subscriptions`. For each page the sweep reads, once each, the current items (`ListCurrentSubscriptionItemsBySubscriptionIDs`), the live provisions' products (`ListLiveProvisionProductsBySubscriptionIDs`, new), the shapes (`ListConferralShapes`), the displacements (`ListSubscriptionDisplacementsBySubscriptionIDs`) and the subscriptions with a `reconcile_subscription` entry that is `pending`, `processing` or `failed`, or `dead_letter` and updated within the last day (`ListSubscriptionsWithRecentReconcileEntries`, in `internal/integration/queries`). `collectionDrift` (reading no row) applies `CollectionPauseWanted` per subscription over its recorded items: a subscription the rule wants paused whose mirror has no pause, or one the rule wants unpaused whose mirror carries the console's marker, drifts; a foreign pause never does; a Stripe-`paused` subscription is never wanted paused, so one whose mirror carries the console's marker drifts. The sweep drops a row whose mapping fails `MappingReachable` under the key, because such an entry would complete as a skip (L3, or `skipUnreachableSubscription`), change no mirror, and be asked for again every hour. Each drifting subscription without a recent entry gets one entry, in one transaction per page. L5 logs the count. A failed read logs L6 and fails the activity; the next hour runs again.
|
||||
Shape: it pages the live subscriptions (`active`, `trialing`, `past_due`, `unpaid` and `paused`) by id, 500 at a time (`ListLiveSubscriptionsForCollectionSweep`: id, status, the three mirror columns, keyset `subscription_id > $after`, joined to `stripe.subscription_mappings` with `m.stripe_subscription_id IS NOT NULL`, so that a subscription with no Stripe mapping, or a mapping with no Stripe id, never appears). The query lives in `internal/integrations/stripe/store/queries/subscription_mappings.sql` (Go package `stripe`, which `fulfillment` imports as `internalstripe`), because billing's sqlc loads `internal/db/migrations/` and `internal/db/sqlc_schemas.sql` only, which declare no `stripe` table, while the store's sqlc loads both streams; `FillInvoiceSubscriptionLinks` (`invoice_mappings.sql:66-82`) is the precedent of a store query that joins `core.subscriptions`. For each page the sweep reads, once each, the conferring products of the current items (`ListCurrentConferringProductsBySubscriptionIDs`, new in billing: each current item's product whose `entitlement_set_id` is set, because `CollectionPauseWanted` counts only those, D2, and no other read of the sweep says whether a product has a set), the live provisions' products (`ListLiveProvisionProductsBySubscriptionIDs`, new), the shapes (`ListConferralShapes`), the displacements (`ListSubscriptionDisplacementsBySubscriptionIDs`) and the subscriptions with a `reconcile_subscription` entry that is `pending`, `processing` or `failed`, or `dead_letter` and updated within the last day (`ListSubscriptionsWithRecentReconcileEntries`, in `internal/integration/queries`). `collectionDrift` (reading no row) applies `CollectionPauseWanted` per subscription, passing every recorded conferring product as `desired` and, as `left`, the map `DisplacedProducts` returns over those with no live provision, as `convergeConferrals` builds it: a subscription the rule wants paused whose mirror has no pause, or one the rule wants unpaused whose mirror carries the console's marker, drifts; a foreign pause never does; a Stripe-`paused` subscription is never wanted paused, so one whose mirror carries the console's marker drifts. The sweep drops a row whose mapping fails `MappingReachable` under the key, because such an entry would complete as a skip (L3, or `skipUnreachableSubscription`), change no mirror, and be asked for again every hour. Each drifting subscription without a recent entry gets one entry, in one transaction per page. L5 logs the count. A failed read logs L6 and fails the activity; the next hour runs again.
|
||||
|
||||
The sweep reads the recorded items, where the reconcile reads Stripe's; a difference costs one reconcile that decides from Stripe and changes nothing.
|
||||
|
||||
@@ -170,7 +170,7 @@ Shape:
|
||||
- Each act calls it when it ended at least one provision of the ending plan, after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, with the reason `subscription-delivery:revocation:<grant id>`, `subscription-delivery:expiration:<grant id>` or `subscription-delivery:subscription:<subscription id>`. An act that ended nothing delivers nothing, as it resumes nothing, so a replay is inert.
|
||||
- It reads, under the pool row the caller holds, the recorded products of the organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused` (`ListRecordedSubscriptionProductsOfPool`: subscription id, status, product id and the summed quantity of its current items, `core.subscription_items.ended_at IS NULL`, for products with an entitlement set, ordered by subscription id then product id), skipping the ending subscription in `reconcileEnded`.
|
||||
- Short-circuit: when the read returns no row other than the excepted subscription, the step makes no further read, including the ordering read `ListSubscriptionsSupersededByProvisions`; a subscription with no missing product makes no shape or displacement read. The step reads per live subscription, displaced or not, so every trace of an act that ended a provision gains the one read.
|
||||
- The order: first the subscriptions the ending plan superseded, then the rest, each group in subscription id order. A subscription the ending plan superseded is one whose latest episode on a ladder of the pool ended in a `core.supersession_pairs` row whose `successor_provision_id` is one of `endedProvisionIDs`; one new read, `ListSubscriptionsSupersededByProvisions(pool_id, provision_ids, subscription_ids)`, finds them among the listed subscriptions, with the latest episode taken as `core.subscription_displacements` takes it (`00034_subscription_displacements.sql:41-49`) and the pairs matched as the view pairs them (`00033_supersession_pairs.sql:27-43`). The holder of a displacement cannot order them: `core.subscription_displacements` names only a live position as holder (`h.status IN ('active', 'suspended')`, `00034:69-73`), so after `core.end_conferral` no displacement names an ended provision, and before it, the holder is whatever holds the ladder now, not the plan that superseded the subscription. Take S1 displaced by S2 and S2 displaced by a grant G: when G ends, S2 delivers first and S1 then finds S2 holding the ladder, where subscription id order alone would give the ladder to S1 and leave S2, the subscription G displaced, billing undelivered. The limit: the read matches the pair's successor against `endedProvisionIDs` alone, and an extension (Manage) supersedes its predecessor's provision with its own, so when the ending grant is an extension of the grant that displaced S2, S2's pair names the predecessor's provision and S2 falls into the id-ordered rest. When S2 has the higher id, S1 then takes the ladder and S2 stays left alone, displaced by S1, billing without delivering (F62). Two subscriptions on one ladder is a shape only the Dashboard makes (F16), so the step does not follow the grant's lineage.
|
||||
- The order: first the subscriptions the ending plan superseded, then the rest, each group in subscription id order. A subscription the ending plan superseded is one whose latest episode on a ladder of the pool ended in a `core.supersession_pairs` row whose `successor_provision_id` is one of `endedProvisionIDs`; one new read, `ListSubscriptionsSupersededByProvisions(pool_id, provision_ids, subscription_ids)`, finds them among the listed subscriptions, with the latest episode taken as `core.subscription_displacements` takes it (`00034_subscription_displacements.sql:41-49`) and the pairs matched as the view pairs them (`00033_supersession_pairs.sql:27-43`). The holder of a displacement cannot order them: `core.subscription_displacements` names only a live position as holder (`h.status IN ('active', 'suspended')`, `00034:69-73`), so after `core.end_conferral` no displacement names an ended provision, and before it, the holder is whatever holds the ladder now, not the plan that superseded the subscription. Take S1 displaced by S2 and S2 displaced by a grant G: when G ends, S2 delivers first and S1 then finds S2 holding the ladder, where subscription id order alone would give the ladder to S1 and leave S2, the subscription G displaced, billing undelivered. The limit: the read matches the pair's successor against `endedProvisionIDs` alone, so it misses S2 whenever the provision that displaced S2 is not one the act ended, either because the ending grant extends it (an extension, through Manage, supersedes its predecessor's provision with its own) or because a later grant, not an extension of it, replaced it. S2's pair then names the earlier provision, and S2 falls into the id-ordered rest. When S2 has the higher id, S1 then takes the ladder and S2 stays left alone, displaced by S1, billing without delivering (F62). Following the grant's lineage would cover the first shape only. Two subscriptions on one ladder is a shape only the Dashboard makes (F16), and a subscription displaced by another subscription keeps billing in such shapes as decided with the maintainer (D2), so the step accepts the limit.
|
||||
- Per subscription, in that order: its live provisions (`GetLivePoolProvisionsBySubscriptionID`); the missing products; the shapes (one `ListConferralShapes` for every product); its displacements (`ListSubscriptionDisplacements`); `DisplacedProducts` over the missing ones; `ChooseTiers` over the rest; then, under a savepoint (`subscription_delivery`), `core.confer` sourced by the subscription for each kept missing product in product id order, actor `system`; and, when the status is `past_due`, `unpaid` or `paused`, `core.sync_source_status('suspended')` for the subscription, so its tier comes back suspended. A refused conferral rolls back to the savepoint, is logged (L4), and the ending proceeds; a lock wait, a deadlock or a cancelled context fails the act, as in resumption.
|
||||
- It confers only; ending and re-bounding stay with the reconcile, which the act's request (D4) runs seconds later.
|
||||
- A grant resumed just before it holds its rungs, so `DisplacedProducts` leaves the subscription's product alone there; the floor then sees the ladder held.
|
||||
@@ -233,11 +233,11 @@ The rule, rule 3a, ahead of rule 3 (the target is the current product), applied
|
||||
3. the target is the current product: none, reason `Current`;
|
||||
4. any other target: none, reason `PaysOnLadder` ("a subscription pays on the ladder without holding it"). This includes every tier between a lower grant and the paid tier.
|
||||
|
||||
It sits ahead of rule 3 because the granted tier, the current one, is offered the switch. No answer on such a ladder is Checkout, and `plans.Across` is unchanged: rule 3a answers no Checkout on any paying ladder, so a product with such a ladder already combines to none. `switchOffer` (`plan_offer.go:337-381`) maps a refusal with `Paying` set and `Suspended` to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and then a refusal with `Paying` set and not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on. On a ladder a grant holds against a paying subscription `pos.Subscribed` is false, so without the second case every other rule 3a refusal (the paid tier, item 1, and a tier between a lower grant and the paid tier, item 4) would reach `!pos.Subscribed`, and `renderPlansAfterMove` would answer "There's no active subscription to change on this plan.", which is false there, since a subscription pays on the ladder. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence. `resumeOfferFor` (D20) maps the same way.
|
||||
It sits ahead of rule 3 because the granted tier, the current one, is offered the switch. No answer on such a ladder is Checkout, and `plans.Across` is unchanged: rule 3a answers no Checkout on any paying ladder, so a product with such a ladder already combines to none. `switchOffer` (`plan_offer.go:337-381`), under rule 3a's own condition (`pos.Paying != nil && !pos.Subscribed`), maps a refusal whose `Paying` is suspended to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and then a refusal whose `Paying` is not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on. The condition is rule 3a's because a switch acts on the subscription that backs the position (`SwitchPlan` resolves through it, `plan_change.go:196`): a subscription that holds the rung over a paying one answers its refused switches from its own state, so a post to its current tier reads "You're already on that plan.", and the paying subscription's past-due state never answers for it. On a ladder a grant holds against a paying subscription `pos.Subscribed` is false, so without the second mapping every other rule 3a refusal (the paid tier, item 1; the current tier under a grant at or below the paid tier, item 3; and every tier item 4 refuses, below the grant or between a lower grant and the paid tier) would reach `!pos.Subscribed`, and `renderPlansAfterMove` would answer "There's no active subscription to change on this plan.", which is false there, since a subscription pays on the ladder. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence. `resumeOfferFor` (D20) keeps its own order, because Resume acts on the paying subscription, so its payment sentence is true there.
|
||||
|
||||
### D10. The paid plan's card
|
||||
|
||||
The card of the tier the paying subscription pays for, on a ladder a grant holds, carries the subscription's state and controls; it may be the current card when the grant is of the subscription's own tier. `buildTier` draws it even when its product is no longer a public plan, as it draws the current and the held rungs (`member_plans.go:399-412`), so Cancel plan stays reachable; such a card also offers Resume when D20's conditions hold. On a ladder no plan holds (a bundle's vacated ladder) the paid tier draws no line and no control, and the cards on the ladder a grant holds carry them (#271 decides more).
|
||||
The card of the tier the paying subscription pays for, on a ladder a grant holds, carries the subscription's state and controls; it may be the current card when the grant is of the subscription's own tier. `buildTier` draws it even when its product is no longer a public plan, as it draws the current and the held rungs (`member_plans.go:399-412`), so Cancel plan stays reachable; such a card also offers Resume when D20's conditions hold. On a ladder no plan holds (a bundle's vacated ladder) the paid tier draws its price, as every card does, and no control, and the cards on the ladder a grant holds carry the subscription's state and controls (#271 decides more).
|
||||
|
||||
The card's states, read from the paying row and the mirror:
|
||||
|
||||
@@ -261,7 +261,7 @@ Pay invoice: the card links to the existing plan route. `planPosition` (`member_
|
||||
|
||||
Options: (a) the resolver falls back from the position to the paying subscription, for every move; (b) a second resolver for Cancel and Keep only, the switch refusing.
|
||||
|
||||
Pick: (a), now that the switch is decided. `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`: when the ladder's position is not subscription-backed, or the pool holds no position on the ladder at all (a bundle's vacated ladder; the resolver returns at `if !ok`, `plan_change.go:792`), it finds the live subscription whose current item's product is a tier of the ladder (`ListSubscriptionRungsByOrg`, the first by subscription id), resolves that item and its mappings as today, and sets `holdsLadder = false`, `positionStatus` to `suspended` when the subscription's status is `past_due`, `unpaid` or `paused`, and `subscriptionStatus` from the subscription row. `SwitchPlan`, `KeepCurrentPlan`, `PreviewSwitch`, `CancelSubscription` and `SubscriptionBacksLadder` call it, and `ResumePlan` from section 12 (D20). Their refusals read the same two fields, so a past-due paying subscription refuses an immediate cancellation and a switch, and a `paused` one refuses every act, as for a holding subscription.
|
||||
Pick: (a), now that the switch is decided. `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`: when the ladder's position is not subscription-backed, or the pool holds no position on the ladder at all (a bundle's vacated ladder; the resolver returns at `if !ok`, `plan_change.go:792`), it finds the live subscription whose current item's product is a tier of the ladder (`ListSubscriptionRungsByOrg`, the first by subscription id), resolves that item and its mappings as today, and sets `holdsLadder = false`, `currentProductID` to the paying item's product, not the held position's (`SwitchPlan` compares the target with it, `plan_change.go:214`, `:245`, as `PreviewSwitch` does, `:560`, and the resolver finds the item by it, `:822`), `positionStatus` to `suspended` when the subscription's status is `past_due`, `unpaid` or `paused`, and `subscriptionStatus` from the subscription row. `SwitchPlan`, `KeepCurrentPlan`, `PreviewSwitch`, `CancelSubscription` and `SubscriptionBacksLadder` call it, and `ResumePlan` from section 12 (D20). Their refusals read the same two fields, so a past-due paying subscription refuses an immediate cancellation and a switch, and a `paused` one refuses every act, as for a holding subscription.
|
||||
|
||||
Cancel plan at the period end, as everywhere (decided with the maintainer): Stripe accepts `cancel_at_period_end` on the paused subscription. If the grant ends first, D7 delivers the subscription again until its period ends. The endpoint still accepts a posted immediate cancellation of an active paying subscription, which the UI never sends.
|
||||
|
||||
@@ -445,7 +445,7 @@ No price rule applies: Resume keeps the subscription's own item and price, as Ke
|
||||
| F33 | The paused switch needs approval | n/a | As for an ordinary upgrade; the pending update expires after 23 hours | D12 |
|
||||
| F34 | A crash after Stripe applied the switch, before the console's reconcile | n/a | Any later reconcile confers the target over G | D8 |
|
||||
| F35 | Checkout on a ladder S pays for, any tier | Sold | Refused with 422 before Stripe | D9 |
|
||||
| F36 | A bundle's vacated ladder | Checkout sold | Refused; the paid tier shows no line; #271 unchanged | D9, D10 |
|
||||
| F36 | A bundle's vacated ladder | Checkout sold | Refused; the paid tier shows its price and no control; #271 unchanged | D9, D10 |
|
||||
| F37 | A switch from a past-due paying S | n/a | Refused: "Pay the unpaid invoice before changing this plan." | D9 |
|
||||
| F38 | A grant of S's own tier (a transfer) | S bills | Paused; the current card is also the paid card; tiers above it offer the switch | D10 |
|
||||
| F39 | A grant ranked below S's tier | S bills | Paused; S's card offers Resume plan; the tiers above S's tier offer the switch; the tiers between G's and S's offer nothing | D9, D20 |
|
||||
@@ -471,7 +471,7 @@ No price rule applies: Resume keeps the subscription's own item and price, as Ke
|
||||
| F59 | An operator issues a grant again over a resumed S | n/a | S is displaced again and paused again (F1) | D4 |
|
||||
| F60 | The member resumes S under a bundle grant G (G's product is a tier of two ladders) | n/a | G's whole provision is superseded (#88); the act runs no floor, so the default does not return there; the act's own requests reconcile every live subscription, so another subscription displaced on that ladder delivers there and is unpaused within seconds | D4, D20 |
|
||||
| F61 | The member cancels S in one tab while a resume commits in another | n/a | The resume reads no scheduled cancellation, because `CancelSubscription` calls Stripe (`plan_change.go:671`) before its reconcile records `cancel_at_period_end` and the scheduled change; S takes the ladder from G and ends at its period end, and an unmarked G delivers no more after that; accepted, since both acts are the member's own and D20's refusal cannot see Stripe | D20 |
|
||||
| F62 | S1 displaced by S2, S2 displaced by G, G extended through Manage, and the extension ends; S2 has the higher id (two subscriptions on one ladder, a shape only the Dashboard makes) | n/a | S2's pair names the provision of the grant the extension replaced, not one the ending act ended, so the ordering read misses S2 and both go in id order: S1 takes the ladder, and S2 stays left alone, displaced by S1, billing without delivering; accepted | D7 |
|
||||
| F62 | S1 displaced by S2, S2 displaced by G, and the provision that displaced S2 is not one the ending act ended: G was extended through Manage and the extension ends, or a later grant G2, not an extension of G, replaced G and G2 ends; S2 has the higher id (two subscriptions on one ladder, a shape only the Dashboard makes) | n/a | S2's pair names G's provision, not one the ending act ended, so the ordering read misses S2 and both go in id order: S1 takes the ladder, and S2 stays left alone, displaced by S1, billing without delivering; accepted | D7 |
|
||||
|
||||
## Locks and transactions
|
||||
|
||||
@@ -522,7 +522,7 @@ Reused unchanged: "Cancel plan", "Keep plan", "Pay invoice", "Your plan change h
|
||||
| W | Issue grant, the warning when a product is marked ⚠ | `Products marked ⚠ would supersede a tier a subscription pays for; its billing pauses until the grant ends.` | approved |
|
||||
| T1 | Tier changes, a delivery after a revocation (actor `system`, reason `subscription-delivery:revocation:`) | `Subscription delivers again after a revocation` | approved |
|
||||
| T2 | The same after an expiry | `Subscription delivers again after a grant expired` | approved |
|
||||
| T3 | The same after a subscription that held the ladder ended | `Subscription delivers again after a subscription ended` | approved |
|
||||
| T3 | The same after a subscription that held the ladder ended or dropped the item that held it | `Subscription delivers again after a subscription ended` | approved; the dropped-item case pending the maintainer, open question 13 |
|
||||
|
||||
`<ladders>` and `<holder>` are as `displacementTitle` fills them today. `<grant holder>` is `a grant holds` when one grant provision holds every ladder its sentence names and `grants hold` when several do (question 5); a paused sentence names no other holder, since the rule pauses only under grants.
|
||||
|
||||
@@ -548,7 +548,7 @@ Each claim is pinned by a deliberate break (`docs/testing.md`, "Prove a test wit
|
||||
| 3 | `TestCollectionPauseWanted`, `TestDecideCollection`, `TestReconcile_AGrantOverTheSubscriptionRequestsThePause`, `TestApplyCollection_*` (eight), `TestOutbox_ReconcileSubscriptionAction`, trace goldens | D1, D2, D6 |
|
||||
| 4 | `TestActsRequestSubscriptionReconciles` (one row per act), `TestConferGrantTxRequestsNothing`, `TestReconcileEndedRequestsTheOtherSubscriptions`, `TestSurplusEndRequestsTheOtherSubscriptions`, `TestIssueGrantHandlerRequestsAReconcile`, the demo seed's assertion | D4 |
|
||||
| 5 | `TestDisplacementTitle` (rewritten, with the several-grants rows), `TestSubscriptionTitlesFor`, `TestDisplacedOnPage`, `TestSubscriptionsListMarksAPausedSubscription`, `TestOrgEnrollmentGolden` (`grant-over-subscription-paused`), `TestOrgEnrollmentIssueGrantPanel_Stacked`, `TestOrgEnrollmentProductsSection` | D16 |
|
||||
| 6 | `TestCollectionDrift`, `TestSweepCollectionDrift_*` (five), `TestSweepScheduledChangesWorkflowRunsTheCollectionSweepAfterAFailure` | D5 |
|
||||
| 6 | `TestCollectionDrift`, `TestSweepCollectionDrift_*` (six), `TestSweepScheduledChangesWorkflowRunsTheCollectionSweepAfterAFailure` | D5 |
|
||||
| 7 | `TestDeliverDisplaced_*` (including the ending holder's displaced subscription first), `TestHumanizeTransitionReason` rows, trace goldens | D7 |
|
||||
| 8 | `TestDisplacedProducts` rows, `TestSubscriptionDisplacements_TheHolderRank`, `TestDisplacementHolderRankMigrationUpDownUp`, `TestReconcile_ATierAtOrAboveTheGrantTakesTheLadder`, `TestReconcile_AGrantBelowTheSubscriptionsTierKeepsTheLadder` | D8 |
|
||||
| 9 | `TestOffer` rows (the switch rows land in section 11), `TestAcross` (unedited), `TestPayingByLadder`, `TestCheckoutRefusesALadderASubscriptionPaysFor`, `TestProductsPageReadsPayingOnce`, the Products page's Checkout absence | D9 |
|
||||
@@ -558,7 +558,7 @@ Each claim is pinned by a deliberate break (`docs/testing.md`, "Prove a test wit
|
||||
|
||||
`TestOperatorPagesReadAFixedNumberOfTimes` passes unedited for the organization page and the subscriptions list: the mirror rides reads they already make. `TestProductsPageReadsPayingOnce` pins that the Products page and Checkout make one statement more per request (`ListSubscriptionRungsByOrg`), never one per ladder.
|
||||
|
||||
A break no test of its section sees is named in that section's commit with the reason; two are known at drafting. In section 9 (task 9.5), `switchOffer`'s paying refusal left to `!pos.Subscribed` is unseen, because no section-9 test posts a switch on a paying ladder; section 11's `TestPostSwitchFromAPausedSubscription` catches it (task 11.6). In section 12 (task 12.8), the supersession of a bundle grant's other ladder is unseen, because `core.confer` owns it. The handler's decision gate is caught by `TestPostResume`'s row `held by another subscription`, which only the decision refuses. Every other break has a test that reads it, among them each mirrored column and each returned column (tasks 2.6 and 8.4).
|
||||
A break no test of its section sees is named in that section's commit with the reason; two are known at drafting. In section 9 (task 9.5), breaks of `switchOffer`'s paying mappings (the unavailable-plan mapping deleted, the suspended mapping deleted, the `Paying.Paused` test dropped, and the `!pos.Subscribed` test dropped from their condition) are unseen, because no section-9 test posts a switch on a paying ladder; section 11's `TestPostSwitchFromAPausedSubscription` catches each (task 11.6). In section 12 (task 12.8), the supersession of a bundle grant's other ladder is unseen, because `core.confer` owns it. The handler's decision gate is caught by `TestPostResume`'s row `held by another subscription`, which only the decision refuses. Every other break has a test that reads it, among them each mirrored column and each returned column (tasks 2.6 and 8.4).
|
||||
|
||||
## What is unverified
|
||||
|
||||
@@ -600,7 +600,11 @@ A subscription the console paused stays paused under the old binary, which never
|
||||
|
||||
## Open questions
|
||||
|
||||
All questions are settled.
|
||||
Question 13 is open; the rest are settled.
|
||||
|
||||
**Open:**
|
||||
|
||||
13. T3's reach. When a subscription that held a ladder drops the item at Stripe while another subscription waits on that ladder, the surplus end delivers the waiting one with the reason `subscription-delivery:subscription:` (D7), so its Tier changes row reads T3, "Subscription delivers again after a subscription ended", although the first subscription is still live. Only the Dashboard reaches this case. The text is written for (a), the recommended answer: T3 for both cases, with Copy T3's Where widened to a subscription that dropped the item that held the ladder, because the subscription's plan on that ladder did end. The alternative is (b): a fourth label for the surplus end, which is new wording and a fourth reason constant in task 7.2. Doing nothing gives (a).
|
||||
|
||||
**Settled** (1 and 11 by the designer, 2 to 10 and 12 with the maintainer):
|
||||
|
||||
|
||||
@@ -51,23 +51,24 @@ None.
|
||||
- `stripe-subscription-management`: added "A grant's hold pauses the subscription's collection at Stripe", "A subscription delivers again in the act that ends the plan holding its ladder", "Cancel plan and Keep plan reach a subscription that pays on a ladder without holding it", "A subscription paused for a grant is switched to the granted tier or above" and "A member resumes a plan paused under a grant ranked below it"; modified "Subscription reconcile computes a genuine diff, grouped by product" (the exception at or above a grant, the pause in place of "changes nothing at Stripe", the delivery in the ending act) and "Suspension and resume propagate via sync_source_status" (the pause in place of "SHALL NOT attempt to stop the subscription's billing").
|
||||
- `member-offer`: modified "One decision says which move a member is offered on a ladder" (the subscription that pays without holding, its rule, and Resume).
|
||||
- `stripe-subscription-creation`: added "Checkout refuses a ladder a subscription pays for without holding it".
|
||||
- `member-product-discovery`: added "A paid plan whose ladder a grant holds shows its pause on its own card".
|
||||
- `member-product-discovery`: added "A paid plan whose ladder a grant holds shows its pause on its own card"; modified "Plan-move controls reflect built billing mechanics" (a rung held by a grant sells Checkout only on a ladder no subscription pays for, and the switch preview reaches the paying subscription).
|
||||
- `member-invoice-history`: modified "Stripe's page of an invoice is read when the member opens it" (the plan route reaches the paying subscription's open invoice).
|
||||
- `plan-enrollment-administration`: modified "Advisory warning when a grant would supersede a subscription-sourced position" (the warning's text, and the grant now pauses the subscription's collection) and "The billing card says when a subscription delivers nothing while another plan holds its ladder" (the paused titles).
|
||||
- `plan-enrollment-administration`: modified "Advisory warning when a grant would supersede a subscription-sourced position" (the warning's text, and the grant now pauses the subscription's collection), "The billing card says when a subscription delivers nothing while another plan holds its ladder" (the paused titles) and "Tier changes is the audit list, in operator vocabulary" (the delivery's three reasons).
|
||||
- `member-console-demo-seed`: modified "The seed plays a ledger demo on Carlos's organization" (the revocation and the expiry deliver Carlos Member's canceling subscription again, so no default is restored and the Active tab is empty).
|
||||
- `operator-billing-views`: modified "The subscriptions list marks a subscription that delivers nothing while another plan holds its ladder" (the paused title).
|
||||
- `grant-resumption`: modified "Only the end of a replacing plan resumes a grant" (the ending act's delivery of a subscription is not a resumption and runs after it; a switch or a resume that takes the ladder replaces the grant) and "A grant waits on the nearest plan above it that has not ended" (its scenario's subscription is live while the operator's grant supersedes its position).
|
||||
- `operator-panel-navigation`: added "The Monthly recurring headline leaves out a subscription whose collection is paused".
|
||||
|
||||
## Impact
|
||||
|
||||
- **Code:** `internal/fulfillment/reconcile.go`, `plan_change.go`, a new `collection.go` (the decision, the Stripe call, the drift sweep); `internal/entitlements` (the moved rule, the pause rule, the outbox requests, the delivery step, `IssueGrant`, the resume act); `internal/plans/offer.go`; `internal/server/plan_offer.go`, `member_plans.go`, `member_plan_moves.go`, `member_hosted_invoice.go`, `billing.go`, `action_triggers.go`, `operator_enrollment.go`, `operator_enrollment_forms.go`, `operator_billing.go`, `operator_tier_changes.go`; `internal/embeds/templates/partials/member_plans.html`; `internal/integrations/stripe/workflows/outbox.go`; `internal/workflows/billing/`; `internal/stripetest/mock.go` (an invoice list).
|
||||
- **Code:** `internal/fulfillment/reconcile.go`, `plan_change.go`, a new `collection.go` (the decision, the Stripe call) and a new `collection_sweep.go` (the drift sweep); `internal/integrations/stripe/store/queries/subscription_mappings.sql` and `internal/integration/queries/outbox.sql` (the sweep's reads); `internal/entitlements` (the moved rule, the pause rule, the outbox requests, the delivery step, `IssueGrant`, the resume act); `internal/plans/offer.go`; `internal/server/plan_offer.go`, `member_plans.go`, `member_plan_moves.go`, `member_hosted_invoice.go`, `billing.go`, `action_triggers.go`, `operator_enrollment.go`, `operator_enrollment_forms.go`, `operator_billing.go`, `operator_tier_changes.go`; `internal/embeds/templates/partials/member_plans.html`; `internal/integrations/stripe/workflows/outbox.go`; `internal/workflows/billing/`; `internal/stripetest/mock.go` (an invoice list); `test/e2e/screens` (the wait for an empty outbox before the first capture).
|
||||
- **Schema:** `00036_subscription_collection_pause.sql` (three columns on `core.subscriptions`) and `00037_displacement_holder_rank.sql` (`core.subscription_displacements` returns the holder's product and rank).
|
||||
- **Stripe calls:** `POST /v1/subscriptions/{id}` setting or clearing `pause_collection` and the marker (the Subscriptions write the moves already need); the paused switch's update; `GET /v1/invoices?subscription=…&status=open` for Pay invoice on a paused card (Invoices read, already held).
|
||||
- **Routes:** one added, `POST /partials/member/plans/resume`, declared as an action trigger.
|
||||
- **Behaviour a deployment sees:** a grant over a paid tier stops the subscription's charges within seconds and resumes them when the grant ends, with the tier delivered in the same act; the member sees the paused plan, can cancel it, move it to the granted tier or above, or, under a lower grant, resume it; no second subscription on a ladder can be bought.
|
||||
- **Deploy:** re-run `scripts/db-reader-role.sql` after the migrations so the reader role reads the three new columns (`docs/database-management.md`, "Running the script"). Nothing to backfill: the drift sweep pauses every subscription already displaced by a grant within an hour of the deploy (D19), and a read-only count before the push goes to the maintainer (task 13.3).
|
||||
- **Tests:** unit tests of the rules, reconcile tests through the Stripe mock, database tests of each act's request and of the delivery step, the trace goldens, handler tests of the Products page, Checkout, the switch, Resume plan and Pay invoice, database tests of the resume act and its refusals, the organization page and subscriptions list titles, the migrations' up-down-up, and the Stripe sandbox walk at landing.
|
||||
- **Docs:** `docs/stripe.md`, `docs/models/payments-billing.md`, `docs/models/plan-ladders-transitions.md`, `docs/plan-management.md`, `docs/database-locks.md`, `test/AGENTS.md`.
|
||||
- **Docs:** `docs/stripe.md`, `docs/models/payments-billing.md`, `docs/models/plan-ladders-transitions.md`, `docs/plan-management.md`, `docs/database-locks.md`, `test/AGENTS.md`, `test/seed/member-console-demo/README.md`.
|
||||
|
||||
## Related issues
|
||||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: The seed plays a ledger demo on Carlos's organization
|
||||
|
||||
The seeder SHALL perform, on Carlos Member's personal organization, a sequence of grant acts through the same `internal/entitlements` helpers the operator surface and the expiry activity call (`ConferGrantTx`, `ExtendGrantTx`, `RevokeGrantTx`, `ExpireGrantTx`), each in its own transaction, with the operator Alice as actor and author, and every grant note starting with "Ledger demo:". The sequence SHALL be: an evaluation grant of `demo_plan_2`; a promotional grant of `demo_plan_3`; the extension of that position; a complimentary grant of `demo_plan_2`; the revocation of that grant; an evaluation grant of `demo_plan_2` valid until its issue instant; the expiry of that grant. The seeder SHALL NOT write a grant, provision, or transition row directly, and SHALL NOT backdate any act. When Alice's person row does not exist, the seeder SHALL skip the demo with a warning and exit 0.
|
||||
|
||||
#### Scenario: the ledger reads the whole vocabulary
|
||||
|
||||
- **GIVEN** the seeder ran with the operator seeded
|
||||
- **WHEN** an operator opens Carlos Member's organization
|
||||
- **THEN** Tier changes lists, newest first: Started (Subscription delivers again after a grant expired), Ended (Grant expired), Upgraded, Started (Subscription delivers again after a revocation), Ended (Revoked by an operator), Downgraded, Extended, Upgraded, Upgraded, Started (Seeded default)
|
||||
- **AND** the grants ledger's History tab lists five grants whose notes start with "Ledger demo:" and the Active tab shows its empty state, because Carlos Member's canceling subscription holds the Demo Ladder
|
||||
|
||||
#### Scenario: the demo is idempotent
|
||||
|
||||
- **GIVEN** Carlos's organization already holds a grant whose description starts with "Ledger demo:"
|
||||
- **WHEN** the seeder runs again
|
||||
- **THEN** the demo step creates nothing and reports skipped
|
||||
|
||||
#### Scenario: no operator, no demo
|
||||
|
||||
- **GIVEN** Alice's person row does not exist
|
||||
- **WHEN** the seeder runs
|
||||
- **THEN** the demo step logs a warning naming the missing operator, creates nothing, and the seeder exits 0
|
||||
+144
-1
@@ -11,7 +11,7 @@ On the Products page, on a ladder a grant holds while a live subscription of the
|
||||
- no `pause_collection` behavior recorded (the pause pending or failed): the existing "{price}, renews {date}", "{price}, moves to {tier} on {date}" or "{price}, ends {date}", or "{price}, payment due" with Pay invoice, with the same controls and no Resume plan;
|
||||
- status `paused`: the existing "{price}, paused" and "Entitlements are suspended.", and no control.
|
||||
|
||||
{granted} SHALL be the name of the product the grant holds on the ladder, the paid tier's own name under a grant of that tier. Cancel plan on that card SHALL cancel the subscription at its period end, and its confirmation's body SHALL read "{paid} ends on {date}; {granted} stays granted." under a grant of another tier and "Your subscription ends on {date}; {granted} stays granted." under a grant of the subscription's own tier, each followed by " The unpaid invoice stays due." when the payment is due, {date} the subscription's period end. Resume plan SHALL open the shared confirmation dialog titled "Resume {paid}?" whose body reads "Your subscription replaces the grant. Nothing is charged now; then {price}.", {price} the subscription's own recurring price, and whose confirm control reads "Resume plan". The granted tier's card and each tier ranked above it, and above the paid tier, SHALL draw the switch the decision offers, labelled "Upgrade"; under a grant ranked below the paid tier, the tiers between them SHALL draw no control. On a ladder the subscription pays for and no plan holds, the paid tier's card SHALL draw no price line and no control. The page SHALL read the paying subscriptions in one statement per request.
|
||||
{granted} SHALL be the name of the product the grant holds on the ladder, the paid tier's own name under a grant of that tier. Cancel plan on that card SHALL cancel the subscription at its period end, and its confirmation's body SHALL read "{paid} ends on {date}; {granted} stays granted." under a grant of another tier and "Your subscription ends on {date}; {granted} stays granted." under a grant of the subscription's own tier, each followed by " The unpaid invoice stays due." when the payment is due, {date} the subscription's period end. Resume plan SHALL open the shared confirmation dialog titled "Resume {paid}?" whose body reads "Your subscription replaces the grant. Nothing is charged now; then {price}.", {price} the subscription's own recurring price, and whose confirm control reads "Resume plan". The granted tier's card and each tier ranked above it, and above the paid tier, SHALL draw the switch the decision offers, labelled "Upgrade"; under a grant ranked below the paid tier, the tiers between them SHALL draw no control. On a ladder the subscription pays for and no plan holds, the paid tier's card SHALL draw no control and none of the paused lines. The page SHALL read the paying subscriptions in one statement per request.
|
||||
|
||||
#### Scenario: The paid plan's card while the grant holds
|
||||
|
||||
@@ -63,3 +63,146 @@ On the Products page, on a ladder a grant holds while a live subscription of the
|
||||
- **WHEN** a member opens the Products page of an organization whose subscription to Pro is paused with the console's marker for a Basic grant on the same ladder
|
||||
- **THEN** Pro's card reads "Paused while Basic is granted" with Resume plan and then Cancel plan, Plus's card draws no control, and Max's card offers "Upgrade"
|
||||
- **AND** Resume plan opens the confirmation "Resume Pro?" with "Your subscription replaces the grant. Nothing is charged now; then {price}."
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Plan-move controls reflect built billing mechanics
|
||||
|
||||
Each non-current plan tier SHALL present a move control whose enablement reflects whether the underlying billing mechanism is implemented and whether the member's subscription is free to move. With the `plan-switch-mechanics` change, the previously-disabled paid moves are now built, so the catalog SHALL **enable** them:
|
||||
|
||||
- **Free/default rung → paid rung**: an active control that submits the target tier's `price_id` to the checkout action specified by `member-plan-upgrade` (unchanged).
|
||||
- **Paid rung → another paid rung** (up or down): an active control routed to the `stripe-subscription-management` **switch** endpoint, which changes the existing subscription item's price. Before confirmation, the control SHALL surface the preview that endpoint's "Live proration preview before a switch" requirement defines: for a move up, the amount charged now and the recurring price after it; for a move down, the date the current tier ends and the recurring price after it.
|
||||
- **Paid rung → free/default rung**: an active control routed to the `stripe-subscription-management` **cancellation** endpoint, defaulting to cancel-at-period-end. Only a rank-0 tier that carries no price is this move; a rank-0 tier with a price is a paid rung like any other, and moving to it is a paid-to-paid downgrade. This move SHALL exist only when the cancel confirmation's prediction ("The member's current plan shows its cost and renewal") puts the free rung on its ladder, by a resumed grant (the free rung is the held rung, below) or by the default restoration. Otherwise the free rung SHALL carry no move control, and the current card's "Cancel plan" is the way to cancel. A subscription whose `current_period_end` is unknown has no prediction, and its free rung SHALL keep this move. Once the subscription's cancellation is scheduled (`cancel_at_period_end`), the free rung SHALL carry no move control either, because a second cancellation is not a move; the current card's "Keep plan" control is the way back.
|
||||
- **Paid rung → held rung below it**: an active "Downgrade" control routed to the **cancellation** endpoint at the period end, as defined below.
|
||||
|
||||
A rung is **paid**, for these moves, when a subscription backs the member's position on it, because only a subscription can be switched or cancelled; its rank and price do not decide it. A rung the member holds by a grant, the organization type's default included, is not paid. When no subscription of the organization pays for a tier of the ladder (`member-offer`, "One decision says which move a member is offered on a ladder"), a higher tier SHALL be offered through Checkout, as from the free/default rung, and a lower tier SHALL carry no move control, because a member cannot end a grant; on a ladder a subscription pays for without holding its rung, the tiers carry the moves "A paid plan whose ladder a grant holds shows its pause on its own card" states. The switch preview SHALL refuse, with the switch's own answer, a ladder on which no subscription of the organization holds the rung or pays for a tier.
|
||||
|
||||
The tier a scheduled downgrade moves to, on its ladder, SHALL carry no move control while that move is scheduled, because the move is already made; the current card's "Keep plan" control is the way back. Every other rung keeps the control it would have without the scheduled move. On a ladder where the scheduled downgrade's product has no tier, no rung is that tier. The held rung is the exception: when the scheduled move lands on it, its control stays the held move, which cancels at the period end and replaces the downgrade (grant-resumption design D11, D24).
|
||||
|
||||
A ladder has a **held rung** when `grant-resumption`'s definition ("One definition says which grants would resume") returns a grant whose product is a tier of that ladder, with the subscription backing the member's current rung on it as holder, evaluated at the date a period-end cancellation would take effect: `commitment_end` when a live commitment's policy is `block`, and `current_period_end` otherwise. The held rung is that grant's tier on the ladder. A grant that would expire by that date yields no held rung, and a subscription whose `current_period_end` is unknown yields none. On a ladder with a held rung:
|
||||
|
||||
- when the held rung ranks below the current rung, its control SHALL read "Downgrade" and SHALL be routed to the **cancellation** endpoint at the period end, because the subscription's end resumes the grant; its confirmation SHALL be the current card's cancel confirmation ("The member's current plan shows its cost and renewal"), which names the held rung ("You keep Pro until Oct 26, 2026, then move to Plus.");
|
||||
- when the held rung ranks above the current rung, it SHALL carry no control: the current card's "Cancel plan", whose confirmation names the tier that follows ("You keep Plus until Oct 26, 2026, then move to Pro."), is the way there (grant-resumption design D10). A member reaches this placement only through a downgrade scheduled before the grant was marked, or through an edit to the subscription's price at the payment provider; whether the console should prevent or resolve that state is [forge issue #159](https://git.coopcloud.tech/wiki-cafe/member-console/issues/159);
|
||||
- once the subscription's cancellation is scheduled (`cancel_at_period_end`), the held rung SHALL carry no control, because the move it offered is already made; the current card's "Keep plan" control is the way back;
|
||||
- every rung ranked below both the held rung and the current rung, the free rung included, SHALL carry no move control, because a member cannot end a grant and cancelling lands on the held rung;
|
||||
- every other rung is routed as above for a subscription-backed rung;
|
||||
- the switch endpoint, preview and commit alike, SHALL refuse the held rung and every rung ranked below both it and the current rung with the unavailable-plan answer ("That plan is no longer available. Refresh the page and choose a current plan."), so a page rendered before the grant was marked cannot schedule a switch this routing no longer offers.
|
||||
|
||||
Commitment policy (`subscriptions.early_termination_policy`) for a mid-term downgrade or cancellation is **enforced by the `stripe-subscription-management` endpoints**, not pre-reflected on the control: the catalog renders the move enabled, and on submission `block` defers the change to `commitment_end` while `fee` is refused with a reason — the outcome surfaces in the re-rendered catalog. Reflecting the policy *on the control itself* before submission — labeling a `block` move as taking effect at `commitment_end`, or rendering a `fee` move disabled up front — is a **deferred enhancement** (tracked as [forge issue #18](https://git.coopcloud.tech/wiki-cafe/member-console/issues/18)), latent until operators can configure commitments and the all-evergreen deployment carries one. The plans view model SHALL expose each tier's `price_id`, the move's target endpoint, and a flag indicating whether the move is enabled. Each add-on row SHALL show an enabled "Add" button that submits the product's default `price_id` to the checkout action specified by `member-plan-upgrade`.
|
||||
|
||||
#### Scenario: Free/default-to-paid move is an active control
|
||||
|
||||
- **WHEN** a member is on the free/default rung of a ladder and a higher paid tier is purchasable
|
||||
- **THEN** that tier's card SHALL show an active "Upgrade" control that submits the tier's `price_id` per `member-plan-upgrade`
|
||||
|
||||
#### Scenario: Paid-to-paid move is enabled and previews its timing
|
||||
|
||||
- **WHEN** a member holds a paid rung on a ladder and another paid rung (higher or lower) is reachable
|
||||
- **THEN** that tier's card SHALL show an active move control routed to the switch endpoint
|
||||
- **AND** confirming the move SHALL first surface the preview: the amount charged now for a move up, the date the current tier ends for a move down
|
||||
|
||||
#### Scenario: Paid-to-free move is enabled as a cancellation
|
||||
|
||||
- **WHEN** a member holds a paid rung, the free/default rung of the same ladder is reachable as a downgrade, and cancelling would put that free rung on the ladder
|
||||
- **THEN** that rung SHALL show an active control routed to the cancellation endpoint, defaulting to cancel-at-period-end
|
||||
|
||||
#### Scenario: The free rung has no control when cancelling leaves its ladder empty
|
||||
|
||||
- **WHEN** a member on Pro by subscription, on Wiki plans and Forum plans, where Forum plans is the organization type's default ladder with Free as its free rung, bought over only a marked grant for Plus on Wiki plans
|
||||
- **THEN** Free's card on Forum plans shows no move control, because the resumed grant keeps the default restoration from running
|
||||
- **AND** Pro's "Cancel plan" confirmation reads "You keep Pro until Oct 26, 2026, then move to Plus on Wiki plans and leave Forum plans."
|
||||
|
||||
#### Scenario: A free rung that is not the default has no control
|
||||
|
||||
- **WHEN** a member on Standard by subscription views a ladder whose free rung is not the organization type's default product, and no grant waits on the subscription
|
||||
- **THEN** that free rung's card shows no move control, and Standard's card offers "Cancel plan"
|
||||
|
||||
#### Scenario: A paid lowest tier is a downgrade, not a cancellation
|
||||
|
||||
- **WHEN** a member holds rank 1 on a ladder whose rank-0 tier carries a price
|
||||
- **THEN** the rank-0 tier's card SHALL show a "Downgrade" control routed to the switch endpoint
|
||||
- **AND** it SHALL NOT be routed to the cancellation endpoint
|
||||
|
||||
#### Scenario: A rung held by a grant moves up through Checkout
|
||||
|
||||
- **WHEN** a member holds a priced rung by a grant, a higher tier is purchasable, and no subscription of the organization pays on the ladder
|
||||
- **THEN** that tier's card SHALL show an active "Upgrade" control routed to Checkout, a lower tier's card SHALL show no move control, and the current card SHALL offer no cancellation
|
||||
|
||||
#### Scenario: A subscriber on a priced rank-0 tier switches up
|
||||
|
||||
- **WHEN** a member's subscription backs a rank-0 tier that carries a price
|
||||
- **THEN** a higher tier's "Upgrade" control SHALL be routed to the switch, not to Checkout
|
||||
|
||||
#### Scenario: A move down to a held rung is a cancellation at renewal
|
||||
|
||||
- **WHEN** a member on Pro by subscription, renewing Oct 26, 2026, holds Plus by a grant marked to resume that the subscription bought over and that has no end date
|
||||
- **THEN** Plus's card shows an active "Downgrade" control routed to the cancellation endpoint, whose confirmation reads "You keep Pro until Oct 26, 2026, then move to Plus."
|
||||
- **AND** the free rung's card below Plus shows no move control
|
||||
|
||||
#### Scenario: A held rung carries no control once the cancellation is scheduled
|
||||
|
||||
- **WHEN** a member on Pro, renewing Oct 26, 2026, chose Plus's "Downgrade" on the held rung and confirmed, so the subscription's cancellation is scheduled for Oct 26, 2026
|
||||
- **THEN** Plus's card reads "Granted" and carries no control
|
||||
- **AND** Pro's card says the plan ends on Oct 26, 2026 and offers "Keep plan" alone
|
||||
|
||||
#### Scenario: A rung between the held rung and the current rung is still a switch
|
||||
|
||||
- **WHEN** the same member views Standard, ranked between Plus and Pro
|
||||
- **THEN** Standard's "Downgrade" control is routed to the switch endpoint, taking effect at renewal
|
||||
|
||||
#### Scenario: A held rung above the current rung carries no control
|
||||
|
||||
- **WHEN** a member's subscription, renewing Oct 26, 2026, bought over a marked grant for Pro and now delivers Plus, because a downgrade scheduled before the grant was marked has landed
|
||||
- **THEN** Pro's card reads "Granted" and carries no control
|
||||
- **AND** Plus's "Cancel plan" confirmation reads "You keep Plus until Oct 26, 2026, then move to Pro."
|
||||
- **AND** Standard, ranked between Plus and Pro, is an upgrade routed to the switch, and a rung below Plus shows no move control
|
||||
|
||||
#### Scenario: The free rung has no control once the cancellation is scheduled
|
||||
|
||||
- **WHEN** a member on Standard by subscription, with no grant waiting, scheduled the cancellation, and the free rung would otherwise carry "Downgrade"
|
||||
- **THEN** the free rung's card shows no move control
|
||||
- **AND** Standard's card offers "Keep plan" alone
|
||||
|
||||
#### Scenario: A grant that expires before the cancellation would take effect holds no rung
|
||||
|
||||
- **WHEN** the grant for Plus has `valid_until` on or before the subscription's `current_period_end`
|
||||
- **THEN** Plus's "Downgrade" control is routed to the switch endpoint, as for any paid rung
|
||||
- **AND** the current card's cancel confirmation follows the rule for a ladder without a held rung
|
||||
|
||||
#### Scenario: A block commitment judges the grant at the commitment's end
|
||||
|
||||
- **WHEN** the subscription's live commitment has policy `block` and a `commitment_end` after the grant's `valid_until`, and the grant's `valid_until` is after `current_period_end`
|
||||
- **THEN** the ladder has no held rung
|
||||
|
||||
#### Scenario: An unmarked grant holds no rung
|
||||
|
||||
- **WHEN** the grant for Plus is not marked to resume
|
||||
- **THEN** the ladder's moves are routed as if no grant existed
|
||||
|
||||
#### Scenario: The tier a scheduled downgrade moves to carries no control
|
||||
|
||||
- **WHEN** a member on Pro has a downgrade to Standard scheduled for the period end
|
||||
- **THEN** Standard's card carries no move control
|
||||
- **AND** the other rungs keep the controls they had before the downgrade was scheduled
|
||||
- **AND** the current card offers "Keep plan" and "Cancel plan"
|
||||
|
||||
#### Scenario: A scheduled downgrade onto the held rung keeps the held move
|
||||
|
||||
- **WHEN** a member on Pro has a downgrade to Plus scheduled for the period end, and Plus is the held rung
|
||||
- **THEN** Plus's card reads "Granted" and keeps its "Downgrade", routed to the cancellation at the period end
|
||||
|
||||
#### Scenario: A stale page cannot switch to a held rung
|
||||
|
||||
- **WHEN** a member submits the switch preview or the switch for Plus after the grant was marked
|
||||
- **THEN** the endpoint refuses it with "That plan is no longer available. Refresh the page and choose a current plan." and schedules nothing
|
||||
|
||||
#### Scenario: Committed move is enabled; its policy is enforced on submission
|
||||
|
||||
- **WHEN** a member's subscription has a `commitment_end` in the future and the move is a downgrade or cancellation
|
||||
- **THEN** the catalog SHALL render the move control enabled (it does not pre-label the commitment policy)
|
||||
- **AND** on submission the `stripe-subscription-management` endpoint SHALL enforce the policy (`block` defers to `commitment_end`; `fee` is refused with a reason), with the result surfaced in the re-rendered catalog
|
||||
|
||||
#### Scenario: Add-on row shows an enabled add button
|
||||
|
||||
- **WHEN** an add-on product row is rendered
|
||||
- **THEN** the row SHALL show an enabled "Add" button that submits the product's default `price_id` to Checkout
|
||||
|
||||
+61
@@ -94,3 +94,64 @@ On the organization composite, the billing card's Subscriptions row SHALL carry
|
||||
|
||||
- **WHEN** the read of the displacements fails
|
||||
- **THEN** the Subscriptions row shows "Failed to load deliveries." under its value line and no "Not delivering" badge
|
||||
|
||||
### Requirement: Tier changes is the audit list, in operator vocabulary
|
||||
|
||||
The composite's plan audit list SHALL be headed "Tier changes" (the term "position" and the retired "Position history" heading never render; maintainer design round 2026-08-24) with a help-icon tooltip stating what the list is and the name-resolution caveat. Rows SHALL carry the ladder's display name, a humanized change verb (Started, Resumed, Upgraded, Downgraded, Extended, Transferred with a tooltip explaining a funding-source change at the same tier, Ended), and tier NAMES for the from/to sides resolved from the ladder's current shape — best effort: a rank no longer present on the ladder falls back to "rank N", and the sides a Started, Resumed or Ended row does not have render the empty-value marker. The verb SHALL follow one label rule (grant-resumption design D22): a row whose reason is one of the three resumption reasons reads "Resumed", a row whose reason is an operator's extension reads "Extended", and every other row reads its transition type's label, so a restored default stays "Started" with its reason. The landing surface's recent-activity line reads its tier events by the same rule (`operator-panel-navigation`). The list SHALL page with the shared pager under namespaced parameters — default page size 10 with the shared page-size picker — so its links cannot clobber the ledger's tab or search state.
|
||||
|
||||
The list SHALL show one row per act the machinery performed. A supersession (`core.confer()` replacing an incumbent) writes the incumbent's `end` row and the successor's typed row in one call at one instant, and the typed row carries both sides; the list SHALL hide that `end` row, and only that one: an `end` row is hidden exactly when a typed row with a from side exists in the same pool at the same instant with the same actor and reason. An expiry, revocation, or cancellation writes an `end` and then a fresh `initiate` with no from side, which reads "Started" when it is a restored default and "Resumed" when it is a resumed grant (`grant-resumption`); both rows SHALL stay. The list SHALL NOT synthesize a row or invent a from side.
|
||||
|
||||
The Reason cell SHALL read in words. A row whose reason the machinery wrote shows the view's sentence for it (Grant expired; Default restored after a grant expired; Revoked by an operator; Extended by an operator; Default restored after a revocation; Default restored after a subscription ended; Grant resumed after a subscription ended; Grant resumed after a revocation; Grant resumed after a grant expired; Subscription delivers again after a revocation; Subscription delivers again after a grant expired; Subscription delivers again after a subscription ended; Default on organization creation; Seeded default; Org-type default changed; Tier added to the ladder; Ladder tiers reordered; Tier removed from the ladder), with the grant's note as a muted line under it when the row's provision is grant-backed. A row the machinery did not write (Issue grant records the operator's note as the reason) shows the grant's reason label with the note as a muted line under it (the grants ledger's cell). A reason the view does not know renders raw. The raw reason string SHALL ride as the cell's tooltip in every case.
|
||||
|
||||
#### Scenario: A change row reads in names, not integers
|
||||
|
||||
- **WHEN** a pool upgraded from the tier at rank 0 to the tier at rank 1 on a ladder
|
||||
- **THEN** the row renders the ladder's display name, "Upgraded", and the two tiers' product names, with no bare integer ranks
|
||||
|
||||
#### Scenario: A reshaped ladder degrades honestly
|
||||
|
||||
- **WHEN** a historical rank no longer exists on the ladder's current shape
|
||||
- **THEN** that side renders "rank N" and the heading's tooltip states that names reflect the ladder's current shape
|
||||
|
||||
#### Scenario: A supersession is one row
|
||||
|
||||
- **WHEN** an operator issues a grant over an organization's default tier, or extends its tier
|
||||
- **THEN** the list shows one row for the change, with the old tier as From and the new tier as To, and no separate Ended row for the replaced provision
|
||||
|
||||
#### Scenario: An expiry is two rows
|
||||
|
||||
- **WHEN** a grant expires and the org-type default is restored
|
||||
- **THEN** the list shows an Ended row for the expired tier reading "Grant expired" with the grant's note under it, and a Started row for the default reading "Default restored after a grant expired", both at the expiry's time
|
||||
|
||||
#### Scenario: A grant-backed row shows the grant's reason and the note
|
||||
|
||||
- **WHEN** an operator issued a grant with the reason Evaluation and a note
|
||||
- **THEN** its Tier changes row's Reason cell reads "Evaluation" with the note as a muted line under it, and no identifier appears in the cell
|
||||
|
||||
#### Scenario: An extension reads as Extended
|
||||
|
||||
- **WHEN** an operator extends a tier with a note
|
||||
- **THEN** the list shows one row for the extension, its Change reading "Extended" with no funding-source tooltip, the same tier as From and To, and its Reason cell reading "Extended by an operator" with the note as a muted line under it
|
||||
- **AND** the Change of a handoff between funding sources that is not an extension still reads "Transferred" with the funding-source tooltip
|
||||
|
||||
#### Scenario: A resumption is two rows
|
||||
|
||||
- **WHEN** a subscription on Pro ends and a marked grant for Plus that it bought over resumes
|
||||
- **THEN** the list shows an Ended row for Pro and a row for Plus whose Change reads "Resumed" and whose Reason cell reads "Grant resumed after a subscription ended" with the grant's note under it, both at the reconcile's time
|
||||
- **AND** no row for the resumption reads "Started"
|
||||
|
||||
#### Scenario: A resumption after a revocation is two rows
|
||||
|
||||
- **WHEN** an operator revokes an evaluation grant for Pro and the marked grant for Plus it was issued over resumes
|
||||
- **THEN** the list shows an Ended row for Pro reading "Revoked by an operator" and a Resumed row for Plus reading "Grant resumed after a revocation", both at the revocation's time
|
||||
- **AND** when the evaluation expires instead, the Resumed row reads "Grant resumed after a grant expired"
|
||||
|
||||
#### Scenario: A restored default still reads Started
|
||||
|
||||
- **WHEN** a subscription on Pro ends, no marked grant resumes, and the floor restores the default Free
|
||||
- **THEN** the list shows an Ended row for Pro and a row for Free whose Change reads "Started" and whose Reason cell reads "Default restored after a subscription ended"
|
||||
|
||||
#### Scenario: A subscription delivers again after a revocation
|
||||
|
||||
- **WHEN** an operator revokes the grant that displaced a subscription
|
||||
- **THEN** the list shows an "Ended" row reading "Revoked by an operator", and a "Started" row reading "Subscription delivers again after a revocation"
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ Every reconcile SHALL record the subscription's `pause_collection` behavior, its
|
||||
|
||||
### Requirement: A subscription delivers again in the act that ends the plan holding its ladder
|
||||
|
||||
A revocation, an expiry, the subscription reconcile's ended branch and its end of a surplus provision SHALL, when they ended at least one provision of the ending plan, confer in the same transaction each live subscription's recorded products that the displacement rule no longer leaves alone, after the resumption of marked grants and before the default floor, under the pool row the act holds and without any subscription's advisory lock. The step, `entitlements.DeliverDisplacedSubscriptionsTx`, SHALL read the recorded current items of the organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused` (the ending subscription left out), keep each product with an entitlement set that has no live provision of the subscription, apply the displacement rule and the reconcile's choice of tiers to them, and confer each kept product sourced by the subscription, each subscription under its own savepoint, the subscriptions the ending plan superseded first and then the rest, each group in ascending subscription id order and each subscription's products in ascending `product_id` order. A subscription whose status is `past_due`, `unpaid` or `paused` SHALL be suspended through `core.sync_source_status` in the same savepoint, so its tier comes back suspended. A conferral the database refuses SHALL roll back to its savepoint, SHALL be logged, and SHALL NOT fail the act; a lock wait, a deadlock or a cancelled context SHALL fail it. The step SHALL only confer: ending and re-bounding stay with the subscription's own reconcile, which the act's outbox request runs. An act that ended nothing SHALL deliver nothing.
|
||||
A revocation, an expiry, the subscription reconcile's ended branch and its end of a surplus provision SHALL, when they ended at least one provision of the ending plan, confer in the same transaction each live subscription's recorded products that the displacement rule no longer leaves alone, after the resumption of marked grants and before the default floor, under the pool row the act holds and without any subscription's advisory lock. The step, `entitlements.DeliverDisplacedSubscriptionsTx`, SHALL read the recorded current items of the organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused` (the ending subscription left out), keep each product with an entitlement set that has no live provision of the subscription, apply the displacement rule and the reconcile's choice of tiers to them, and confer each kept product sourced by the subscription, each subscription under its own savepoint, the subscriptions whose latest episode on a ladder of the pool was superseded by a provision the act ended first, and then the rest, each group in ascending subscription id order and each subscription's products in ascending `product_id` order. A subscription whose status is `past_due`, `unpaid` or `paused` SHALL be suspended through `core.sync_source_status` in the same savepoint, so its tier comes back suspended. A conferral the database refuses SHALL roll back to its savepoint, SHALL be logged, and SHALL NOT fail the act; a lock wait, a deadlock or a cancelled context SHALL fail it. The step SHALL only confer: ending and re-bounding stay with the subscription's own reconcile, which the act's outbox request runs. An act that ended nothing SHALL deliver nothing.
|
||||
|
||||
#### Scenario: A revocation delivers the subscription in its own transaction
|
||||
|
||||
|
||||
@@ -16,33 +16,34 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
## 2. The subscription row mirrors the pause, and the Overview leaves a paused subscription out of its headline
|
||||
|
||||
- [ ] 2.1 `internal/db/migrations/00036_subscription_collection_pause.sql` (design D3, Migration plan): the SPDX header; a header comment in the style of `00026` saying what the three columns record, that every reconcile writes them from the subscription it fetched, and that the console's own pause is the one whose marker column is true; `ALTER TABLE core.subscriptions ADD COLUMN pause_collection_behavior TEXT NULL, ADD COLUMN pause_collection_resumes_at TIMESTAMPTZ NULL, ADD COLUMN pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE;`, with no check on the behavior, as `status` has none (design D3). Down drops the three columns.
|
||||
- [ ] 2.2 `internal/billing/queries/subscriptions.sql`: `CreateSubscription` and `UpdateSubscriptionStatus` stay as they are; a new `UpdateSubscriptionCollection :exec` sets `pause_collection_behavior`, `pause_collection_resumes_at` and `pause_collection_marked` for a `subscription_id`; `ListSubscriptionsPage` selects `s.pause_collection_behavior` after `s.cancel_at_period_end`; `SumMonthlyRecurringByCurrency` adds `AND s.pause_collection_behavior IS NULL` to `WHERE s.status = 'active'` (Copy O4), and its comment says why. `make sqlc-generate`: the generated diff is `internal/billing/models.go`'s `Subscription` gaining the three fields; the column lists of `internal/billing/subscriptions.sql.go` (`CreateSubscription`, `GetSubscriptionByID`, `GetSubscriptionsByBillingAccountID`, `UpdateSubscriptionStatus`) and of `internal/billing/billing_accounts.sql.go` (`GetLatestSubscriptionByBillingAccountID`, a `SELECT * FROM core.subscriptions` at `internal/billing/queries/billing_accounts.sql:69-75`); the new query in `subscriptions.sql.go` and `querier.go`; and `ListSubscriptionsPage`'s column. No existing caller changes, and the test fakes that embed `billing.Querier` still compile, because the embedded interface supplies the new method. The test kit's `Suspend` (`internal/testkit/world/plans.go:377-389`), `CancelAtPeriodEnd` (`:439-446`) and `EndSubscription` (`internal/testkit/world/acts.go:104-113`) and the demo seed (`internal/demoseed/demoseed.go:1065`) call `UpdateSubscriptionStatus`, which leaves the mirror alone, so a `PauseCollection` made before them survives (design D3).
|
||||
- [ ] 2.3 `internal/fulfillment/reconcile.go`, `upsertSubscription`: `collectionMirror(sub *stripe.Subscription) (behavior sql.NullString, resumesAt sql.NullTime, marked bool)`, reading no row, maps `sub.PauseCollection` (nil gives NULL, NULL, and the marker test alone) and `sub.Metadata[collectionMarkerKey] == collectionMarkerValue`; both branches call `UpdateSubscriptionCollection` with its values, directly after `CreateSubscription` or `UpdateSubscriptionStatus` and before the branch's other statements (`UpsertSubscriptionMapping`, `CreateSubscriptionChange`). `collectionMarkerKey = "member_console_collection"` and `collectionMarkerValue = "paused_for_grant"` are constants in a new `internal/fulfillment/collection.go`, with a doc comment naming the schedules' precedent (`findSpentSchedule`).
|
||||
- [ ] 2.4 Reader role: `internal/migrate/testdata/console-reader-columns.txt` gains `read core.subscriptions.pause_collection_behavior`, `read core.subscriptions.pause_collection_marked` and `read core.subscriptions.pause_collection_resumes_at`, in the file's order (the file aligns its columns, as `read core.…` shows, and is written with `-update`); `scripts/db-reader-role.sql` needs no edit if it grants by the file's rule, otherwise its `core.subscriptions` column list gains the three.
|
||||
- [ ] 2.5 Test kit: `(w *World) PauseCollection(s Subscription)` in `internal/testkit/world/billing.go` sets `pause_collection_behavior = 'void'` and `pause_collection_marked = true` on the subscription's row, with a doc comment saying it stands for the reconcile's record of the console's pause; `(w *World) ForeignPause(s Subscription)` sets the behavior alone.
|
||||
- [ ] 2.6 Tests:
|
||||
- [x] 2.1 `internal/db/migrations/00036_subscription_collection_pause.sql` (design D3, Migration plan): the SPDX header; a header comment in the style of `00026` saying what the three columns record, that every reconcile writes them from the subscription it fetched, and that the console's own pause is the one whose marker column is true; `ALTER TABLE core.subscriptions ADD COLUMN pause_collection_behavior TEXT NULL, ADD COLUMN pause_collection_resumes_at TIMESTAMPTZ NULL, ADD COLUMN pause_collection_marked BOOLEAN NOT NULL DEFAULT FALSE;`, with no check on the behavior, so a value a later API version adds does not stop the reconcile (design D3). Down drops the three columns.
|
||||
- [x] 2.2 `internal/billing/queries/subscriptions.sql`: `CreateSubscription` and `UpdateSubscriptionStatus` stay as they are; a new `UpdateSubscriptionCollection :exec` sets `pause_collection_behavior`, `pause_collection_resumes_at` and `pause_collection_marked` for a `subscription_id`; `ListSubscriptionsPage` selects `s.pause_collection_behavior` after `s.cancel_at_period_end`; `SumMonthlyRecurringByCurrency` adds `AND s.pause_collection_behavior IS NULL` to `WHERE s.status = 'active'` (Copy O4), and its comment says why. `make sqlc-generate`: the generated diff is `internal/billing/models.go`'s `Subscription` gaining the three fields; the column lists of `internal/billing/subscriptions.sql.go` (`CreateSubscription`, `GetSubscriptionByID`, `GetSubscriptionsByBillingAccountID`, `UpdateSubscriptionStatus`) and of `internal/billing/billing_accounts.sql.go` (`GetLatestSubscriptionByBillingAccountID`, a `SELECT * FROM core.subscriptions` at `internal/billing/queries/billing_accounts.sql:69-75`); the new query in `subscriptions.sql.go` and `querier.go`; and `ListSubscriptionsPage`'s column. No existing caller changes, and the test fakes that embed `billing.Querier` still compile, because the embedded interface supplies the new method. The test kit's `Suspend` (`internal/testkit/world/plans.go:377-389`), `CancelAtPeriodEnd` (`:439-446`) and `EndSubscription` (`internal/testkit/world/acts.go:104-113`) and the demo seed (`internal/demoseed/demoseed.go:1065`) call `UpdateSubscriptionStatus`, which leaves the mirror alone, so a `PauseCollection` made before them survives (design D3).
|
||||
- [x] 2.3 `internal/fulfillment/reconcile.go`, `upsertSubscription`: `collectionMirror(sub *stripe.Subscription) (behavior sql.NullString, resumesAt sql.NullTime, marked bool)`, reading no row, maps `sub.PauseCollection` (nil gives NULL, NULL, and the marker test alone) and `sub.Metadata[collectionMarkerKey] == collectionMarkerValue`; both branches call `UpdateSubscriptionCollection` with its values, directly after `CreateSubscription` or `UpdateSubscriptionStatus` and before the branch's other statements (`UpsertSubscriptionMapping`, `CreateSubscriptionChange`). `collectionMarkerKey = "member_console_collection"` and `collectionMarkerValue = "paused_for_grant"` are constants in a new `internal/fulfillment/collection.go`, with a doc comment naming the schedules' precedent (`findSpentSchedule`).
|
||||
- [x] 2.4 Reader role: `internal/migrate/testdata/console-reader-columns.txt` gains `read core.subscriptions.pause_collection_behavior`, `read core.subscriptions.pause_collection_marked` and `read core.subscriptions.pause_collection_resumes_at`, in the file's order (the file aligns its columns, as `read core.…` shows, and is written with `-update`); `scripts/db-reader-role.sql` needs no edit if it grants by the file's rule, otherwise its `core.subscriptions` column list gains the three.
|
||||
- [x] 2.5 Test kit: `(w *World) PauseCollection(s Subscription)` in `internal/testkit/world/billing.go` sets `pause_collection_behavior = 'void'` and `pause_collection_marked = true` on the subscription's row, with a doc comment saying it stands for the reconcile's record of the console's pause; `(w *World) ForeignPause(s Subscription)` sets the behavior alone.
|
||||
- [x] 2.6 Tests:
|
||||
- `TestSubscriptionCollectionPauseMigrationUpDownUp` (`internal/db/subscription_collection_pause_test.go`): up, down, up on a `dbtest.Scratch` database, with the columns present after each up and absent after the down. Failure text: `after %s, column %s present = %v, want %v`.
|
||||
- `TestReconcile_MirrorsTheCollectionPause` (`internal/fulfillment/collection_test.go`), rows through `checkMirror`: `no pause` (NULL, NULL, false), `the console's pause` (void, NULL, true), `a pause made in the Dashboard` (`mark_uncollectible`, a `resumes_at`, false), `a marker with no pause` (NULL, NULL, true), and `first sight, the console's pause` (void, NULL, true, the subscription's first reconcile, which goes through `CreateSubscription`); each other row reconciles the subscription once with no pause (the create branch) and then once in the row's state (the update branch), reading the row after the second. Failure text: `mirror(%s) = %q, %v, %v, want %q, %v, %v`.
|
||||
- `TestReconcile_MirrorsTheCollectionPause` (`internal/fulfillment/collection_test.go`), rows through `checkMirror`: `no pause` (NULL, NULL, false), `the console's pause` (void, NULL, true), `a pause made in the Dashboard` (`mark_uncollectible`, a `resumes_at`, false), `a marker with no pause` (NULL, NULL, true), `the console's pause cleared` (first reconciled with the console's pause, then with no pause and no marker: NULL, NULL, false), and `first sight, the console's pause` (void, NULL, true, the subscription's first reconcile, which goes through `CreateSubscription`); each other row reconciles the subscription once with no pause (the create branch) and then once in the row's state (the update branch), reading the row after the second. Failure text: `mirror(%s) = %q, %v, %v, want %q, %v, %v`.
|
||||
- `TestConsoleReaderColumns` passes with the three lines.
|
||||
- `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription` (`internal/server/operator_overview_db_test.go`): three active subscriptions of one currency from the kit, one of them `PauseCollection` and one `ForeignPause` (a pause made in the Dashboard leaves the headline too). The query sums every `active` subscription in the shared test database, so the test reads `SumMonthlyRecurringByCurrency`'s `usd` bucket before it builds the fixture and after it, and the difference equals the third subscription's monthly amount; `recurringCaption(3, 0, nil, 1)`, called with the fixture's own counts and not the global count query, reads "3 active subscriptions". Failure texts: `monthly recurring = %v, want %v: a paused subscription was summed`; `caption = %q, want %q`.
|
||||
- [ ] 2.7 Docs: `docs/models/payments-billing.md`, the subscriptions row of its table and the Reconciler row (`:40`), say that the row records the collection pause Stripe reports, and that the Monthly recurring headline leaves a paused subscription out; the status-classification note (`:83`) gains "except a subscription grants displace, whose collection the console pauses"; `00036` is listed where the model lists its migrations.
|
||||
- [ ] 2.8 Trace goldens, rewritten with `-update` and read: the 39 goldens under `internal/fulfillment/testdata/` whose trace holds `UpdateSubscriptionStatus` or `CreateSubscription` each gain the one line `UpdateSubscriptionCollection` directly after that statement. Their `== rows` sections are unchanged, because the subscriptions dump names its fields. Any other change is a stop. The 39 are every file of `scheduled_change_trace/` (9); in `reconcile_trace/`, `active_again`, `addon_added`, `addon_removed`, `canceled_replay`, `canceled_resumes_grant`, `canceled_to_default`, `first_sight`, `grant_over_subscription`, `grant_over_suspended_recovery`, `incomplete`, `item_replaced`, `item_without_id`, `past_due`, `price_swap`, `product_without_set`, `quantity`, `quantity_zero`, `replay`, `second_subscription_over_first`, `three_ladders_first_sight`, `two_tiers_one_ladder` and `unmapped_price` (22; `fetch_refused`, `no_customer` and `unreachable` do not change); in `sweep_trace/`, `already_canceled`, `already_ended`, `cancellation_refused`, `due_cancellation`, `lost_claim`, `period_end_landed`, `stale_downgrade` and `term_boundary_switch` (8; `quantity_change`, `term_boundary_switch_refused`, `unreachable_item` and `unreachable_target_price` do not change). The demo seed's statement goldens (`internal/demoseed/testdata/`) do not change, because the seed calls `CreateSubscription` and `UpdateSubscriptionStatus` itself.
|
||||
- [ ] 2.9 Breaks:
|
||||
- [x] 2.7 Docs: `docs/models/payments-billing.md`, the subscriptions row of its table and the Reconciler row (`:40`), say that the row records the collection pause Stripe reports, and that the Monthly recurring headline leaves a paused subscription out; the status-classification note (`:83`) gains "A subscription that grants displace delivers nothing while they hold its ladders, and the console pauses its collection."; `00036` is listed where the model lists its migrations.
|
||||
- [x] 2.8 Trace goldens, rewritten with `-update` and read: the 39 goldens under `internal/fulfillment/testdata/` whose trace holds `UpdateSubscriptionStatus` or `CreateSubscription` each gain the one line `UpdateSubscriptionCollection` directly after that statement. Their `== rows` sections are unchanged, because the subscriptions dump names its fields. Any other change is a stop. The 39 are every file of `scheduled_change_trace/` (9); in `reconcile_trace/`, `active_again`, `addon_added`, `addon_removed`, `canceled_replay`, `canceled_resumes_grant`, `canceled_to_default`, `first_sight`, `grant_over_subscription`, `grant_over_suspended_recovery`, `incomplete`, `item_replaced`, `item_without_id`, `past_due`, `price_swap`, `product_without_set`, `quantity`, `quantity_zero`, `replay`, `second_subscription_over_first`, `three_ladders_first_sight`, `two_tiers_one_ladder` and `unmapped_price` (22; `fetch_refused`, `no_customer` and `unreachable` do not change); in `sweep_trace/`, `already_canceled`, `already_ended`, `cancellation_refused`, `due_cancellation`, `lost_claim`, `period_end_landed`, `stale_downgrade` and `term_boundary_switch` (8; `quantity_change`, `term_boundary_switch_refused`, `unreachable_item` and `unreachable_target_price` do not change). The demo seed's statement goldens (`internal/demoseed/testdata/`) do not change, because the seed calls `CreateSubscription` and `UpdateSubscriptionStatus` itself.
|
||||
- [x] 2.9 Breaks:
|
||||
- the headline's predicate dropped (the generated `SumMonthlyRecurringByCurrency` constant without `AND s.pause_collection_behavior IS NULL`): caught by `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription`, `want_new` `a paused subscription was summed`;
|
||||
- the marker not read (`sub.Metadata[collectionMarkerKey] == collectionMarkerValue` replaced by `false` in `collectionMirror`): caught by `TestReconcile_MirrorsTheCollectionPause`, `want_new` `mirror(the console's pause) =`;
|
||||
- the update branch not writing the mirror (the `UpdateSubscriptionCollection` call deleted from the update branch of `upsertSubscription`): caught by the same test, `want_new` `mirror(the console's pause) =`;
|
||||
- the create branch not writing the mirror (the call deleted from the create branch): caught by the `first sight, the console's pause` row, `want_new` `mirror(first sight, the console's pause) =`;
|
||||
- the reader-columns line removed for `pause_collection_marked`: caught by `TestConsoleReaderColumns`, `want_new` `console_reader's columns disagree with` (`internal/migrate/console_reader_test.go:139`);
|
||||
- `pause_collection_resumes_at` mirrored as NULL always: caught by the `a pause made in the Dashboard` row, `want_new` `mirror(a pause made in the Dashboard) =`;
|
||||
- the foreign pause summed (the headline's predicate tested on the marker instead of the behavior): caught by `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription`, `want_new` `a paused subscription was summed`.
|
||||
- [ ] 2.10 `make screens`: no screen changes, because the demo holds no paused subscription.
|
||||
- the foreign pause summed (the headline's predicate tested on the marker instead of the behavior): caught by `TestOverviewMonthlyRecurringLeavesOutAPausedSubscription`, `want_new` `a paused subscription was summed`;
|
||||
- a cleared pause not recorded (the generated `updateSubscriptionCollection` constant's `pause_collection_behavior = $2` replaced by `pause_collection_behavior = COALESCE($2, pause_collection_behavior)`): caught by the `the console's pause cleared` row, `want_new` `mirror(the console's pause cleared) =`.
|
||||
- [x] 2.10 `make screens`: no screen changes, because the demo holds no paused subscription.
|
||||
|
||||
## 3. The reconcile decides the pause, and the outbox applies it
|
||||
|
||||
- [ ] 3.1 `internal/entitlements/collection.go` (new): `CollectionPauseWanted(status string, desired []string, left map[string]Displacement) bool`, reading no row, as design D2 states the rule; its doc comment states the four conditions and why a subscription displaced by another subscription keeps billing.
|
||||
- [ ] 3.2 `internal/fulfillment/collection.go`: `collectionAction` (`collectionNone`, `collectionSet`, `collectionClear`) and `decideCollection(wanted bool, sub *stripe.Subscription) (collectionAction, foreign bool)`, reading no row, as design D2's table states; `collectionParams(action) *stripe.SubscriptionParams` builds the set (`PauseCollection: &stripe.SubscriptionPauseCollectionParams{Behavior: stripe.String("void")}` and `AddMetadata(collectionMarkerKey, collectionMarkerValue)`) or the clear (`AddExtra("pause_collection", "")` and `AddMetadata(collectionMarkerKey, "")`).
|
||||
- [ ] 3.3 `internal/fulfillment/reconcile.go`: `ReconcileSubscription`'s body becomes `reconcile(ctx, db, logger, keyMode, stripeSubscriptionID, reason string, applyCollection bool) (called bool, err error)`, which `ReconcileSubscription` calls with `false`, dropping the flag; `called` is true when `applyCollectionAction` made its call. In the active branch, `convergeConferrals` returns its `left` map and the desired products; the branch calls `entitlements.CollectionPauseWanted` and `decideCollection`, logs L1 when `foreign` and the rule wants a pause, and keeps the action for after the commit. A non-empty action with `applyCollection` false calls `entitlements.RequestSubscriptionReconcile(ctx, tx, subscriptionID)` before the commit. After the commit, with `applyCollection` true, `applyCollectionAction(ctx, logger, stripeSubscriptionID, action)` makes the one `subscription.Update` call, logs L2 on success, and returns the error wrapped as `reconcile: apply collection to %s: %w`. `ApplySubscriptionCollection(ctx, db, logger, keyMode, coreSubscriptionID, reason string) error` reads the subscription's Stripe mapping (`GetSubscriptionMappingBySubscriptionID`), returns nil with L3 when there is none or it has no Stripe id, and otherwise calls `reconcile` with `true`; when that run made a call, it runs `reconcile` with `true` once more, so the decision is made again from a fetch taken after its own call, at most twice in all, and every error it returns names the Stripe subscription id. The doc comments state design D1's reasons: a member's move never reports a pause failure, and the decision is a set-to-state, so two runs that cross converge through the echo.
|
||||
- [ ] 3.3 `internal/fulfillment/reconcile.go`: `ReconcileSubscription`'s body becomes `reconcile(ctx, db, logger, keyMode, stripeSubscriptionID, reason string, applyCollection bool) (called bool, err error)`, which `ReconcileSubscription` calls with `false`, dropping the flag; `called` is true when `applyCollectionAction` made its call. In the active branch, `convergeConferrals` returns its `left` map and the desired products, and beside them the ids of the provisions `endSurplusConferrals` ended, which `endSurplusConferrals` returns to it (4.5 reads them, and 7.3 passes them to the delivery step); the branch calls `entitlements.CollectionPauseWanted` and `decideCollection`, logs L1 when `foreign` and the rule wants a pause, and keeps the action for after the commit. A non-empty action with `applyCollection` false calls `entitlements.RequestSubscriptionReconcile(ctx, tx, subscriptionID)` before the commit. After the commit, with `applyCollection` true, `applyCollectionAction(ctx, logger, stripeSubscriptionID, action)` makes the one `subscription.Update` call, logs L2 on success, and returns the error wrapped as `reconcile: apply collection to %s: %w`. `ApplySubscriptionCollection(ctx, db, logger, keyMode, coreSubscriptionID, reason string) error` reads the subscription's Stripe mapping (`GetSubscriptionMappingBySubscriptionID`), returns nil with L3 when there is none or it has no Stripe id, and otherwise calls `reconcile` with `true`; when that run made a call, it runs `reconcile` with `true` once more, so the decision is made again from a fetch taken after its own call, at most twice in all, and every error it returns names the Stripe subscription id. The doc comments state design D1's reasons: a member's move never reports a pause failure, and the decision is a set-to-state, so two runs that cross converge through the echo.
|
||||
- [ ] 3.4 The suspended branch (design D6): `reconcileSuspended` keeps its suspension and then, only when the status is `past_due` or `unpaid`, calls `collectionInputs(ctx, billingQ, stripeQ, entQ, sub, subUUID, poolID)`, which resolves each fetched item through `resolveItem` (no write), groups the products with an entitlement set, and reads the live provisions, the shapes and the displacements under the pool row the branch holds, then `DisplacedProducts`; the branch decides as the active one does. A `paused` subscription is never wanted paused and makes no read; a stale marker on it is cleared.
|
||||
- [ ] 3.5 `internal/entitlements/outbox_requests.go` (new): `RequestSubscriptionReconcile(ctx context.Context, tx integration.DBTX, subscriptionID string) error` calls `integration.Enqueue(ctx, tx, "stripe", "reconcile_subscription", map[string]string{"subscription_id": subscriptionID})`; `ReconcileSubscriptionAction = "reconcile_subscription"` is the action type's one constant, which the executor names too.
|
||||
- [ ] 3.6 `internal/integrations/stripe/workflows/outbox.go`, `executeAction`: the case `entitlements.ReconcileSubscriptionAction` calls `a.executeReconcileSubscription(ctx, entry)`, which parses the payload (a missing or malformed `subscription_id` returns a `temporal.NewNonRetryableApplicationError` naming the entry), and returns `classifyStripeError` over `fulfillment.ApplySubscriptionCollection(ctx, a.DB, a.Logger, sdkKeyMode(), id, fmt.Sprintf("outbox:reconcile_subscription:%d", entry.ID))`. Its doc comment says that the call needs no idempotency key of its own because it sets a state. The comment at `internal/server/operator_integrations_stripe.go:263`, "Today only Stripe enqueues into it (operator_billing.go)", is updated, because core `entitlements` now enqueues a Stripe action too.
|
||||
@@ -129,20 +130,23 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
## 6. An hourly sweep asks again for a subscription whose pause disagrees with the rule
|
||||
|
||||
- [ ] 6.1 Queries (design D5): `ListLiveSubscriptionsForCollectionSweep` (`internal/integrations/stripe/store/queries/subscription_mappings.sql`, Go package `stripe`, which `fulfillment` imports as `internalstripe`, because billing's sqlc does not load the Stripe store's migrations, `internal/billing/sqlc.yaml:4-6`, and the store's sqlc loads both streams, `internal/integrations/stripe/store/sqlc.yaml:4-6`; `subscription_id`, `status`, the three mirror columns, and the mapping's `livemode` and `sync_status`; joined to `stripe.subscription_mappings`, so an unmapped subscription never appears; the statuses `active`, `trialing`, `past_due`, `unpaid` and `paused`; `subscription_id > $1` keyset, `LIMIT $2`, ordered by id; its generated code lands in `internal/integrations/stripe/store/subscription_mappings.sql.go`, which every break of the query edits); `ListCurrentSubscriptionItemsBySubscriptionIDs` if no query of that shape exists (billing; subscription id, product id, quantity, `ended_at IS NULL`); `ListLiveProvisionProductsBySubscriptionIDs` (entitlements; subscription id and product id of non-ended provisions); `ListSubscriptionsWithRecentReconcileEntries` (`internal/integration/queries/outbox.sql`; `payload->>'subscription_id'` of `reconcile_subscription` entries whose status is `pending`, `processing` or `failed`, or `dead_letter` with `updated_at > NOW() - interval '1 day'`, for the listed ids). `make sqlc-generate`.
|
||||
- [ ] 6.2 `internal/fulfillment/collection_sweep.go`: `collectionDrift(subs, items, live, rungs, displacements) []string`, reading no row, applies `CollectionPauseWanted` over the recorded products with a set that have no live provision and compares the mirror (wanted and no behavior, or not wanted and the marker set, drift; a foreign pause never does), returning the drifting ids in id order. `SweepCollectionDrift(ctx, db, logger, keyMode) (int, error)` pages, drops the rows whose mapping fails `MappingReachable` under the key, reads once per page, drops ids with a recent entry, and writes one entry per drifting id in one transaction per page; L5 when the count is above zero, L6 and the error on a failed read.
|
||||
- [ ] 6.3 `internal/workflows/billing/activities.go`: `SweepCollectionDriftActivity` calls it with `a.keyMode`; `sweep_workflow.go`: `SweepScheduledChangesWorkflow` runs it after `SweepScheduledChangesActivity`, each activity's failure logged and the other still run; the activity is registered where the first one is.
|
||||
- [ ] 6.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`.
|
||||
- [ ] 6.2 `internal/fulfillment/collection_sweep.go`: `collectionDrift(subs, products, live, rungs, displacements) []string`, reading no row, passes every recorded conferring product of a subscription (6.1's `ListCurrentConferringProductsBySubscriptionIDs`) as `desired` to `CollectionPauseWanted`, with `left` the map `DisplacedProducts` returns over those with no live provision, as `convergeConferrals` builds it, and compares the mirror (wanted and no behavior, or not wanted and the marker set, drift; a foreign pause never does), returning the drifting ids in id order. `SweepCollectionDrift(ctx, db, logger, keyMode) (int, error)` calls the unexported `sweepCollectionDrift(ctx, db, logger, keyMode, pageSize int, reads sweepReads)` with 500 and the real queriers; `sweepReads` holds the sweep's reads (the page, the conferring products, the live provisions, the shapes, the displacements and the recent entries), so the database tests can set a page size and refuse a read. It pages, drops the rows whose mapping fails `MappingReachable` under the key, reads once per page, drops ids with a recent entry, and writes one entry per drifting id in one transaction per page; L5 when the count is above zero, L6 and the error on a failed read. The server's `displacementsBySubscription` (`internal/server/operator_enrollment.go:1827-1839`), which converts the displacement rows per subscription, moves to `entitlements.DisplacementsBySubscription`, which the server and the sweep both call, because `fulfillment` cannot call the server's.
|
||||
- [ ] 6.3 `internal/workflows/billing/activities.go`: `SweepCollectionDriftActivity` calls it with `a.keyMode`; `sweep_workflow.go`: `SweepScheduledChangesWorkflow` runs it after `SweepScheduledChangesActivity`, each activity's failure logged and the other still run, and the workflow returns the first failing activity's error after both have run, so the scheduled run records the failure; the activity is registered where the first one is.
|
||||
- [ ] 6.4 Tests:
|
||||
- `TestCollectionDrift` (`internal/fulfillment/collection_sweep_test.go`, no database), rows: `wanted, not recorded` (drifts); `wanted, recorded` (no); `not wanted, the marker recorded` (drifts); `paused, the marker recorded` (drifts); `not wanted, a foreign pause` (no); `displaced by a subscription` (no); and the drifting ids fed in two orders. Failure text: `collectionDrift(%s) = %v, want %v`.
|
||||
- `TestCollectionDrift` (`internal/fulfillment/collection_sweep_test.go`, no database), rows: `wanted, not recorded` (drifts); `wanted, recorded` (no); `not wanted, the marker recorded` (drifts); `paused, the marker recorded` (drifts); `not wanted, a foreign pause` (no); `displaced by a subscription` (no); `partly displaced, nothing recorded` (no); and the drifting ids fed in two orders. Failure text: `collectionDrift(%s) = %v, want %v`.
|
||||
- `TestSweepCollectionDrift_AsksForADisplacedSubscription` (database): a grant over a subscription with no recorded pause and no entry; one entry. Failure text: `the sweep wrote %d entries for the displaced subscription, want 1`.
|
||||
- `TestSweepCollectionDrift_SkipsASubscriptionWithAnEntry`, rows `a pending entry`, `a dead letter an hour old` and `a dead letter two days old` (its `updated_at` set by the test), each the same fixture with that entry; entries 0, 0, 1. Failure text: `with %s, the sweep wrote %d entries, want %d`.
|
||||
- `TestSweepCollectionDrift_ReadsOncePerPage`: twelve drifting subscriptions with a page size of five run the same statements per page, counted through the test kit's statement counter. Failure text: `the sweep ran %d statements for %d pages, want %d`.
|
||||
- `TestSweepCollectionDrift_AFailedReadFailsTheRun`: a querier refusing the items read; the error returned and L6 logged. Failure text: `a failed read = %v, want the error`.
|
||||
- `TestSweepCollectionDrift_ReadsOncePerPage`: twelve drifting subscriptions, run through `sweepCollectionDrift` with a page size of five; the sweep pages every mapped live subscription in the shared database, which other tests leave there, so the number of pages is not known in advance, and the test counts each per-page read by name through the test kit's statement counter (`Statements.ByName`) and compares it with the number of non-empty pages the page query returned. Failure text: `the sweep ran %d statements for %d pages, want %d`.
|
||||
- `TestSweepCollectionDrift_AFailedReadFailsTheRun`: `sweepCollectionDrift` with a `sweepReads` whose conferring-products read fails; the error returned and L6 logged. Failure text: `a failed read = %v, want the error`.
|
||||
- `TestSweepCollectionDrift_ASetLessItemRidesThePause`: a displaced tier and an item whose product has no entitlement set, recorded paused with the marker; the sweep writes no entry. Failure text: `the sweep wrote %d entries for a paused subscription with a set-less item, want 0`.
|
||||
- `TestSweepCollectionDrift_SkipsAnUnmappedSubscription`, rows `no mapping` (a displaced subscription with no Stripe mapping) and `a mapping for the other key mode`; for either, the sweep returns nil and writes no entry. Failure texts: `with %s, the sweep returned %v`; `with %s, the sweep wrote %d entries, want 0`.
|
||||
- `TestSweepScheduledChangesWorkflowRunsTheCollectionSweepAfterAFailure` (`internal/workflows/billing/sweep_workflow_test.go`, new, Temporal's `testsuite`) asserts both activities run and that a failure of the first still runs the second. Failure text: `the collection sweep did not run after a failed scheduled-change sweep`.
|
||||
- [ ] 6.5 Docs: `docs/models/payments-billing.md`, the Reconciler row, names the hourly drift sweep and the dead letter's one-day wait.
|
||||
- [ ] 6.6 Breaks:
|
||||
- the foreign pause counted as drift: caught by `TestCollectionDrift`, `want_new` `collectionDrift(not wanted, a foreign pause) =`;
|
||||
- `desired` narrowed to the missing products: caught by `TestCollectionDrift`, `want_new` `collectionDrift(partly displaced, nothing recorded) =`;
|
||||
- the set filter dropped from the generated `ListCurrentConferringProductsBySubscriptionIDs` constant: caught by `TestSweepCollectionDrift_ASetLessItemRidesThePause`, `want_new` `the sweep wrote 1 entries for a paused subscription with a set-less item`;
|
||||
- the dead-letter window dropped from `ListSubscriptionsWithRecentReconcileEntries`' generated constant (any dead letter skips): caught by `TestSweepCollectionDrift_SkipsASubscriptionWithAnEntry`, `want_new` `with a dead letter two days old, the sweep wrote 0 entries, want 1`;
|
||||
- the recent-entry filter removed: caught by the same, `want_new` `with a pending entry, the sweep wrote 1 entries, want 0`;
|
||||
- a per-subscription read inside the page loop: caught by `TestSweepCollectionDrift_ReadsOncePerPage`, `want_new` `the sweep ran`;
|
||||
@@ -155,7 +159,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
- [ ] 7.1 Query (design D7): `ListRecordedSubscriptionProductsOfPool` (billing or entitlements; subscription id, status, product id, summed quantity of current items for products with an entitlement set, for the pool's organization's subscriptions whose status is `active`, `trialing`, `past_due`, `unpaid` or `paused`, ordered by subscription id, product id); `ListSubscriptionsSupersededByProvisions(pool_id, provision_ids, subscription_ids)` (`internal/entitlements/queries/pool_provision_transitions.sql`; the listed subscriptions whose latest episode on a ladder of the pool, by `pool_provision_ladders` activation time and then id as `00034_subscription_displacements.sql:41-49` takes it, ended in a `core.supersession_pairs` row whose `successor_provision_id` is one of `provision_ids`, matched on the pool, the ladder, the ended provision and `effective_at = ended_at` as `00033_supersession_pairs.sql:27-43` pairs them; distinct subscription ids, ordered). `make sqlc-generate`.
|
||||
- [ ] 7.2 `internal/entitlements/subscription_delivery.go` (new): `DeliveredProduct{SubscriptionID, ProductID, ProvisionID string}` and `DeliverDisplacedSubscriptionsTx(ctx, tx, poolID, exceptSubscriptionID, reason string, endedProvisionIDs []string) ([]DeliveredProduct, error)`, as design D7 states, the subscriptions the ending plan superseded first (one `ListSubscriptionsSupersededByProvisions` read over the listed subscriptions, with `endedProvisionIDs`) and then the rest, each group in subscription id order, with `deliverInSavepoint` following `resumeInSavepoint` (`grant_resumption.go:146-171`), savepoint `subscription_delivery`, and the conferral at the summed quantity, as `conferOrBound` confers (`reconcile.go:938-972`). L4 for a refused conferral. When the read returns no row other than the excepted subscription, the step makes no further read, including the ordering read `ListSubscriptionsSupersededByProvisions`, and a subscription with no missing product makes no shape or displacement read (design D7). Reason constants `SubscriptionDeliveryRevocation = "subscription-delivery:revocation:"`, `SubscriptionDeliveryExpiration = "subscription-delivery:expiration:"`, `SubscriptionDeliverySubscription = "subscription-delivery:subscription:"`.
|
||||
- [ ] 7.3 `RevokeGrantTx` and `ExpireGrantTx` call it after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, only when the act ended a provision, with the reason, the grant id and the ids of the provisions it ended; `reconcileEnded` and the active branch after `endSurplusConferrals` call it when they ended one, with the ending subscription excepted. `docs/database-locks.md`, "Grant acts" and "Subscription reconcile", gain the step as the design's Locks section states.
|
||||
- [ ] 7.3 `RevokeGrantTx` and `ExpireGrantTx` call it after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, only when the act ended a provision, with the reason, the grant id and the ids of the provisions it ended; `reconcileEnded` calls it when it ended one, with the ending subscription excepted and the provisions `core.end_conferral` ended; the active branch calls it after `endSurplusConferrals` when that ended one, with the subscription excepted and the provisions `endSurplusConferrals` ended, which it returns (3.3). `docs/database-locks.md`, "Grant acts" and "Subscription reconcile", gain the step as the design's Locks section states.
|
||||
- [ ] 7.4 `internal/server/operator_tier_changes.go`, `humanizeTransitionReason`: the three prefixes, for actor `system`, read T1, T2 and T3.
|
||||
- [ ] 7.5 Tests (`internal/entitlements/subscription_delivery_db_test.go`):
|
||||
- `TestDeliverDisplaced_ARevocationDeliversTheSubscription`: the revocation's transaction confers Plus sourced by S, and no default is conferred. Failure texts: `after the revocation, S holds %v on the ladder, want Plus`; `the floor conferred the default over a subscription it should have delivered`.
|
||||
@@ -167,10 +171,10 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `TestDeliverDisplaced_AnActThatEndedNothingDeliversNothing`. Failure text: `a replayed revocation delivered %v`.
|
||||
- `TestDeliverDisplaced_SubscriptionsInIdOrder`: two subscriptions displaced on two ladders by one bundle grant, created in both orders; their conferrals' transition ids rise with the subscription ids. Failure text: `delivered %v, want subscription id order`.
|
||||
- `TestDeliverDisplaced_TheSubscriptionTheEndingHolderDisplacedGoesFirst`: S1, the lower id, is displaced by S2, and S2 is displaced by grant G; G is revoked. The ladder holds S2's product and S1 is left alone. Failure text: `after G ended, the ladder holds %v, want S2's product`.
|
||||
- `TestDeliverDisplaced_WaitsForThePoolRow`: a transaction holds the pool row; the revocation waits (`dbtest.AwaitLockWait`), and takes no subscription advisory lock (`pg_locks` shows none for S while it waits). Failure text: `the delivery took S's advisory lock`.
|
||||
- `TestDeliverDisplaced_WaitsForThePoolRow`: a transaction holds the pool row, and the revocation waits (`dbtest.AwaitLockWait`); a second transaction holds S's subscription advisory lock, with `SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, the key the reconcile takes as its trace shows it, and leaves the pool row free; once the first transaction releases the row, the revocation must commit. A revocation that took S's lock would wait on it, and its transaction's `lock_timeout` (set by `BeginMaterializing`, `internal/entitlements/tx.go:81-89`) would fail it. Failure text: `the delivery took S's advisory lock`.
|
||||
- `TestHumanizeTransitionReason` rows for the three prefixes. Failure text unchanged.
|
||||
- [ ] 7.6 Trace goldens, rewritten with `-update` and read: the three reconcile traces `reconcile_trace/canceled_to_default.golden`, `canceled_resumes_grant.golden` and `addon_removed.golden`, and the four sweep traces `sweep_trace/already_ended.golden`, `already_canceled.golden`, `due_cancellation.golden` and `lost_claim.golden`, whose acts all ended a provision, each gain the one statement `ListRecordedSubscriptionProductsOfPool` after the resumption's statements (after `ListResumableGrantsHeldBy` in `canceled_to_default` and the four sweep traces, after `RELEASE SAVEPOINT grant_resumption` in `canceled_resumes_grant`), or after `core.end_conferral` in `addon_removed`, the active branch's surplus end, which resumes nothing (before its `<materialize>` line): the step reads per live subscription, displaced or not, and its short-circuit (7.2) makes no further read when the fixture holds no other subscription. No server golden changes: no fixture under `internal/server/testdata/` revokes or expires a grant in an organization with a subscription, so no T1 to T3 row appears. Any case whose rows change is a stop.
|
||||
- [ ] 7.7 Docs: `docs/stripe.md`'s grant bullet says the tier is delivered in the act that ends the grant; `docs/models/plan-ladders-transitions.md` invariant 20 says the same; `docs/plan-management.md:164` ("the subscription delivers again at its next reconcile after the grant ends") is rewritten, because it is false after this section. `test/seed/member-console-demo/README.md:73-74` is rewritten, because the ledger demo's revocation and expiry now deliver Carlos's canceling subscription (7.9): line 73 (the **Grants** row) says that Carlos Member's organization carries only the default grant its pool was floored with, since no default is restored on it; line 74 (Carlos Member's Tier changes) reads "Started (Subscription delivers again after a grant expired)" and "Started (Subscription delivers again after a revocation)" where it reads "Started (Default restored after a grant expired)" and "Started (Default restored after a revocation)".
|
||||
- [ ] 7.6 Trace goldens, rewritten with `-update` and read: the three reconcile traces `reconcile_trace/canceled_to_default.golden`, `canceled_resumes_grant.golden` and `addon_removed.golden`, and the four sweep traces `sweep_trace/already_ended.golden`, `already_canceled.golden`, `due_cancellation.golden` and `lost_claim.golden`, whose acts all ended a provision, each gain the one statement `ListRecordedSubscriptionProductsOfPool` after the resumption's statements (after `ListResumableGrantsHeldBy` in `canceled_to_default` and the four sweep traces, after `RELEASE SAVEPOINT grant_resumption` in `canceled_resumes_grant`), or, in `addon_removed`, the active branch's surplus end, which resumes nothing, directly after `core.end_conferral` and before section 4's `ListLiveSubscriptionsOfPool`: the step reads per live subscription, displaced or not, and its short-circuit (7.2) makes no further read when the fixture holds no other subscription. No server golden changes: no fixture under `internal/server/testdata/` revokes or expires a grant in an organization with a subscription, so no T1 to T3 row appears. Any case whose rows change is a stop.
|
||||
- [ ] 7.7 Docs: `docs/stripe.md`'s grant bullet says the tier is delivered in the act that ends the grant; `docs/models/plan-ladders-transitions.md` invariant 20 says the same; `docs/plan-management.md:164` ("the subscription delivers again at its next reconcile after the grant ends") is rewritten, because it is false after this section. `test/seed/member-console-demo/README.md:73-74` is rewritten, because the ledger demo's revocation and expiry now deliver Carlos's canceling subscription (7.9): line 73 (the **Grants** row) says that Carlos Member's organization carries only the default grant its pool was floored with, since no default is restored on it; line 74 (Carlos Member's Tier changes) reads "Started (Subscription delivers again after a grant expired)" and "Started (Subscription delivers again after a revocation)" where it reads "Started (Default restored after a grant expired)" and "Started (Default restored after a revocation)". The README then agrees with the change's `member-console-demo-seed` delta ("The seed plays a ledger demo on Carlos's organization"), which states the same Tier changes and an Active tab that shows its empty state.
|
||||
- [ ] 7.8 Breaks:
|
||||
- the step after the floor (the call moved below `ReapplyDefaultsIfVacant` in `RevokeGrantTx`): caught by `TestDeliverDisplaced_ARevocationDeliversTheSubscription`, `want_new` `the floor conferred the default over a subscription`;
|
||||
- the step before the resumption: caught by `TestDeliverDisplaced_AResumableGrantGoesFirst`, `want_new` `with G0 resumable, S was delivered`;
|
||||
@@ -181,13 +185,14 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- the ended reconcile's call deleted: caught by `TestDeliverDisplaced_TheEndOfTheHoldingSubscription`, `want_new` `after S2's end, S1 holds`;
|
||||
- the subscriptions walked in reverse: caught by `TestDeliverDisplaced_SubscriptionsInIdOrder`, `want_new` `want subscription id order`;
|
||||
- the ordering by subscription id alone (the superseded-first sort removed): caught by `TestDeliverDisplaced_TheSubscriptionTheEndingHolderDisplacedGoesFirst`, `want_new` `after G ended, the ladder holds`;
|
||||
- the label of T1 changed: caught by `TestHumanizeTransitionReason`, `want_new` `humanizeTransitionReason("subscription-delivery:revocation:`.
|
||||
- the label of T1 changed: caught by `TestHumanizeTransitionReason`, `want_new` `humanizeTransitionReason("subscription-delivery:revocation:`;
|
||||
- an advisory lock on S taken before the conferral (`pg_advisory_xact_lock(hashtext(<S>)::bigint)` added to the delivery step ahead of `core.confer`): caught by `TestDeliverDisplaced_WaitsForThePoolRow`, `want_new` `the delivery took S's advisory lock`.
|
||||
- [ ] 7.9 `cd test && ./reset-app-db.sh --rebuild`, then `make screens`. The rebuild is needed because the demo snapshot's fingerprint covers the migrations, `internal/demoseed/*.go` and the clock pin (`test/reset-app-db.sh:120`), not `internal/entitlements`, and this section changes none of the three, so a plain reset would restore the snapshot section 4 built. The demo changes: Carlos's canceling subscription records `demo-plan`, a tier of the Demo Ladder, which the revoked grant and the expired grant are on, and holds no provision, so the revocation's delivery step confers `demo-plan` sourced by the subscription instead of restoring the default, and the expiry confers it again. Carlos Member's Tier changes then read T1 and T2 where they read "Default restored after a revocation" and "Default restored after a grant expired", the two restored default grants are not issued, and the subscription holds the ladder. The captures that change, each read and named in the commit: `operator-organization-detail` (it prefers Carlos Member, `test/e2e/screens/manifest.go:60-61`), in each state the utility captures, at both widths; `operator-grants`, at both widths, which loses the two restored default grants; and `operator-overview`'s recent activity, at both widths. Any other change is a stop. The demo seed's goldens under `internal/demoseed/testdata/` do not change: the canceling and grant steps' statement goldens run no ledger act, and `seed/twice.txt` records the steps' counts and the rows a second seed changes, which stay the same. Hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the Tier changes page with a row for each of T1 to T3, on the test stack with the kit's states loaded, are attached to the commit's review.
|
||||
|
||||
## 8. A subscription that pays at or above the grant takes the ladder
|
||||
|
||||
- [ ] 8.1 `internal/db/migrations/00037_displacement_holder_rank.sql` (design D8): the SPDX header; a header comment saying what the two columns add and why the function is dropped and created; `DROP FUNCTION core.subscription_displacements(UUID, UUID);` and the function as in `00034` with `holder_product_id UUID` and `holder_rank INTEGER` after its five columns, selecting `h.product_id` and `t.rank` through `LEFT JOIN core.plan_ladder_tiers t ON t.plan_ladder_id = h.plan_ladder_id AND t.product_id = h.product_id`; the `GRANT EXECUTE`. Down drops it and restores `00034`'s body and grant.
|
||||
- [ ] 8.2 The three queries name seven aliases and select `d.holder_product_id::uuid AS holder_product_id` and `d.holder_rank::int AS holder_rank` after `holder_source`; their comments say the rank decides the exception. `make sqlc-generate`. `Displacement` gains `HolderProductID`, `HolderRank` and `HolderRanked`; `DisplacementsFromRows` and the server's `displacementsBySubscription` fill them.
|
||||
- [ ] 8.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:
|
||||
- `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.
|
||||
@@ -213,14 +218,14 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
- [ ] 9.1 `internal/billing/queries/subscriptions.sql`: `ListSubscriptionRungsByOrg` as design D9 states, with the mirror's behavior and marker, the scheduled cancellation and switch, and each item's price facts; `ListLadderPositionsByPool` (`internal/entitlements/queries/pool_provision_ladders.sql:212-243`) gains `default_sourced`, so that `GrantHolds` is false when the default holds the rung (design D9). `make sqlc-generate`.
|
||||
- [ ] 9.2 `internal/plans/offer.go`: `Paying` with every field of design D9, and `Position.Paying`; reasons `PaidHere` ("a subscription pays for the target on this ladder without holding it") and `PaysOnLadder` ("a subscription pays on the ladder without holding it"); rule 3a ahead of rule 3 in `Offer`, applied when `Paying` is set and the held position is not subscription-backed (`!pos.Subscribed`), with the rules' doc comment renumbered or the rule named 3a there. In this commit its item 1 (the paying product) answers none, reason `PaidHere`, and section 12 adds Resume; its item 2 (a grant holds, the paying subscription is not suspended, the target ranks at or above the held rung and above the paying product) answers none, reason `PaysOnLadder`, and section 11 turns it into Switch; the rank test against the paying product is question 3's answer (design D9). `Across` is unchanged: rule 3a answers no Checkout on any paying ladder, so a product with such a ladder already combines to none (`checkoutOffer`'s existing `Across` call refuses it, `internal/server/billing.go:284-290`).
|
||||
- [ ] 9.3 `internal/server/plan_offer.go`: `positionLoader` reads `ListSubscriptionRungsByOrg` once per request, cached as `predictions` is (`positions()` is not cached); `payingByLadder(rows, positions) map[string]plans.Paying`, reading no row, sets every field as design D9 states, `GrantHolds` being the held position's `grant_id` set and `default_sourced` false; the choice of a ladder's paying subscription is one pure function in `internal/entitlements` beside `PositionsByLadder`, which `payingByLadder` and `resolveSubscriptionOnLadder` (10.2) both call; `onLadder` sets `pos.Paying`. `switchOffer` maps a refusal with `Paying` suspended to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and after that a refusal with `Paying` set and not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on (design D9); its doc comment states the order. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence on such a ladder.
|
||||
- [ ] 9.3 `internal/server/plan_offer.go`: `positionLoader` reads `ListSubscriptionRungsByOrg` once per request, cached as `predictions` is (`positions()` is not cached); `payingByLadder(rows, positions) map[string]plans.Paying`, reading no row, sets every field as design D9 states, `GrantHolds` being the held position's `grant_id` set and `default_sourced` false; the choice of a ladder's paying subscription is one pure function in `internal/entitlements` beside `PositionsByLadder`, which `payingByLadder` and `resolveSubscriptionOnLadder` (10.2) both call; `onLadder` sets `pos.Paying`. `switchOffer`, under rule 3a's own condition (`pos.Paying != nil && !pos.Subscribed`), maps a refusal whose `Paying` is suspended to `ErrSubscriptionSuspended`, or `ErrSubscriptionPaused` when `Paying.Paused`, and after that a refusal whose `Paying` is not suspended to `errPlanNotOffered`, both ahead of its `!pos.Subscribed` case, which then answers only a ladder no subscription pays on, so a subscription that holds the rung over a paying one keeps its own refusals (design D9); its doc comment states the order and the condition. The switch and its preview both ask `switchOffer`, so both answer the unavailable-plan sentence on such a ladder.
|
||||
- [ ] 9.4 Tests:
|
||||
- `TestOffer` rows (`internal/plans/offer_test.go`): `the paid tier` (none, PaidHere); `a tier between a lower grant and the paid tier` (none, PaysOnLadder); `a tier below the grant with a paying subscription` (none, PaysOnLadder); `a past-due paying subscription` (none for every target); `a paused paying subscription` (none); `a bundle's vacated ladder` (none, PaysOnLadder, no Checkout); `the default holds the rung` (`GrantHolds` false: no Resume and no switch for any target); `a subscription that holds the rung over another one` (rule 3a does not apply: the held subscription's target above it is a switch, with no `PaysOnLadder` reason); and the existing `a higher tier over a grant is Checkout` row, with no `Paying`, unchanged. Failure text unchanged.
|
||||
- `TestAcross` passes unedited: it takes moves, not positions, and rule 3a already answers no Checkout.
|
||||
- `TestPayingByLadder` (`internal/server/plan_offer_test.go`, no database), rows: `the holding subscription` (never paying); `two subscriptions on one ladder` (the lower id); `a bundle` (both ladders, `OtherLadders` set on each); `the default holds the rung` (`GrantHolds` false); `the console's pause recorded` (`ConsolePaused`); `a pause made in the Dashboard` (the behavior without the marker: `ConsolePaused` false); `a marker with no pause` (`ConsolePaused` false); `a cancellation scheduled` and `a downgrade scheduled` (`MoveScheduled`); `paused` (`Suspended` and `Paused`). Failure text: `payingByLadder(%s) = %v, want %v`.
|
||||
- `TestCheckoutRefusesALadderASubscriptionPaysFor` (`internal/server/billing_checkout_offer_db_test.go`), rows `above the grant` and `the vacated ladder of a bundle`: 422 with "That plan is no longer available. Refresh the page and choose a current plan.", no Stripe call. Failure text: `%s: checkout answered %d, want 422, with %d Stripe calls`.
|
||||
- `TestCheckoutRefusesATierBelowOrAtAGrantedRung` and the existing Checkout tests pass unedited; `TestCheckoutAboveAGrantWithNoSubscription` asserts the session is still created. Failure text: `checkout above a grant with no subscription answered %d`.
|
||||
- `TestMemberPlansGolden`: a new state `paid-plus-under-granted-pro` (the kit's `Subscribe(o, plus)`, then `Issue(o, pro)`, then `PauseCollection`), goldens `internal/server/testdata/member_plans/paid-plus-under-granted-pro.html` and `.json` written with `-update` and read: no card offers Checkout and none offers a switch yet. Plus is a tier of Wiki and Duo, so Duo's Plus card draws no line and no control, and Duo Max offers no Checkout. The card's own state comes in section 10 and the switch in section 11, whose goldens change again. No existing state's `.html` or `.json` changes, because no existing state has a subscription that pays on a ladder without holding it.
|
||||
- `TestMemberPlansGolden`: a new state `paid-plus-under-granted-pro` (the kit's `Subscribe(o, plus)`, then `Issue(o, pro)`, then `PauseCollection`), goldens `internal/server/testdata/member_plans/paid-plus-under-granted-pro.html` and `.json` written with `-update` and read: no card offers Checkout and none offers a switch yet. Plus is a tier of Wiki and Duo, so Duo's Plus card draws its price and no control, and Duo Max offers no Checkout. The card's own state comes in section 10 and the switch in section 11, whose goldens change again. No existing state's `.html` or `.json` changes, because no existing state has a subscription that pays on a ladder without holding it.
|
||||
- `TestProductsPageReadsPayingOnce` (`internal/server/member_plans_read_count_db_test.go`, new, counting statements as `TestOperatorPagesReadAFixedNumberOfTimes` does): the page runs one statement more than before, for any number of ladders; its fixture holds no ladder a grant holds against a paying subscription. Failure text: `the Products page ran %d statements, want %d`.
|
||||
- [ ] 9.5 Breaks:
|
||||
- rule 3a applied when the held position is subscription-backed (the `!pos.Subscribed` test dropped): caught by `TestOffer`, `want_new` `Offer(a subscription that holds the rung over another one) =`;
|
||||
@@ -230,19 +235,19 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `ConsolePaused` read from the behavior alone: caught by the same, `want_new` `payingByLadder(a pause made in the Dashboard) =`;
|
||||
- `MoveScheduled` read from `cancel_at_period_end` alone: caught by the same, `want_new` `payingByLadder(a downgrade scheduled) =`;
|
||||
- the loader reading per ladder: caught by the read-count test, `want_new` `the Products page ran`.
|
||||
- Unseen by any test of the section, named in the commit message: `switchOffer`'s paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted), because no section-9 test posts a switch on a paying ladder; 11.6 records it, caught by `TestPostSwitchFromAPausedSubscription`.
|
||||
- Unseen by any test of the section, named in the commit message, because no section-9 test posts a switch on a paying ladder: `switchOffer`'s paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted); the suspended mapping deleted; the `Paying.Paused` test dropped; and the `!pos.Subscribed` test dropped from the mappings' condition. 11.6 records each, caught by `TestPostSwitchFromAPausedSubscription`.
|
||||
- [ ] 9.6 `make screens`: no demo state has a paying subscription, so no capture changes; a change is read and named.
|
||||
- [ ] 9.7 Docs: invariant 19 of `docs/models/plan-ladders-transitions.md` ("from a grant-held rung the only move offered is up, through Checkout") says that on a ladder a subscription pays for without holding, no tier is sold through Checkout, the switch of the paying subscription is offered at or above the grant and above the paid tier, and the paid tier resumes under a lower grant (sections 11 and 12 make both live); invariant 12 of `docs/models/payments-billing.md` (`:65`) says that Checkout refuses a ladder a subscription pays for whether or not the subscription holds it.
|
||||
|
||||
## 10. The paid plan's card, Cancel plan, Keep plan and Pay invoice (#269)
|
||||
|
||||
- [ ] 10.1 Sandbox check, before the code (design, What is unverified): on a Stripe sandbox test clock at the console's pinned API version, with the console's restricted test key, a subscription paused with `behavior=void` and the marker, set to cancel at the period end and then kept (`cancel_at_period_end=false`): Stripe accepts it, creates no invoice, and the pause and the marker stay. The result is recorded in the commit message; a refusal is a stop and goes to the maintainer.
|
||||
- [ ] 10.2 `internal/fulfillment/plan_change.go` (design D11): `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`, with the paying fallback through `ListSubscriptionRungsByOrg`, `holdsLadder`, and the status-derived suspension; every caller named in design D11 calls it. Its doc comment says which subscription it finds when no subscription backs the position. It chooses the paying subscription through the pure function 9.3 names, so the resolver and `payingByLadder` state the rule once.
|
||||
- [ ] 10.3 `internal/server/member_plans.go` (design D10): `buildTier`, for the card whose product is the ladder's `Paying.ProductID` on a ladder a grant holds, calls `setPaidUnderGrant(tier, ladderID, paying, granted)`, which sets `PaidUnderGrant`, `GrantedName`, `CollectionPaused`, the price line's facts (the subscription's own price from the paying row), `CanCancel`, `CanKeep`, `MovesTo`, `MovesOn` and `EndsOn` by D10's table, and `PaysInvoice` for `past_due` or `unpaid`; the current card's `setCurrent` defers to it when the current product is the paying product, and `buildTier` draws the paid card even when its product is not a public plan, as it draws the current and the held rungs (design D10). `setCancelBodies` gives the card's confirmation Copy M2 under a grant of another tier and M9 under a grant of the subscription's own tier, each followed by M7's sentence when the payment is due. `plansOfferPaidMove` (`:589-601`) counts a card with `PaidUnderGrant` and `PaysInvoice()` as well as a `current` card, so the billing facts show for the paid card's Pay invoice. The Note of Keep plan's action trigger (`internal/server/action_triggers.go:94-95`, "the current plan's control, …") is updated, because Keep plan is now drawn on the paid card. The comment at `:750-758` no longer says a grant-held tier has no billing.
|
||||
- [ ] 10.2 `internal/fulfillment/plan_change.go` (design D11): `resolveLadderSubscription` becomes `resolveSubscriptionOnLadder`, with the paying fallback through `ListSubscriptionRungsByOrg`, `holdsLadder`, and the status-derived suspension; every caller named in design D11 calls it. Its doc comment says which subscription it finds when no subscription backs the position. It chooses the paying subscription through the pure function 9.3 names, so the resolver and `payingByLadder` state the rule once. The fallback's `currentProductID` is the paying item's product, not the held position's, because `SwitchPlan` compares the target with it (`plan_change.go:214`, `:245`), as `PreviewSwitch` does (`:560`), and the resolver finds the item by it (`:822`).
|
||||
- [ ] 10.3 `internal/server/member_plans.go` (design D10): `buildTier`, for the card whose product is the ladder's `Paying.ProductID` on a ladder a grant holds, calls `setPaidUnderGrant(tier, ladderID, paying, granted)`, which sets `PaidUnderGrant`, `GrantedName`, `CollectionPaused`, the price line's facts (the subscription's own price from the paying row), `CanCancel`, `CanKeep`, `MovesTo`, `MovesOn` and `EndsOn` by D10's table, and `PaysInvoice` for `past_due` or `unpaid`; the current card's `setCurrent` defers to it when the current product is the paying product, and `buildTier` draws the paid card even when its product is not a public plan, as it draws the current and the held rungs (design D10). `buildLadder` sets the ladder's `CancelsOn` from the paying row (`cancel_at_period_end` with `current_period_end`, or the scheduled cancellation's date) on a ladder a grant holds; `pos.CancelScheduled` stays unset. `setCancelBodies` gives the card's confirmation Copy M2 under a grant of another tier and M9 under a grant of the subscription's own tier, each followed by M7's sentence when the payment is due. `plansOfferPaidMove` (`:589-601`) counts a card with `PaidUnderGrant` and `PaysInvoice()` as well as a `current` card, so the billing facts show for the paid card's Pay invoice. The Note of Keep plan's action trigger (`internal/server/action_triggers.go:94-95`, "the current plan's control, …") is updated, because Keep plan is now drawn on the paid card. The comment at `:750-758` no longer says a grant-held tier has no billing.
|
||||
- [ ] 10.4 `internal/embeds/templates/partials/member_plans.html`: the price line reads M8 when `PaidUnderGrant`, `CollectionPaused` and a downgrade is scheduled, otherwise M0 or M1 when `PaidUnderGrant` and `CollectionPaused`, ahead of the existing branches; a scheduled cancellation keeps M0, its date on the ladder heading's existing badge; M1 draws no suspension line; the controls block draws Pay invoice, Keep plan and Cancel plan for a paid-under-grant card as for the current card. The template's comment states the card's states.
|
||||
- [ ] 10.5 `internal/server/member_hosted_invoice.go` (design D10): `planPosition` falls back to the paying subscription; `unpaidInvoicePage` lists the paying subscription's open invoices (`invoice.List` with `Subscription` and `Status: "open"`, limit 1) and redirects to the first one's hosted page. `internal/stripetest/mock.go` answers `GET /v1/invoices` from its existing `Invoices` map (keyed by invoice id, `mock.go:63-69`), listing the invoices whose subscription and status match the `subscription` and `status` parameters, with a doc comment. `internal/stripetest/testdata/routes.golden`, the row `the invoice list` (`:125-126`, which today records `error: stripetest: unexpected path /v1/invoices`), then records the list's answer; it is rewritten with `-update` and read, and no other row changes.
|
||||
- [ ] 10.5 `internal/server/member_hosted_invoice.go` (design D10): `planPosition` falls back to the paying subscription; `unpaidInvoicePage` lists the paying subscription's open invoices (`invoice.List` with `Subscription` and `Status: "open"`, limit 1) and redirects to the first one's hosted page. `internal/stripetest/mock.go` answers `GET /v1/invoices` from its existing `Invoices` map (keyed by invoice id, `mock.go:63-69`), listing the invoices whose subscription and status match the `subscription` and `status` parameters, newest first by `Created` and then by id, because the map has no order, with a doc comment. `internal/stripetest/testdata/routes.golden`, the row `the invoice list` (`:125-126`, which today records `error: stripetest: unexpected path /v1/invoices`), then records the list's answer; it is rewritten with `-update` and read, and no other row changes.
|
||||
- [ ] 10.6 Tests:
|
||||
- `TestMemberPlansGolden`: states `paid-plus-under-granted-pro` (section 9's, now with M0 and Cancel plan), `paid-plus-under-granted-pro-past-due` (M1, Pay invoice then Cancel plan, no suspension line), `paid-plus-under-granted-pro-unconfirmed` (no `PauseCollection`: the existing renews line), `paid-plus-under-granted-pro-cancellation-scheduled` (M0, Keep plan, and the heading's "cancels on" badge), `paid-plus-under-granted-pro-downgrade-scheduled` (the kit's `ScheduleDowngrade` to Basic before `Issue(o, pro)`: M8, Keep plan then Cancel plan), `paid-plus-paused-under-granted-pro` (status `paused`: M4, no control), and `granted-plus-own-tier` (`Subscribe(o, plus)`, `Issue(o, plus)`, `PauseCollection`: a grant of Plus over the Plus subscription, and the current card carries M0, "Paused while Plus is granted"); each state's `.html` and `.json` under `internal/server/testdata/member_plans/` written with `-update` and read, and `paid-plus-under-granted-pro.html` and `.json` rewritten. Plus is a tier of Wiki and Duo, so in every `paid-plus-*` state Duo's Plus card draws no line and no control, and Duo Max offers no Checkout. No golden shows the billing facts line: `TestMemberPlansGolden` empties `BillingFacts` before it renders (`member_plans_golden_db_test.go:303`).
|
||||
- `TestMemberPlansGolden`: states `paid-plus-under-granted-pro` (section 9's, now with M0 and Cancel plan), `paid-plus-under-granted-pro-past-due` (M1, Pay invoice then Cancel plan, no suspension line), `paid-plus-under-granted-pro-unconfirmed` (no `PauseCollection`: the existing renews line), `paid-plus-under-granted-pro-cancellation-scheduled` (M0, Keep plan, and the heading's "cancels on" badge), `paid-plus-under-granted-pro-downgrade-scheduled` (the kit's `ScheduleDowngrade` to Basic before `Issue(o, pro)`: M8, Keep plan then Cancel plan), `paid-plus-paused-under-granted-pro` (status `paused`: M4, no control), and `granted-plus-own-tier` (`Subscribe(o, plus)`, `Issue(o, plus)`, `PauseCollection`: a grant of Plus over the Plus subscription, and the current card carries M0, "Paused while Plus is granted"); each state's `.html` and `.json` under `internal/server/testdata/member_plans/` written with `-update` and read, and `paid-plus-under-granted-pro.html` and `.json` rewritten. Plus is a tier of Wiki and Duo, so in every `paid-plus-*` state Duo's Plus card draws its price and no control, and Duo Max offers no Checkout. No golden shows the billing facts line: `TestMemberPlansGolden` empties `BillingFacts` before it renders (`member_plans_golden_db_test.go:303`).
|
||||
- `TestPlansOfferPaidMoveGate` (`internal/server/billing_facts_render_test.go:128`) gains the case `paidDue`, a paid-under-grant card whose payment is due and whose relation is not `current`, which earns the line. Failure text: `a paid card whose payment is due does not earn the line`.
|
||||
- `TestMemberPlansGolden`: a state `paid-retired-plus-under-granted-pro`, built in a world of its own so that the fixture's shared Plus is never retired: `w.Retire` sets `is_active = false` on the one product row (`internal/testkit/world/plans.go:191-203`), and `buildTier` skips an unlisted tier unless it is current or held (`internal/server/member_plans.go:399-402`), so retiring the shared Plus would drop its card from every other state where Plus is neither current nor held. The test makes a second `world.New` with its own Wiki ladder (Basic, Plus, Pro) and its own organization, its ids named through a normalizer as the first world's are, runs `Subscribe(o, plus)`, `Issue(o, pro)` and `PauseCollection`, then retires that world's Plus, and renders it as the subtest `paid-retired-plus-under-granted-pro`, keeping its ladders apart by that world's suffix as the page filter does (`member_plans_golden_db_test.go:296-301`). Plus's card is drawn with M0 and Cancel plan; `paid-retired-plus-under-granted-pro.html` and `.json` written with `-update` and read.
|
||||
- The `.json` of each of the 22 states that predate section 9 (every `.json` under `internal/server/testdata/member_plans/` at section 9's commit but `paid-plus-under-granted-pro.json`) is rewritten with `-update` and read; each gains only `PaidUnderGrant`, `GrantedName` and `CollectionPaused` at their zero values, and none of those states' `.html` changes; any other diff is a stop.
|
||||
@@ -250,7 +255,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `TestCancelAPausedSubscription` (`internal/fulfillment/plan_change_paid_under_grant_test.go`): `CancelSubscription` at the period end sends `cancel_at_period_end=true` and no `pause_collection`, records the scheduled cancellation and reconciles. The form and the function's error are asserted in one check. Failure text: `cancel call form = %v (error %v), want cancel_at_period_end and no pause change`.
|
||||
- `TestKeepAPausedSubscription`: `KeepCurrentPlan` clears the flag, supersedes the row, and sends no `pause_collection`. Failure text: `keep call form = %v`.
|
||||
- `TestAPastDuePayingSubscriptionIsNotCancelledImmediately`: the immediate cancellation is refused with `ErrImmediateCancelSuspended` before any Stripe call. Failure text: `an immediate cancellation of a past-due paying subscription = %v`.
|
||||
- `TestPlanUnpaidInvoiceForAPausedPlan` (`internal/server/member_hosted_invoice_db_test.go`), rows: `past due with an open invoice` (303 to the mock's hosted URL); `active` (303 to `/billing`, no Stripe call); `no open invoice` (303 to `/billing`); `another organization's ladder` (404). Failure text: `%s: answered %d %q, want %d %q`.
|
||||
- `TestPlanUnpaidInvoiceForAPausedPlan` (`internal/server/member_hosted_invoice_db_test.go`), rows: `past due with an open invoice`, its `latest_invoice` a void renewal (303 to the open invoice's hosted URL in the mock); `active`, the mock holding an open invoice for that subscription (303 to `/billing`, no Stripe call); `no open invoice` (303 to `/billing`); `another organization's ladder` (404). Failure text: `%s: answered %d %q, want %d %q`.
|
||||
- `TestCancelBodyOnThePaidCard`, rows: `a grant of another tier` (M2 with the period end); `a grant of the subscription's own tier` (M9); `a grant of another tier, payment due` (M7 over M2: "Plus ends on Jan 15, 2099; Pro stays granted. The unpaid invoice stays due."); `the own tier, payment due` (M7 over M9). Failure text: `%s: cancel body = %q, want %q`.
|
||||
- [ ] 10.7 Docs: `docs/stripe.md`'s grant bullet names the paid plan's card, Cancel plan at the period end and Pay invoice; `docs/plan-management.md` says what the member sees.
|
||||
- [ ] 10.8 Breaks:
|
||||
@@ -265,7 +270,8 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- M7's sentence dropped: caught by the same, `want_new` `a grant of another tier, payment due: cancel body =`;
|
||||
- the paid card's Pay invoice not counted in `plansOfferPaidMove`: caught by `TestPlansOfferPaidMoveGate`, `want_new` `a paid card whose payment is due does not earn the line`;
|
||||
- the paid card skipped when its product is not listed: caught by `TestMemberPlansGolden/paid-retired-plus-under-granted-pro`, `want_new` `testdata/member_plans/paid-retired-plus-under-granted-pro.html differs from what the code produced`;
|
||||
- M8 not drawn (a scheduled downgrade reads M0): caught by `TestPaidPlanCardUnderAGrant`, `want_new` `downgrade scheduled: price line`, and by `TestMemberPlansGolden/paid-plus-under-granted-pro-downgrade-scheduled`, `want_new` `testdata/member_plans/paid-plus-under-granted-pro-downgrade-scheduled.html differs from what the code produced`.
|
||||
- M8 not drawn (a scheduled downgrade reads M0): caught by `TestPaidPlanCardUnderAGrant`, `want_new` `downgrade scheduled: price line`, and by `TestMemberPlansGolden/paid-plus-under-granted-pro-downgrade-scheduled`, `want_new` `testdata/member_plans/paid-plus-under-granted-pro-downgrade-scheduled.html differs from what the code produced`;
|
||||
- the ladder heading's "cancels on" badge not drawn (`buildLadder` not setting `CancelsOn` from the paying row): caught by `TestMemberPlansGolden/paid-plus-under-granted-pro-cancellation-scheduled`, `want_new` `testdata/member_plans/paid-plus-under-granted-pro-cancellation-scheduled.html differs from what the code produced`.
|
||||
- [ ] 10.9 `make screens`: no demo state reaches the paid card; hand captures at 1280 desktop width and 390 mobile width (emulated, `innerWidth` checked) of the Products page in the states `paid-plus-under-granted-pro`, its past-due form, its cancellation-scheduled form (Keep plan and the badge), its downgrade-scheduled form (M8), its unconfirmed form, `granted-plus-own-tier` (a grant of the subscription's own tier), and the cancellation's confirmation in its M2 and M9 forms, on the test stack with the kit's states loaded, are attached to the commit's review.
|
||||
|
||||
## 11. The switch of a paused subscription (#278)
|
||||
@@ -284,7 +290,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `TestPreviewSwitchOfAPausedSubscription`, in the form 11.1(c) found. Unavailable (Stripe refused the preview, or its figure differs from the update's charge): `PreviewSwitch` of a subscription carrying the console's pause returns the unavailable preview. Equal: it returns the mock's figure. Failure text: `paused preview = %+v, want unavailable` (equal form: `paused preview = %+v, want the mock's figure`).
|
||||
- `TestOffer` rows (`internal/plans/offer_test.go`): `a tier above a grant that displaced a subscription` (a switch, enabled, relation Upgrade); `the granted tier over a paying subscription` (a switch, enabled, relation Upgrade); `a tier above the paid tier over a lower grant` (a switch, enabled, relation Upgrade); `the granted tier below the paid tier` (none, reason `Current`). Failure text unchanged.
|
||||
- `TestPlanMoveMessageStatesTheTiming` (`internal/server/plan_move_message_test.go`) row `replaces the grant` equals M3's whole text with an amount, and its fallback row with the prorated-difference sentence. Failure text unchanged.
|
||||
- `TestPostSwitchFromAPausedSubscription` (`internal/server/member_switch_offer_db_test.go`): the posted switch to Max answers the submitted message, and to Plus answers the unavailable-plan sentence. Failure text: `%s: answered %q, want %q`.
|
||||
- `TestPostSwitchFromAPausedSubscription` (`internal/server/member_switch_offer_db_test.go`) runs three named fixtures. `a Pro grant over Plus`, rows: `Max` (answers the submitted message); `Plus`, the paid tier (the unavailable-plan sentence); `past due` (`Suspend(sub, "past_due")`, Max posted: "Pay the unpaid invoice before changing this plan."); `paused` (`Suspend(sub, "paused")`, Max posted: "A paused plan cannot be changed."). `a Basic grant over Pro`, rows: `Max` (answers the submitted message); `Plus`, between (the unavailable-plan sentence); `Basic`, the granted tier below the paid tier (the unavailable-plan sentence). `held by another subscription` (the kit's second `Subscribe` on the ladder holds the rung over the paying subscription, as `TestPostResume`'s row of that name builds it, 12.7), row: `the holder's current tier` ("You're already on that plan."). Failure text: `%s: answered %q, want %q`.
|
||||
- `TestMemberPlansGolden`, six states rewritten with `-update` and read, the `.html` and `.json` of each under `internal/server/testdata/member_plans/`, because rule 3a item 2 has no condition on `ConsolePaused` or `MoveScheduled`: `paid-plus-under-granted-pro`, `paid-plus-under-granted-pro-unconfirmed`, `paid-plus-under-granted-pro-cancellation-scheduled`, `paid-plus-under-granted-pro-downgrade-scheduled` and `paid-retired-plus-under-granted-pro`, in each of which Pro's current card draws "Upgrade" and Standard ranks below the granted Pro and draws nothing (the retired state's own ladder, Basic, Plus and Pro, has no Standard); and `granted-plus-own-tier`, in which Standard's and Pro's cards on Wiki, and Duo Max's card on Duo, draw "Upgrade", because the fixture's Plus grant holds both ladders. Each named card's `.json` gains the switch's move fields. `paid-plus-under-granted-pro-past-due` and `paid-plus-paused-under-granted-pro` do not change, because their subscription is suspended.
|
||||
- No other state's `.html` or `.json` changes: `TierViewModel` already carries every field `setMove` sets (`internal/server/member_plans.go:108-139`), so the current card's move adds no field; any other diff is a stop.
|
||||
- `TestProductsPageReadsPayingOnce` passes unedited: its fixture holds no ladder a grant holds against a paying subscription, so 11.3's read of the current card's default price, `computePriceReadiness`'s statements once per such ladder (`internal/server/plan_offer.go:238-261`), adds nothing to its count.
|
||||
@@ -301,7 +307,10 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- the suspension test dropped: caught by `TestOffer`, `want_new` `Offer(a past-due paying subscription) =`;
|
||||
- `replacesGrant` ignored: caught by `TestPlanMoveMessageStatesTheTiming`, `want_new` `replaces the grant`;
|
||||
- section 8's exception removed for the switch's product: caught by `TestSwitchAPausedSubscription_OneUpdate`, `want_new` `after the switch, the ladder holds`;
|
||||
- a paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted from `switchOffer`, 9.3): caught by `TestPostSwitchFromAPausedSubscription`, `want_new` `answered "There's no active subscription`.
|
||||
- a paying refusal left to `!pos.Subscribed` (the `Paying`-set, not-suspended case deleted from `switchOffer`, 9.3): caught by `TestPostSwitchFromAPausedSubscription`, `want_new` `answered "There's no active subscription`;
|
||||
- the suspended mapping deleted from `switchOffer` (a suspended `Paying` misses the not-suspended case and reaches `!pos.Subscribed`): caught by the `past due` row, `want_new` `past due: answered "There's no active subscription`;
|
||||
- the `Paying.Paused` test dropped from `switchOffer`: caught by the `paused` row, `want_new` `paused: answered "Pay the unpaid`;
|
||||
- the `!pos.Subscribed` test dropped from the mappings' condition: caught by the `held by another subscription` fixture's row, `want_new` `answered "That plan is no longer available`.
|
||||
- [ ] 11.7 `make screens`: no demo state reaches the switch; hand captures at both widths of the switch's confirmation from the paused subscription (M3) are attached to the commit's review.
|
||||
|
||||
## 12. Resume plan when the grant ranks below the paid tier
|
||||
@@ -318,7 +327,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `TestResumeSubscription_Refusals`, rows through `checkResumeRefusal`: `no pause recorded`; `a pause made in the Dashboard` (`ForeignPause`); `a marker with no pause`; `a grant of the paid tier`; `a grant above the paid tier`; `held by another subscription`; `a cancellation scheduled` (`CancelAtPeriodEnd`); `a downgrade scheduled` (`ScheduleDowngrade`); `past due` (`Suspend`); `paused` (`Suspend`); `canceled` (`EndSubscription`); `a bundle`; `the product drafted` (`Draft`). Each answers its row's refusal and writes no position, no transition and no outbox entry. Failure text: `%s: resume = %v, want %v, with nothing written`.
|
||||
- `TestResumeSubscription_OverABundleGrantEndsItOnItsOtherLadder`: the grant's product is a tier of two ladders; after the resume the grant's other ladder holds nothing and no default is conferred there (F60). Failure text: `after the resume over a bundle grant, the other ladder holds %v, want nothing`.
|
||||
- `TestResumeSubscription_ASecondSubmitConfersOnce`: two calls in sequence; the second answers `ErrSubscriptionHoldsLadder`, and the ladder has one upgrade transition by the subscription. Failure text: `a second resume = %v with %d transitions, want the holds refusal and 1`.
|
||||
- `TestResumeSubscription_AnEndingActFirst`, rows `revocation` and `expiry`: a transaction runs `RevokeGrantTx` or `ExpireGrantTx` and stays open; the resume waits for the pool row (`dbtest.AwaitLockWait`), and `pg_locks` shows no advisory lock for the subscription while it waits; after the commit, which delivers the subscription (section 7), the resume answers `ErrSubscriptionHoldsLadder` and writes nothing. Failure texts: `after a concurrent %s, resume = %v, want the holds refusal`; `the resume took the subscription's advisory lock`.
|
||||
- `TestResumeSubscription_AnEndingActFirst`, rows `revocation` and `expiry`: a transaction runs `RevokeGrantTx` or `ExpireGrantTx` and stays open; the resume waits for the pool row (`dbtest.AwaitLockWait`); a second transaction holds the subscription's advisory lock, with `SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, the key the reconcile takes as its trace shows it, and leaves the pool row free; after the first transaction's commit, which delivers the subscription (section 7), the resume must answer `ErrSubscriptionHoldsLadder` and write nothing. A resume that took the subscription's lock would wait on it, and its transaction's `lock_timeout` (set by `BeginMaterializing`, `internal/entitlements/tx.go:81-89`) would fail it, which the test reports with the advisory-lock failure text. Failure texts: `after a concurrent %s, resume = %v, want the holds refusal`; `the resume took the subscription's advisory lock`.
|
||||
- `TestResumeSubscription_AMarkedGrantResumesWhenTheSubscriptionEnds`: the grant marked to resume; the resume; then the subscription ends (`EndSubscription` and its reconcile); the ladder holds the grant's Basic again. Failure text: `after the subscription ended, the ladder holds %v, want the marked grant's Basic`.
|
||||
- `TestResumePlan_MakesNoStripeCall` (`internal/fulfillment/plan_change_paid_under_grant_test.go`): `ResumePlan` sends no request to the Stripe mock; `ApplySubscriptionCollection` on the entry it wrote then sends one update whose form holds `pause_collection=` and `metadata[member_console_collection]=` and no `items`. Failure texts: `resume sent %v to Stripe, want nothing`; `the clear after the resume = %v, want the clear alone`.
|
||||
- `TestResumePlan_RefusesAnUnreachableMapping`: the subscription mapped for the other key mode; `ErrPriceUnreachable`, nothing written. Failure text: `resume over an unreachable mapping = %v, want ErrPriceUnreachable`.
|
||||
@@ -347,6 +356,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- the act's holds test dropped: caught by `TestResumeSubscription_ASecondSubmitConfersOnce`, `want_new` `a second resume =`;
|
||||
- the act's request dropped: caught by `TestResumeSubscription_TakesTheLadderFromTheGrant`, `want_new` `the resume wrote entries for`;
|
||||
- the act's reads moved above `LockPools`: caught by `TestResumeSubscription_AnEndingActFirst`, `want_new` `after a concurrent revocation, resume =`;
|
||||
- an advisory lock on the subscription taken before the conferral (`pg_advisory_xact_lock(hashtext(<subscription id>)::bigint)` added directly after `LockPools`, so the refusing resume of `AnEndingActFirst` reaches it): caught by `TestResumeSubscription_AnEndingActFirst`, `want_new` `the resume took the subscription's advisory lock`;
|
||||
- the reachability test dropped from `ResumePlan`: caught by `TestResumePlan_RefusesAnUnreachableMapping`, `want_new` `resume over an unreachable mapping =`;
|
||||
- the trigger's declaration removed: caught by `TestEveryMutationRouteIsDeclared`, `want_new` `is neither a registered form's path nor a declared action trigger`;
|
||||
- the confirmation's first sentence dropped: caught by `TestResumeConfirmation`, `want_new` `resume confirmation =`;
|
||||
@@ -473,7 +483,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
- On #271, a note, not a close:
|
||||
|
||||
> A note from the grant pause work. When a subscription pays for a product that is a tier of two ladders and a grant takes one of them, the subscription stops delivering that product on both ladders, and the other ladder is left with nothing on it. If the subscription pays for nothing else, its billing is now paused while the grant holds. Checkout now refuses every tier of the other ladder, because buying there would start a second subscription while the first still exists, and the paid tier's card on that ladder shows no price or control. What the member should see or be offered on that ladder is still this issue's open question.
|
||||
> A note from the grant pause work. When a subscription pays for a product that is a tier of two ladders and a grant takes one of them, the subscription stops delivering that product on both ladders, and the other ladder is left with nothing on it. If the subscription pays for nothing else, its billing is now paused while the grant holds. Checkout now refuses every tier of the other ladder, because buying there would start a second subscription while the first still exists, and the paid tier's card on that ladder offers no control. What the member should see or be offered on that ladder is still this issue's open question.
|
||||
|
||||
- #279 and #280 stay open and get no comment.
|
||||
- [ ] 13.6 After a deploy applies `00036` and `00037`, re-run `scripts/db-reader-role.sql` on that deployment (`docs/database-management.md`, "Running the script").
|
||||
|
||||
Reference in New Issue
Block a user