Decide a subscription's collection pause in the reconcile and apply it through the outbox
Third section of #269's change. The reconcile now decides, under the pool row, whether the subscription's payment collection should be paused: it is paused while every product it delivers is left alone because a grant holds the ladder, its status is active, trialing, past_due or unpaid, and at least one item confers (entitlements.CollectionWanted). The reconcile does not call Stripe in its transaction: it records the decision and, when the mirror and the decision disagree, writes a reconcile_subscription outbox entry in the same transaction. The outbox executor reconciles again after the commit and sets or clears pause_collection (behavior void, with the console's marker in the subscription's metadata), then reconciles once more so the mirror records what Stripe answered. A pause made in the Dashboard (no marker) is never replaced or cleared. A malformed payload, a subscription id that is not a UUID and a Stripe 400 are not retried; other failures retry for a day, then dead-letter. The suspended branch decides too, so a past-due subscription a grant displaces is paused. A failed read of its items is logged and does not roll back the suspension: the suspension commits, and the decision error is returned after the commit only when the call would apply it. docs/stripe.md, docs/database-locks.md and test/AGENTS.md describe the action, its order after the pool row, and the sandbox notes. Tests: TestDecideCollection, TestApplyCollection_* (the foreign pause left alone, the clear removing the marker), the reconcile's outbox entry and its absence, TestOutbox_ReconcileSubscriptionAction and its refusals, TestReconcile_APastDueSubscriptionWithAnUnmappedPriceIsStillSuspended. Four trace goldens: three gain the outbox insert before commit, past_due gains the decision's reads. Review: one major, an unmapped price in the suspended branch rolled back the suspension, so a past-due subscription kept delivering; fixed as above, with its test and break. String restored for the test's failure texts; the outbox refuses a non-UUID id. Breaks: 14 of 14 caught. Full suite on reset databases: 4756 pass, 14 skip. make screens: only regenerated ids. The change's text gains a fourth Tier changes label, "Subscription delivers again after a subscription dropped its tier", for a subscription the holding subscription's tier drop delivers again.
This commit is contained in:
@@ -167,7 +167,15 @@ advisory lock, then the rest by branch.
|
||||
which confers through `core.confer`), then materialization.
|
||||
- **Suspended:** `reconcileSuspended` takes the pool row (`LockPools`) before
|
||||
`core.sync_source_status('suspended')`, then materializes when it suspended
|
||||
a provision.
|
||||
a provision. For a `past_due` or `unpaid` subscription it then makes the
|
||||
pause decision's reads under the row it holds (`collectionInputs`: the
|
||||
items' prices and products, the live provisions, the shapes and the
|
||||
displacements); a `paused` subscription makes none.
|
||||
- **The collection pause:** a disagreement between the subscription's pause
|
||||
and the rule writes one `reconcile_subscription` row to `core.outbox` in the
|
||||
reconcile's transaction, an insert that takes no lock. The outbox's own
|
||||
reconcile (`ApplySubscriptionCollection`) makes the Stripe update after the
|
||||
commit, with no lock held.
|
||||
|
||||
No path takes a pool row and then a subscription's advisory lock, so the
|
||||
order cannot wait in a cycle with a grant act, which takes the pool row and
|
||||
|
||||
+2
-1
@@ -214,7 +214,7 @@ A member moves between the paid tiers of a plan ladder on the Products page, and
|
||||
- **A grant over a paid plan.** An operator's grant over a tier a subscription pays for keeps the ladder until it ends or is revoked. The subscription keeps billing and delivers nothing there, and the console changes nothing at Stripe. While the grant holds the ladder, the organization page's Billing card and the subscription's row in the operator's subscriptions list carry a **Not delivering** badge, whose title reads "Billing continues while a grant holds {ladder}." Once only the organization type's default holds the ladder, or nothing does, the subscription's next reconcile delivers its tier again. A new purchase over a grant still replaces the grant.
|
||||
- **Pay invoice.** The card of a plan whose payment is due, and the detail of an open invoice, link to Stripe's hosted invoice page. The console reads the page's URL from Stripe when the member opens the link and redirects there; it never stores or logs the URL, which is a bearer link, and it needs no key permission beyond the reads of subscriptions and invoices that the reconciles already make. Paying there makes the new card the customer's default for invoices but leaves the subscription's own default on the card that failed, which Stripe charges first, so the next renewal charges the failed card again. Stripe's page still takes payment for an invoice Stripe has marked uncollectible, which the console shows as open until the invoice sweep reads it again.
|
||||
|
||||
A restricted key needs permission for the calls these moves make, beyond those the console already uses: `POST /v1/subscription_schedules`, `POST /v1/subscription_schedules/{id}`, `POST /v1/subscription_schedules/{id}/release` and `POST /v1/invoices/{id}/void`. Stripe names the missing permission in the error a key without it receives.
|
||||
A restricted key needs permission for the calls these moves make, beyond those the console already uses: `POST /v1/subscription_schedules`, `POST /v1/subscription_schedules/{id}`, `POST /v1/subscription_schedules/{id}/release` and `POST /v1/invoices/{id}/void`. The console also updates a subscription with `POST /v1/subscriptions/{id}` to set `pause_collection` while a grant holds its ladder and to clear it when the grant no longer does, which is the Subscriptions write the plan moves already need. Stripe names the missing permission in the error a key without it receives.
|
||||
|
||||
## Making a product purchasable
|
||||
|
||||
@@ -244,6 +244,7 @@ If Stripe is **not configured** for the deployment (no API key), the panel says
|
||||
- **Do not delete products or prices in Stripe.** Deactivate them in the member console instead.
|
||||
- **Do not modify subscription quantities or prices in Stripe.** Changes should flow through the member console.
|
||||
- **Do not edit a subscription schedule the console attached** (its metadata carries `scheduled_from_price_id`). Releasing one in the Dashboard cancels that member's scheduled downgrade, and the console records it as taken back; editing its phases is not supported.
|
||||
- **Do not remove the console's collection marker** (metadata `member_console_collection`) or resume collection of a subscription the console paused. The console pauses it again while a grant holds its ladder, and a subscription paused without the marker is left as it is.
|
||||
|
||||
### Acceptable in Stripe
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
// CollectionPauseWanted reports whether a subscription's payment collection is
|
||||
// paused while grants hold its ladders. It reads no row. The subscription's
|
||||
// collection is paused when all four hold:
|
||||
//
|
||||
// 1. its status is active, trialing, past_due or unpaid;
|
||||
// 2. at least one of its current items confers a product (desired is the
|
||||
// products with an entitlement set);
|
||||
// 3. every such product is left alone by DisplacedProducts (left);
|
||||
// 4. every displacement that leaves one alone is held by a grant.
|
||||
//
|
||||
// A subscription partly displaced keeps billing, because one of its products
|
||||
// still delivers. A subscription displaced by another subscription keeps
|
||||
// billing too: that holder is a purchase the member pays for, not an operator's
|
||||
// decision, and the console stops billing only for a plan an operator replaced.
|
||||
func CollectionPauseWanted(status string, desired []string, left map[string]Displacement) bool {
|
||||
switch status {
|
||||
case "active", "trialing", "past_due", "unpaid":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if len(desired) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, productID := range desired {
|
||||
d, out := left[productID]
|
||||
if !out {
|
||||
return false
|
||||
}
|
||||
if d.HolderSource != "grant" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
import "testing"
|
||||
|
||||
// pauseWantedRow is one case of CollectionPauseWanted.
|
||||
type pauseWantedRow struct {
|
||||
name string
|
||||
status string
|
||||
desired []string
|
||||
left map[string]Displacement
|
||||
want bool
|
||||
}
|
||||
|
||||
func checkPauseWanted(t *testing.T, row pauseWantedRow) {
|
||||
t.Helper()
|
||||
if got := CollectionPauseWanted(row.status, row.desired, row.left); got != row.want {
|
||||
t.Errorf("CollectionPauseWanted(%s) = %v, want %v", row.name, got, row.want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCollectionPauseWanted pins the four conditions of the rule: a status that
|
||||
// bills, a conferring product, every conferring product left alone, and every
|
||||
// holder a grant.
|
||||
func TestCollectionPauseWanted(t *testing.T) {
|
||||
byGrant := Displacement{LadderID: "L1", HolderSource: "grant"}
|
||||
bySub := Displacement{LadderID: "L1", HolderSource: "subscription"}
|
||||
for _, row := range []pauseWantedRow{
|
||||
{name: "active, every product left alone by grants", status: "active", desired: []string{"A", "B"},
|
||||
left: map[string]Displacement{"A": byGrant, "B": byGrant}, want: true},
|
||||
{name: "trialing, the same", status: "trialing", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}, want: true},
|
||||
{name: "past_due, the same", status: "past_due", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}, want: true},
|
||||
{name: "unpaid, the same", status: "unpaid", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}, want: true},
|
||||
{name: "paused", status: "paused", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}},
|
||||
{name: "incomplete", status: "incomplete", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}},
|
||||
{name: "canceled", status: "canceled", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": byGrant}},
|
||||
{name: "no product with a set", status: "active", desired: nil, left: map[string]Displacement{}},
|
||||
{name: "one product left alone, one not", status: "active", desired: []string{"A", "B"},
|
||||
left: map[string]Displacement{"A": byGrant}},
|
||||
{name: "left alone by another subscription", status: "active", desired: []string{"A"},
|
||||
left: map[string]Displacement{"A": bySub}},
|
||||
{name: "left alone by a grant and by a purchase", status: "active", desired: []string{"A", "B"},
|
||||
left: map[string]Displacement{"A": byGrant, "B": bySub}},
|
||||
} {
|
||||
checkPauseWanted(t, row)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package entitlements
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/integration"
|
||||
)
|
||||
|
||||
// ReconcileSubscriptionAction is the outbox action type that asks the Stripe
|
||||
// provider to reconcile one subscription and make the Stripe call its
|
||||
// collection pause needs. The Stripe executor names the same constant.
|
||||
const ReconcileSubscriptionAction = "reconcile_subscription"
|
||||
|
||||
// RequestSubscriptionReconcile writes a reconcile_subscription entry for the
|
||||
// core subscription into tx, the caller's transaction, so the request commits
|
||||
// or rolls back with the act that made it. It is an insert and takes no lock.
|
||||
func RequestSubscriptionReconcile(ctx context.Context, tx integration.DBTX, subscriptionID string) error {
|
||||
return integration.Enqueue(ctx, tx, "stripe", ReconcileSubscriptionAction,
|
||||
map[string]string{"subscription_id": subscriptionID})
|
||||
}
|
||||
@@ -4,9 +4,16 @@
|
||||
package fulfillment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/stripe/stripe-go/v81"
|
||||
"github.com/stripe/stripe-go/v81/subscription"
|
||||
|
||||
internalstripe "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/store"
|
||||
)
|
||||
|
||||
// The metadata key and value that mark a collection pause as the console's.
|
||||
@@ -30,3 +37,141 @@ func collectionMirror(sub *stripe.Subscription) (behavior sql.NullString, resume
|
||||
return sql.NullString{String: string(sub.PauseCollection.Behavior), Valid: true},
|
||||
unixToNullTime(sub.PauseCollection.ResumesAt), marked
|
||||
}
|
||||
|
||||
// collectionAction is what the reconcile does at Stripe about a subscription's
|
||||
// collection pause.
|
||||
type collectionAction int
|
||||
|
||||
const (
|
||||
collectionNone collectionAction = iota // Stripe already agrees with the rule
|
||||
collectionSet // pause collection with the console's marker
|
||||
collectionClear // remove the console's pause and marker
|
||||
)
|
||||
|
||||
// decideCollection compares the rule's answer (wanted) with the pause on the
|
||||
// fetched subscription and names the one update that makes them agree. It
|
||||
// reads no row. foreign reports a pause without the console's marker, made
|
||||
// outside the console: the console neither replaces nor clears it, so the
|
||||
// action is none for it.
|
||||
//
|
||||
// wanted Stripe state action
|
||||
// paused none, or a stale marker set
|
||||
// paused the console's, behavior void none
|
||||
// paused the console's, another behavior set
|
||||
// paused foreign none
|
||||
// not the console's, or a stale marker clear
|
||||
// not none, or foreign none
|
||||
func decideCollection(wanted bool, sub *stripe.Subscription) (action collectionAction, foreign bool) {
|
||||
paused := sub.PauseCollection != nil
|
||||
marked := sub.Metadata[collectionMarkerKey] == collectionMarkerValue
|
||||
foreign = paused && !marked
|
||||
if wanted {
|
||||
switch {
|
||||
case foreign:
|
||||
return collectionNone, true
|
||||
case !paused:
|
||||
return collectionSet, false
|
||||
case sub.PauseCollection.Behavior != stripe.SubscriptionPauseCollectionBehaviorVoid:
|
||||
return collectionSet, false
|
||||
}
|
||||
return collectionNone, false
|
||||
}
|
||||
if marked {
|
||||
return collectionClear, false
|
||||
}
|
||||
return collectionNone, foreign
|
||||
}
|
||||
|
||||
// collectionParams builds the update that carries out an action: the set
|
||||
// pauses collection with behavior void and the marker, in one update, and the
|
||||
// clear removes the pause and the marker. It never sets resumes_at.
|
||||
func collectionParams(action collectionAction) *stripe.SubscriptionParams {
|
||||
params := &stripe.SubscriptionParams{}
|
||||
switch action {
|
||||
case collectionSet:
|
||||
params.PauseCollection = &stripe.SubscriptionPauseCollectionParams{
|
||||
Behavior: stripe.String(string(stripe.SubscriptionPauseCollectionBehaviorVoid)),
|
||||
}
|
||||
params.AddMetadata(collectionMarkerKey, collectionMarkerValue)
|
||||
case collectionClear:
|
||||
params.AddExtra("pause_collection", "")
|
||||
params.AddMetadata(collectionMarkerKey, "")
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
// applyCollectionAction makes the one subscription update the action needs
|
||||
// and logs it (L2). It runs after the reconcile's commit with no lock held,
|
||||
// and returns the error wrapped so the outbox's dead-letter table names the
|
||||
// Stripe subscription. The call sets a state, so it needs no idempotency key
|
||||
// of its own: stripe-go adds one per request and reuses it across its own
|
||||
// retries, and repeating the call is harmless.
|
||||
func applyCollectionAction(logger *slog.Logger, stripeSubscriptionID string, action collectionAction) error {
|
||||
if _, err := subscription.Update(stripeSubscriptionID, collectionParams(action)); err != nil {
|
||||
return fmt.Errorf("reconcile: apply collection to %s: %w", stripeSubscriptionID, err)
|
||||
}
|
||||
message := "reconcile: subscription collection paused for a grant"
|
||||
if action == collectionClear {
|
||||
message = "reconcile: subscription collection resumed"
|
||||
}
|
||||
logger.Info(message, slog.String("stripe_subscription_id", stripeSubscriptionID))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplySubscriptionCollection is the outbox executor's entry: it reconciles
|
||||
// the core subscription and, when Stripe's collection pause disagrees with the
|
||||
// rule, makes the Stripe call after the reconcile's commit. A member's move
|
||||
// calls ReconcileSubscription, which never makes the call, so a pause failure
|
||||
// never reports a successful cancellation or switch as failed; here the error
|
||||
// goes back to Temporal, which retries the whole reconcile, re-reading Stripe
|
||||
// and deciding again. The decision is a set-to-state, so two runs that cross
|
||||
// converge through the echo of the call: when this run made a call it runs once
|
||||
// more, deciding from a fetch taken after its own call, at most twice in all.
|
||||
// A subscription with no Stripe mapping is skipped (L3). Every error names the
|
||||
// Stripe subscription id.
|
||||
func ApplySubscriptionCollection(ctx context.Context, db *sql.DB, logger *slog.Logger, keyMode string, coreSubscriptionID, reason string) error {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
mapping, err := internalstripe.New(db).GetSubscriptionMappingBySubscriptionID(ctx, coreSubscriptionID)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return skipUnmapped(logger, coreSubscriptionID)
|
||||
case err != nil:
|
||||
return fmt.Errorf("reconcile: read the Stripe mapping of subscription %s: %w", coreSubscriptionID, err)
|
||||
case !mapping.StripeSubscriptionID.Valid || mapping.StripeSubscriptionID.String == "":
|
||||
return skipUnmapped(logger, coreSubscriptionID)
|
||||
}
|
||||
stripeID := mapping.StripeSubscriptionID.String
|
||||
for range 2 {
|
||||
called, err := reconcile(ctx, db, logger, keyMode, stripeID, reason, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stripe subscription %s: %w", stripeID, err)
|
||||
}
|
||||
if !called {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// chooseCollection decides the action for a fetched subscription and logs a
|
||||
// wanted pause that a foreign one stands in the way of (L1), once per
|
||||
// reconcile.
|
||||
func chooseCollection(logger *slog.Logger, sub *stripe.Subscription, subscriptionID string, wanted bool) collectionAction {
|
||||
action, foreign := decideCollection(wanted, sub)
|
||||
if foreign && wanted {
|
||||
logger.Info("reconcile: collection paused outside the console; left as it is",
|
||||
slog.String("subscription_id", subscriptionID),
|
||||
slog.String("behavior", string(sub.PauseCollection.Behavior)))
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
// skipUnmapped logs that a subscription has no Stripe mapping to apply a
|
||||
// collection pause to (L3) and answers the executor's nil.
|
||||
func skipUnmapped(logger *slog.Logger, coreSubscriptionID string) error {
|
||||
logger.Info("reconcile: subscription has no Stripe mapping; nothing to apply",
|
||||
slog.String("subscription_id", coreSubscriptionID))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package fulfillment
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
stripe "github.com/stripe/stripe-go/v81"
|
||||
)
|
||||
|
||||
// decideRow is one line of design D2's table: the rule's answer, the pause on
|
||||
// the fetched subscription and the action and foreign flag it must give.
|
||||
type decideRow struct {
|
||||
name string
|
||||
wanted bool
|
||||
pause *stripe.SubscriptionPauseCollection
|
||||
marked bool
|
||||
wantAction collectionAction
|
||||
wantForeign bool
|
||||
}
|
||||
|
||||
func decideSubscription(row decideRow) *stripe.Subscription {
|
||||
sub := &stripe.Subscription{PauseCollection: row.pause}
|
||||
if row.marked {
|
||||
sub.Metadata = map[string]string{collectionMarkerKey: collectionMarkerValue}
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
func (a collectionAction) String() string {
|
||||
switch a {
|
||||
case collectionNone:
|
||||
return "none"
|
||||
case collectionSet:
|
||||
return "set"
|
||||
case collectionClear:
|
||||
return "clear"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func checkDecideCollection(t *testing.T, row decideRow) {
|
||||
t.Helper()
|
||||
action, foreign := decideCollection(row.wanted, decideSubscription(row))
|
||||
if action != row.wantAction || foreign != row.wantForeign {
|
||||
t.Errorf("decideCollection(%s) = %v, %v, want %v, %v", row.name, action, foreign, row.wantAction, row.wantForeign)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecideCollection pins design D2's table line by line.
|
||||
func TestDecideCollection(t *testing.T) {
|
||||
void := &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorVoid}
|
||||
uncollectible := &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorMarkUncollectible}
|
||||
for _, row := range []decideRow{
|
||||
{name: "paused, none", wanted: true, wantAction: collectionSet},
|
||||
{name: "paused, the console's void", wanted: true, pause: void, marked: true, wantAction: collectionNone},
|
||||
{name: "paused, the console's mark_uncollectible", wanted: true, pause: uncollectible, marked: true, wantAction: collectionSet},
|
||||
{name: "paused, stale marker", wanted: true, marked: true, wantAction: collectionSet},
|
||||
{name: "paused, foreign", wanted: true, pause: void, wantAction: collectionNone, wantForeign: true},
|
||||
{name: "not paused, the console's", pause: void, marked: true, wantAction: collectionClear},
|
||||
{name: "not paused, the console's mark_uncollectible", pause: uncollectible, marked: true, wantAction: collectionClear},
|
||||
{name: "not paused, stale marker", marked: true, wantAction: collectionClear},
|
||||
{name: "not paused, none", wantAction: collectionNone},
|
||||
{name: "not paused, foreign", pause: void, wantAction: collectionNone, wantForeign: true},
|
||||
} {
|
||||
checkDecideCollection(t, row)
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,23 @@ package fulfillment_test
|
||||
// change grant-pauses-subscription-billing, design D3, tasks 2.3 and 2.6).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stripe "github.com/stripe/stripe-go/v81"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/stripetest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/world"
|
||||
)
|
||||
|
||||
type mirrorRow struct {
|
||||
@@ -102,3 +110,225 @@ func readMirror(t *testing.T, database *sql.DB, subID string) (sql.NullString, s
|
||||
}
|
||||
return behavior, resume, marked
|
||||
}
|
||||
|
||||
// The outbox's reconcile makes the Stripe call a collection pause needs
|
||||
// (openspec change grant-pauses-subscription-billing, design D1, tasks 3.7).
|
||||
|
||||
const markerField = "metadata[member_console_collection]"
|
||||
|
||||
// stripeAppliesCollection makes the mock's subscription change the way Stripe
|
||||
// changes it when an update lands: a pause set with its marker, or cleared.
|
||||
func stripeAppliesCollection(mock *stripetest.MockBackend, stripeSubID string) {
|
||||
mock.Handle = func(c stripetest.Call) (any, error, bool) {
|
||||
if c.Method == "POST" && c.Path == "/v1/subscriptions/"+stripeSubID {
|
||||
applyCollectionForm(mock.Sub, c.Form)
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func applyCollectionForm(sub *stripe.Subscription, f url.Values) {
|
||||
if b := f.Get("pause_collection[behavior]"); b != "" {
|
||||
sub.PauseCollection = &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehavior(b)}
|
||||
}
|
||||
if v, ok := f["pause_collection"]; ok && v[0] == "" {
|
||||
sub.PauseCollection = nil
|
||||
}
|
||||
v, ok := f[markerField]
|
||||
switch {
|
||||
case !ok:
|
||||
case v[0] == "":
|
||||
delete(sub.Metadata, "member_console_collection")
|
||||
default:
|
||||
if sub.Metadata == nil {
|
||||
sub.Metadata = map[string]string{}
|
||||
}
|
||||
sub.Metadata["member_console_collection"] = v[0]
|
||||
}
|
||||
}
|
||||
|
||||
func applyCollection(t *testing.T, database *sql.DB, logger *slog.Logger, fx fixture) error {
|
||||
t.Helper()
|
||||
return fulfillment.ApplySubscriptionCollection(context.Background(), database, logger, stripetest.KeyMode(),
|
||||
coreSubID(t, database, fx.stripeSubID), "test:apply")
|
||||
}
|
||||
|
||||
func reconcileEntries(t *testing.T, database *sql.DB, coreSub string) int {
|
||||
t.Helper()
|
||||
return scalarInt(t, database,
|
||||
`SELECT count(*) FROM core.outbox WHERE action_type = 'reconcile_subscription' AND payload->>'subscription_id' = $1`, coreSub)
|
||||
}
|
||||
|
||||
func setMarkedPause(mock *stripetest.MockBackend, behavior stripe.SubscriptionPauseCollectionBehavior, marked bool) {
|
||||
mock.Sub.PauseCollection = &stripe.SubscriptionPauseCollection{Behavior: behavior}
|
||||
if marked {
|
||||
mock.Sub.Metadata = map[string]string{"member_console_collection": "paused_for_grant"}
|
||||
}
|
||||
}
|
||||
|
||||
func subscriptionPosts(mock *stripetest.MockBackend, fx fixture) []stripetest.Call {
|
||||
return mock.CallsTo("POST", "/v1/subscriptions/"+fx.stripeSubID)
|
||||
}
|
||||
|
||||
func TestApplyCollection_PausesADisplacedSubscription(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
stripeAppliesCollection(mock, fx.stripeSubID)
|
||||
core := coreSubID(t, database, fx.stripeSubID)
|
||||
|
||||
if err := applyCollection(t, database, discardLogger(), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
posts := subscriptionPosts(mock, fx)
|
||||
want := url.Values{
|
||||
"pause_collection[behavior]": {"void"},
|
||||
markerField: {"paused_for_grant"},
|
||||
}
|
||||
if len(posts) != 1 || !maps.EqualFunc(posts[0].Form, want, slicesEqual) {
|
||||
t.Errorf("pause call form = %v, want %v", posts, want)
|
||||
}
|
||||
if n := reconcileEntries(t, database, core); n != 0 {
|
||||
t.Errorf("the executor's reconcile wrote %d outbox entries, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func slicesEqual(a, b []string) bool { return strings.Join(a, "\x00") == strings.Join(b, "\x00") }
|
||||
|
||||
func TestApplyCollection_ClearsTheConsolesPause(t *testing.T) {
|
||||
database, fx, mock := subscribed(t)
|
||||
setMarkedPause(mock, stripe.SubscriptionPauseCollectionBehaviorVoid, true)
|
||||
stripeAppliesCollection(mock, fx.stripeSubID)
|
||||
|
||||
if err := applyCollection(t, database, discardLogger(), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
posts := subscriptionPosts(mock, fx)
|
||||
want := url.Values{"pause_collection": {""}, markerField: {""}}
|
||||
if len(posts) != 1 || !maps.EqualFunc(posts[0].Form, want, slicesEqual) {
|
||||
t.Errorf("clear call form = %v, want %v", posts, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCollection_LeavesAForeignPause(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
setMarkedPause(mock, stripe.SubscriptionPauseCollectionBehaviorMarkUncollectible, false)
|
||||
var logs bytes.Buffer
|
||||
|
||||
if err := applyCollection(t, database, slog.New(slog.NewTextHandler(&logs, nil)), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
if posts := subscriptionPosts(mock, fx); len(posts) != 0 {
|
||||
t.Errorf("a pause made outside the console was changed: %v", posts)
|
||||
}
|
||||
wantInLine(t, logs.String(), "collection paused outside the console; left as it is",
|
||||
"subscription_id="+coreSubID(t, database, fx.stripeSubID), "behavior=mark_uncollectible")
|
||||
}
|
||||
|
||||
// wantInLine fails the test unless one line of logs holds every part.
|
||||
func wantInLine(t *testing.T, logs string, parts ...string) {
|
||||
t.Helper()
|
||||
for _, line := range strings.Split(logs, "\n") {
|
||||
found := true
|
||||
for _, p := range parts {
|
||||
found = found && strings.Contains(line, p)
|
||||
}
|
||||
if found {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Errorf("no log line holds %q; logs:\n%s", parts, logs)
|
||||
}
|
||||
|
||||
func TestApplyCollection_AgreementCallsNothing(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
setMarkedPause(mock, stripe.SubscriptionPauseCollectionBehaviorVoid, true)
|
||||
|
||||
if err := applyCollection(t, database, discardLogger(), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
if posts := subscriptionPosts(mock, fx); len(posts) != 0 {
|
||||
t.Errorf("an agreeing subscription was updated: %v", posts)
|
||||
}
|
||||
}
|
||||
|
||||
// decidesAgainRow is a Stripe that applies the pause call or ignores it.
|
||||
type decidesAgainRow struct {
|
||||
name string
|
||||
applies bool
|
||||
wantUpdates int
|
||||
}
|
||||
|
||||
func TestApplyCollection_DecidesAgainAfterItsCall(t *testing.T) {
|
||||
for _, row := range []decidesAgainRow{
|
||||
{name: "the call lands", applies: true, wantUpdates: 1},
|
||||
{name: "Stripe reverts the call", applies: false, wantUpdates: 2},
|
||||
} {
|
||||
t.Run(row.name, func(t *testing.T) { checkDecidesAgain(t, row) })
|
||||
}
|
||||
}
|
||||
|
||||
func checkDecidesAgain(t *testing.T, row decidesAgainRow) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
if row.applies {
|
||||
stripeAppliesCollection(mock, fx.stripeSubID)
|
||||
}
|
||||
mark := len(mock.Calls)
|
||||
if err := applyCollection(t, database, discardLogger(), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
fetches := 0
|
||||
for _, line := range callsSince(mock, mark) {
|
||||
if strings.HasPrefix(line, "stripe GET /v1/subscriptions/"+fx.stripeSubID) {
|
||||
fetches++
|
||||
}
|
||||
}
|
||||
if fetches != 2 {
|
||||
t.Errorf("fetches = %d, want 2", fetches)
|
||||
}
|
||||
if n := len(subscriptionPosts(mock, fx)); n != row.wantUpdates {
|
||||
t.Errorf("updates = %d, want %d", n, row.wantUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCollection_ReturnsAFailedCall(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
mock.Sub.CancelAtPeriodEnd = true
|
||||
mock.Handle = func(c stripetest.Call) (any, error, bool) {
|
||||
if c.Method == "POST" {
|
||||
return nil, &stripe.Error{HTTPStatusCode: 500, Msg: "refused"}, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
err := applyCollection(t, database, discardLogger(), fx)
|
||||
var stripeErr *stripe.Error
|
||||
if err == nil || !strings.Contains(err.Error(), "apply collection") || !errors.As(err, &stripeErr) {
|
||||
t.Errorf("ApplySubscriptionCollection = %v, want the update's error", err)
|
||||
}
|
||||
if n := scalarInt(t, database, `SELECT count(*) FROM core.subscriptions WHERE subscription_id = $1 AND cancel_at_period_end`,
|
||||
coreSubID(t, database, fx.stripeSubID)); n != 1 {
|
||||
t.Errorf("the reconcile's writes did not commit before the call: %d rows", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCollection_NoMappingIsASkip(t *testing.T) {
|
||||
database := dbtest.Open(t)
|
||||
w := world.New(t, database)
|
||||
o := w.Org("Unmapped Collection", w.OrgType("ucn"), w.Person("Owner"))
|
||||
w.MapAccount(w.BillingAccount(o, "Unmapped Collection"))
|
||||
plan := w.Product("Plan")
|
||||
w.Price(plan, 1200)
|
||||
sub := w.Subscribe(o, world.SubOpts{}, plan)
|
||||
mock := &stripetest.MockBackend{}
|
||||
t.Cleanup(stripetest.Install(mock))
|
||||
var logs bytes.Buffer
|
||||
|
||||
err := fulfillment.ApplySubscriptionCollection(context.Background(), database, slog.New(slog.NewTextHandler(&logs, nil)),
|
||||
stripetest.KeyMode(), sub.ID, "test:apply")
|
||||
if err != nil {
|
||||
t.Errorf("an unmapped subscription = %v, want nil", err)
|
||||
}
|
||||
if len(mock.Calls) != 0 {
|
||||
t.Errorf("an unmapped subscription called Stripe: %v", mock.Calls)
|
||||
}
|
||||
wantInLine(t, logs.String(), "subscription has no Stripe mapping; nothing to apply", "subscription_id="+sub.ID)
|
||||
}
|
||||
|
||||
@@ -137,6 +137,25 @@ func TestReconcile_AGrantOverTheSubscriptionKeepsTheLadder(t *testing.T) {
|
||||
reconcileLeavesTheGrant(t, database, fx, mock, g, "the grant stopped delivering after the subscription's reconcile")
|
||||
}
|
||||
|
||||
// A plain reconcile that finds the pause disagreeing with the rule writes one
|
||||
// outbox entry and makes no call (openspec change
|
||||
// grant-pauses-subscription-billing, design D1, task 3.7).
|
||||
func TestReconcile_AGrantOverTheSubscriptionRequestsThePause(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
mark := len(mock.Calls)
|
||||
|
||||
reconcile(t, database, fx.stripeSubID, "stripe:customer.subscription.updated")
|
||||
core := coreSubID(t, database, fx.stripeSubID)
|
||||
if n := reconcileEntries(t, database, core); n != 1 {
|
||||
t.Errorf("reconcile_subscription entries for %s = %d, want 1", core, n)
|
||||
}
|
||||
for _, line := range callsSince(mock, mark) {
|
||||
if strings.HasPrefix(line, "stripe POST /v1/subscriptions/") {
|
||||
t.Errorf("the reconcile called Stripe for the pause: %v", line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// T1b: a grant of the subscription's own tier takes the ladder as a transfer,
|
||||
// and keeps it.
|
||||
func TestReconcile_AGrantOfTheSubscriptionsOwnTierKeepsTheLadder(t *testing.T) {
|
||||
|
||||
@@ -42,13 +42,31 @@ import (
|
||||
// and on any pool_provision_transitions row.
|
||||
//
|
||||
// It is convergent and idempotent: running it again with unchanged Stripe state
|
||||
// is a no-op, and it never bails early on a pre-existing mapping.
|
||||
// is a no-op, except that while the collection pause disagrees with the rule each
|
||||
// run writes one more reconcile_subscription entry. It never bails early on a
|
||||
// pre-existing mapping.
|
||||
//
|
||||
// keyMode is the mode of the key the process runs under; the row is checked
|
||||
// against it before the fetch.
|
||||
//
|
||||
// It never calls Stripe about the collection pause: a disagreement between the
|
||||
// subscription's pause and the pause rule writes one reconcile_subscription
|
||||
// outbox entry in its transaction instead (ApplySubscriptionCollection makes
|
||||
// the call). A member's move calls this after its own Stripe call, so a pause
|
||||
// failure never reports a successful cancellation or switch as failed.
|
||||
func ReconcileSubscription(ctx context.Context, db *sql.DB, logger *slog.Logger, keyMode string, stripeSubscriptionID, reason string) error {
|
||||
_, err := reconcile(ctx, db, logger, keyMode, stripeSubscriptionID, reason, false)
|
||||
return err
|
||||
}
|
||||
|
||||
// reconcile is ReconcileSubscription's body. With applyCollection, a
|
||||
// disagreement between the subscription's collection pause and the rule is
|
||||
// carried out at Stripe after the commit, and the error of that call is
|
||||
// returned so the outbox retries the whole reconcile; called reports whether
|
||||
// the call was made. Without it the disagreement writes an outbox entry.
|
||||
func reconcile(ctx context.Context, db *sql.DB, logger *slog.Logger, keyMode string, stripeSubscriptionID, reason string, applyCollection bool) (called bool, err error) {
|
||||
if stripeSubscriptionID == "" {
|
||||
return fmt.Errorf("reconcile: empty stripe subscription id")
|
||||
return false, fmt.Errorf("reconcile: empty stripe subscription id")
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
@@ -61,17 +79,48 @@ func ReconcileSubscription(ctx context.Context, db *sql.DB, logger *slog.Logger,
|
||||
// A row that carries no stamp, and a deployment whose key mode is
|
||||
// unknown, reconcile as they do today.
|
||||
if skipUnreachableSubscription(ctx, db, logger, stripeSubscriptionID, keyMode) {
|
||||
return nil
|
||||
return false, nil
|
||||
}
|
||||
|
||||
sub, err := fetchSubscription(stripeSubscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
plan, err := reconcileInTx(ctx, db, logger, sub, stripeSubscriptionID, reason, applyCollection)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Stripe is called only after the commit, so no other reconcile of the
|
||||
// subscription waits on its answer.
|
||||
if err := releaseSpentSchedule(ctx, db, logger, stripeSubscriptionID, plan.spent); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !applyCollection || plan.collection == collectionNone {
|
||||
return false, nil
|
||||
}
|
||||
if err := applyCollectionAction(logger, stripeSubscriptionID, plan.collection); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// afterCommit is what a reconcile's transaction leaves for the calls made
|
||||
// after its commit: the spent schedule to release, and the collection action
|
||||
// the rule asked for (applied only by a reconcile run with applyCollection).
|
||||
type afterCommit struct {
|
||||
spent spentSchedule
|
||||
collection collectionAction
|
||||
}
|
||||
|
||||
// reconcileInTx runs the reconcile's transaction on the fetched subscription
|
||||
// and commits it. Without applyCollection, a collection action the rule asks
|
||||
// for writes the outbox entry in the transaction.
|
||||
func reconcileInTx(ctx context.Context, db *sql.DB, logger *slog.Logger, sub *stripe.Subscription, stripeSubscriptionID, reason string, applyCollection bool) (afterCommit, error) {
|
||||
var plan afterCommit
|
||||
tx, err := entitlements.BeginMaterializing(ctx, db)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: begin tx: %w", err)
|
||||
return plan, fmt.Errorf("reconcile: begin tx: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
@@ -79,7 +128,7 @@ func ReconcileSubscription(ctx context.Context, db *sql.DB, logger *slog.Logger,
|
||||
// subscription so they converge instead of racing the GiST exclusion.
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`SELECT pg_advisory_xact_lock(hashtext($1)::bigint)`, stripeSubscriptionID); err != nil {
|
||||
return fmt.Errorf("reconcile: advisory lock: %w", err)
|
||||
return plan, fmt.Errorf("reconcile: advisory lock: %w", err)
|
||||
}
|
||||
|
||||
billingQ := billing.New(tx)
|
||||
@@ -88,40 +137,53 @@ func ReconcileSubscription(ctx context.Context, db *sql.DB, logger *slog.Logger,
|
||||
|
||||
billingAccountID, poolID, err := resolveAccountPool(ctx, billingQ, stripeQ, entQ, stripeSubscriptionID, sub)
|
||||
if err != nil {
|
||||
return err
|
||||
return plan, err
|
||||
}
|
||||
|
||||
// 1.5 Create-or-update the core subscription + mapping. Either branch fully
|
||||
// reconciles entitlements below; this is a create/update fork, not a skip.
|
||||
subscriptionID, err := upsertSubscription(ctx, billingQ, stripeQ, billingAccountID, stripeSubscriptionID, sub, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
return plan, err
|
||||
}
|
||||
subUUID, err := uuid.Parse(subscriptionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: invalid subscription uuid %s: %w", subscriptionID, err)
|
||||
return plan, fmt.Errorf("reconcile: invalid subscription uuid %s: %w", subscriptionID, err)
|
||||
}
|
||||
|
||||
actor := entitlements.Actor{ActorType: "webhook", Reason: reason}
|
||||
var undecided error
|
||||
|
||||
var spent spentSchedule
|
||||
switch classifyStatus(string(sub.Status)) {
|
||||
case statusEnded:
|
||||
return reconcileEnded(ctx, tx, billingQ, stripeQ, entQ, poolID, subscriptionID, subUUID, actor)
|
||||
return plan, reconcileEnded(ctx, tx, billingQ, stripeQ, entQ, poolID, subscriptionID, subUUID, actor)
|
||||
|
||||
case statusActive:
|
||||
// 1.6–1.9 Converge items and entitlements for an entitlement-bearing sub.
|
||||
if err := reconcileItems(ctx, logger, billingQ, stripeQ, entQ, sub, subscriptionID, subUUID, poolID, actor); err != nil {
|
||||
return err
|
||||
out, err := reconcileItems(ctx, logger, billingQ, stripeQ, entQ, sub, subscriptionID, subUUID, poolID, actor)
|
||||
if err != nil {
|
||||
return plan, err
|
||||
}
|
||||
if spent, err = convergeScheduledChanges(ctx, billingQ, stripeQ, sub, subscriptionID); err != nil {
|
||||
return err
|
||||
if plan.spent, err = convergeScheduledChanges(ctx, billingQ, stripeQ, sub, subscriptionID); err != nil {
|
||||
return plan, err
|
||||
}
|
||||
wanted := entitlements.CollectionPauseWanted(string(sub.Status), out.desired, out.left)
|
||||
plan.collection = chooseCollection(logger, sub, subscriptionID, wanted)
|
||||
|
||||
case statusSuspended:
|
||||
if err := reconcileSuspended(ctx, entQ, subUUID, poolID); err != nil {
|
||||
return err
|
||||
wanted, decideErr, err := reconcileSuspended(ctx, logger, billingQ, stripeQ, entQ, sub, subUUID, poolID)
|
||||
if err != nil {
|
||||
return plan, err
|
||||
}
|
||||
if decideErr != nil {
|
||||
// The suspension stands; no failed read is taken as "not wanted".
|
||||
logger.Warn("reconcile: the collection decision could not be made; the suspension stands",
|
||||
slog.String("subscription_id", subscriptionID),
|
||||
slog.String("error", decideErr.Error()))
|
||||
} else {
|
||||
plan.collection = chooseCollection(logger, sub, subscriptionID, wanted)
|
||||
}
|
||||
undecided = decideErr
|
||||
|
||||
case statusIgnored:
|
||||
// e.g. "incomplete": recorded above; no entitlement action until active.
|
||||
@@ -130,12 +192,18 @@ func ReconcileSubscription(ctx context.Context, db *sql.DB, logger *slog.Logger,
|
||||
slog.String("status", string(sub.Status)))
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
if plan.collection != collectionNone && !applyCollection {
|
||||
if err := entitlements.RequestSubscriptionReconcile(ctx, tx, subscriptionID); err != nil {
|
||||
return plan, fmt.Errorf("reconcile: request the collection reconcile: %w", err)
|
||||
}
|
||||
}
|
||||
// Stripe is called only after the commit, so no other reconcile of the
|
||||
// subscription waits on its answer.
|
||||
return releaseSpentSchedule(ctx, db, logger, stripeSubscriptionID, spent)
|
||||
if err := tx.Commit(); err != nil {
|
||||
return plan, err
|
||||
}
|
||||
if applyCollection && undecided != nil {
|
||||
return plan, fmt.Errorf("reconcile: decide the collection pause: %w", undecided)
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// skipUnreachableSubscription reports whether the subscription's mapping is
|
||||
@@ -281,23 +349,95 @@ func reconcileEnded(
|
||||
// suspended. The pool row is taken after the subscription's lock and before
|
||||
// the status change, so the suspension and its materialization run under it
|
||||
// (docs/database-locks.md, rule 2).
|
||||
func reconcileSuspended(ctx context.Context, entQ *entitlements.Queries, subUUID uuid.UUID, poolID string) error {
|
||||
//
|
||||
// It then answers whether the subscription's collection should be paused
|
||||
// (design D6): a past_due or unpaid subscription a grant displaces would
|
||||
// otherwise keep generating renewals Stripe charges on a plan the grant
|
||||
// replaces, so those two statuses read the decision's inputs under the pool
|
||||
// row. A paused subscription is never wanted paused and makes no read. A
|
||||
// failed read is decideErr, not err: the suspension above stands and the
|
||||
// caller commits it without a decision.
|
||||
func reconcileSuspended(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
billingQ *billing.Queries,
|
||||
stripeQ *internalstripe.Queries,
|
||||
entQ *entitlements.Queries,
|
||||
sub *stripe.Subscription,
|
||||
subUUID uuid.UUID,
|
||||
poolID string,
|
||||
) (wanted bool, decideErr error, err error) {
|
||||
if _, err := entQ.LockPools(ctx, poolID); err != nil {
|
||||
return fmt.Errorf("reconcile: lock pool %s before the suspension: %w", poolID, err)
|
||||
return false, nil, fmt.Errorf("reconcile: lock pool %s before the suspension: %w", poolID, err)
|
||||
}
|
||||
suspended, err := entQ.SyncSourceStatus(ctx, entitlements.SyncSourceStatusParams{
|
||||
Status: "suspended",
|
||||
SubscriptionID: uuid.NullUUID{UUID: subUUID, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: suspend subscription provisions: %w", err)
|
||||
return false, nil, fmt.Errorf("reconcile: suspend subscription provisions: %w", err)
|
||||
}
|
||||
if len(suspended) > 0 {
|
||||
if err := entitlements.MaterializePoolEntitlements(ctx, entQ, poolID); err != nil {
|
||||
return fmt.Errorf("reconcile: rematerialize after suspend: %w", err)
|
||||
return false, nil, fmt.Errorf("reconcile: rematerialize after suspend: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
if sub.Status != stripe.SubscriptionStatusPastDue && sub.Status != stripe.SubscriptionStatusUnpaid {
|
||||
return false, nil, nil
|
||||
}
|
||||
desired, left, err := collectionInputs(ctx, logger, billingQ, stripeQ, entQ, sub, subUUID, poolID)
|
||||
if err != nil {
|
||||
return false, err, nil
|
||||
}
|
||||
return entitlements.CollectionPauseWanted(string(sub.Status), desired, left), nil, nil
|
||||
}
|
||||
|
||||
// collectionInputs reads what the pause rule needs for a subscription whose
|
||||
// items the branch does not mirror: the products of its current items that
|
||||
// have an entitlement set (each item resolved through resolveItem, which
|
||||
// writes nothing), and the products entitlements.DisplacedProducts leaves
|
||||
// alone, from the live provisions, shapes and displacements read under the
|
||||
// pool row the caller holds.
|
||||
func collectionInputs(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
billingQ *billing.Queries,
|
||||
stripeQ *internalstripe.Queries,
|
||||
entQ *entitlements.Queries,
|
||||
sub *stripe.Subscription,
|
||||
subUUID uuid.UUID,
|
||||
poolID string,
|
||||
) (desired []string, left map[string]entitlements.Displacement, err error) {
|
||||
set := make(map[string]int32)
|
||||
if sub.Items != nil {
|
||||
for _, item := range sub.Items.Data {
|
||||
_, product, err := resolveItem(ctx, billingQ, stripeQ, item)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if product.EntitlementSetID.Valid {
|
||||
set[product.ProductID]++
|
||||
}
|
||||
}
|
||||
}
|
||||
desired = sortedProducts(set)
|
||||
live, err := entQ.GetLivePoolProvisionsBySubscriptionID(ctx, uuid.NullUUID{UUID: subUUID, Valid: true})
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("reconcile: list live provisions for subscription: %w", err)
|
||||
}
|
||||
liveByProduct := make(map[string]entitlements.PoolProvision, len(live))
|
||||
for _, p := range live {
|
||||
liveByProduct[p.ProductID] = p
|
||||
}
|
||||
rungs, err := conferralRungs(ctx, entQ, desired)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
left, err = productsLeftAlone(ctx, logger, entQ, desired, rungs, liveByProduct, subUUID, poolID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return desired, left, nil
|
||||
}
|
||||
|
||||
// ReconcileLatestSubscriptionForCustomer lists the customer's most recent
|
||||
@@ -455,13 +595,13 @@ func reconcileItems(
|
||||
subUUID uuid.UUID,
|
||||
poolID string,
|
||||
actor entitlements.Actor,
|
||||
) error {
|
||||
) (conferralOutcome, error) {
|
||||
if sub.Items == nil {
|
||||
return nil
|
||||
return conferralOutcome{}, nil
|
||||
}
|
||||
|
||||
if _, err := entQ.LockPools(ctx, poolID); err != nil {
|
||||
return fmt.Errorf("reconcile: lock pool %s before the resume: %w", poolID, err)
|
||||
return conferralOutcome{}, fmt.Errorf("reconcile: lock pool %s before the resume: %w", poolID, err)
|
||||
}
|
||||
|
||||
// active/trialing: resume any provisions suspended by a prior past_due.
|
||||
@@ -470,12 +610,12 @@ func reconcileItems(
|
||||
SubscriptionID: uuid.NullUUID{UUID: subUUID, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("reconcile: resume subscription provisions: %w", err)
|
||||
return conferralOutcome{}, fmt.Errorf("reconcile: resume subscription provisions: %w", err)
|
||||
}
|
||||
|
||||
items, err := mirrorItems(ctx, logger, billingQ, stripeQ, sub, subscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
|
||||
// 1.6c A schedule's phase change replaces the Stripe item rather than
|
||||
@@ -485,20 +625,20 @@ func reconcileItems(
|
||||
// without an id, since the set mirrorItems collected is then incomplete.
|
||||
if items.allIdentified {
|
||||
if err := endReplacedItems(ctx, logger, billingQ, subscriptionID, items.onSubscription); err != nil {
|
||||
return err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
}
|
||||
|
||||
conferred, err := convergeConferrals(ctx, logger, entQ, items.desired, subUUID, poolID, actor)
|
||||
out, err := convergeConferrals(ctx, logger, entQ, items.desired, subUUID, poolID, actor)
|
||||
if err != nil {
|
||||
return err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
if len(resumed) > 0 || conferred {
|
||||
if len(resumed) > 0 || out.changed {
|
||||
if err := entitlements.MaterializePoolEntitlements(ctx, entQ, poolID); err != nil {
|
||||
return fmt.Errorf("reconcile: materialize entitlements: %w", err)
|
||||
return conferralOutcome{}, fmt.Errorf("reconcile: materialize entitlements: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// mirroredItems is what mirroring a subscription's Stripe items leaves for the
|
||||
@@ -703,7 +843,7 @@ func conferralRungs(ctx context.Context, entQ *entitlements.Queries, products []
|
||||
// another plan took from the subscription and holds is left alone
|
||||
// (core.subscription_displacements), and of two products that share a ladder
|
||||
// only the higher-ranked is conferred (entitlements.ChooseTiers). It reports
|
||||
// whether it wrote anything.
|
||||
// whether it wrote anything, and what the pause rule needs of it.
|
||||
func convergeConferrals(
|
||||
ctx context.Context,
|
||||
logger *slog.Logger,
|
||||
@@ -712,11 +852,11 @@ func convergeConferrals(
|
||||
subUUID uuid.UUID,
|
||||
poolID string,
|
||||
actor entitlements.Actor,
|
||||
) (bool, error) {
|
||||
) (conferralOutcome, error) {
|
||||
// Live state: the subscription's non-ended provisions, one per product.
|
||||
live, err := entQ.GetLivePoolProvisionsBySubscriptionID(ctx, uuid.NullUUID{UUID: subUUID, Valid: true})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reconcile: list live provisions for subscription: %w", err)
|
||||
return conferralOutcome{}, fmt.Errorf("reconcile: list live provisions for subscription: %w", err)
|
||||
}
|
||||
liveByProduct := make(map[string]entitlements.PoolProvision, len(live))
|
||||
for _, p := range live {
|
||||
@@ -726,11 +866,11 @@ func convergeConferrals(
|
||||
order := sortedProducts(desired)
|
||||
rungs, err := conferralRungs(ctx, entQ, order)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
left, err := productsLeftAlone(ctx, logger, entQ, order, rungs, liveByProduct, subUUID, poolID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
remaining := make([]string, 0, len(order))
|
||||
for _, productID := range order {
|
||||
@@ -756,13 +896,29 @@ func convergeConferrals(
|
||||
for _, productID := range kept {
|
||||
wrote, err := conferOrBound(ctx, entQ, liveByProduct, productID, desired[productID], subUUID, poolID, actor)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return conferralOutcome{}, err
|
||||
}
|
||||
changed = changed || wrote
|
||||
}
|
||||
|
||||
ended, err := endSurplusConferrals(ctx, entQ, desired, subUUID, actor)
|
||||
return changed || ended, err
|
||||
return conferralOutcome{
|
||||
changed: changed || len(ended) > 0,
|
||||
left: left,
|
||||
desired: order,
|
||||
ended: ended,
|
||||
}, err
|
||||
}
|
||||
|
||||
// conferralOutcome is what convergeConferrals leaves for the passes after it:
|
||||
// whether it wrote anything, the products it left alone for another plan's
|
||||
// hold, the desired products in ascending order, and the ids of the
|
||||
// provisions it ended because their product is no longer desired.
|
||||
type conferralOutcome struct {
|
||||
changed bool
|
||||
left map[string]entitlements.Displacement
|
||||
desired []string
|
||||
ended []string
|
||||
}
|
||||
|
||||
// productsLeftAlone reads the subscription's displacements, takes as missing
|
||||
@@ -850,19 +1006,19 @@ func conferOrBound(
|
||||
|
||||
// endSurplusConferrals re-reads the live provisions (a same-ladder confer may
|
||||
// have superseded a prior product) and ends any still-live provision no
|
||||
// longer desired. It reports whether it ended anything.
|
||||
// longer desired. It returns the ids of the provisions it ended.
|
||||
func endSurplusConferrals(
|
||||
ctx context.Context,
|
||||
entQ *entitlements.Queries,
|
||||
desired map[string]int32,
|
||||
subUUID uuid.UUID,
|
||||
actor entitlements.Actor,
|
||||
) (bool, error) {
|
||||
) ([]string, error) {
|
||||
postLive, err := entQ.GetLivePoolProvisionsBySubscriptionID(ctx, uuid.NullUUID{UUID: subUUID, Valid: true})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reconcile: re-list live provisions for subscription: %w", err)
|
||||
return nil, fmt.Errorf("reconcile: re-list live provisions for subscription: %w", err)
|
||||
}
|
||||
ended := false
|
||||
var ended []string
|
||||
for _, p := range postLive {
|
||||
if _, ok := desired[p.ProductID]; ok {
|
||||
continue
|
||||
@@ -878,7 +1034,7 @@ func endSurplusConferrals(
|
||||
}); err != nil {
|
||||
return ended, fmt.Errorf("reconcile: end surplus provision %s: %w", p.ProvisionID, err)
|
||||
}
|
||||
ended = true
|
||||
ended = append(ended, p.ProvisionID)
|
||||
}
|
||||
return ended, nil
|
||||
}
|
||||
|
||||
@@ -332,3 +332,48 @@ func TestSubscriptionBacksASuspendedLadder(t *testing.T) {
|
||||
t.Error("SubscriptionBacksLadder = false for a suspended position")
|
||||
}
|
||||
}
|
||||
|
||||
// A past_due subscription a grant displaced is paused too, and the invoice
|
||||
// open before the grant is left as it is (design D6, task 3.7).
|
||||
func TestApplyCollection_PausesAPastDueSubscription(t *testing.T) {
|
||||
database, fx, mock, _ := grantOver(t, false)
|
||||
mock.Sub.Status = stripe.SubscriptionStatusPastDue
|
||||
stripeAppliesCollection(mock, fx.stripeSubID)
|
||||
|
||||
if err := applyCollection(t, database, discardLogger(), fx); err != nil {
|
||||
t.Fatalf("ApplySubscriptionCollection: %v", err)
|
||||
}
|
||||
posts := subscriptionPosts(mock, fx)
|
||||
if len(posts) != 1 || posts[0].Form.Get("pause_collection[behavior]") != "void" {
|
||||
t.Errorf("the past-due subscription's pause call = %v", posts)
|
||||
}
|
||||
for _, c := range mock.Calls {
|
||||
if strings.HasSuffix(c.Path, "/void") {
|
||||
t.Errorf("the pause voided an invoice: %v", c.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A price with no mapping fails the decision's reads, not the suspension: the
|
||||
// past-due subscription still stops delivering and no pause is requested.
|
||||
func TestReconcile_APastDueSubscriptionWithAnUnmappedPriceIsStillSuspended(t *testing.T) {
|
||||
database, fx, mock := subscribed(t)
|
||||
mock.Sub.Items.Data = append(mock.Sub.Items.Data, &stripe.SubscriptionItem{
|
||||
ID: "si_unmapped_" + fx.stripeSubID, Quantity: 1, Price: &stripe.Price{ID: "price_unmapped_" + fx.stripeSubID}})
|
||||
mock.Sub.Status = stripe.SubscriptionStatusPastDue
|
||||
|
||||
if err := fulfillment.ReconcileSubscription(context.Background(), database, discardLogger(), stripetest.KeyMode(), fx.stripeSubID, "test:suspend"); err != nil {
|
||||
t.Fatalf("the past-due subscription with an unmapped price was not suspended: %v", err)
|
||||
}
|
||||
core := coreSubID(t, database, fx.stripeSubID)
|
||||
if got := subscriptionStatus(t, database, core); got != "past_due" {
|
||||
t.Errorf("the past-due subscription with an unmapped price was not suspended: the row reads %q", got)
|
||||
}
|
||||
if got := provisionStatus(t, database, core); got != "suspended" {
|
||||
t.Errorf("the past-due subscription with an unmapped price was not suspended: the provisions read %q", got)
|
||||
}
|
||||
if n := scalarInt(t, database,
|
||||
`SELECT count(*) FROM core.outbox WHERE action_type = 'reconcile_subscription' AND payload->>'subscription_id' = $1`, core); n != 0 {
|
||||
t.Errorf("the undecided reconcile wrote %d outbox entries, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ ListSubscriptionDisplacements
|
||||
GetLivePoolProvisionsBySubscriptionID
|
||||
ListActiveScheduledChangesBySubscription
|
||||
GetPriceMappingByStripeID
|
||||
INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)
|
||||
commit
|
||||
== logs
|
||||
INFO reconcile: product not conferred; another plan holds its ladder subscription_id=<subscription> product_id=<product:Plan> plan_ladder_id=<ladder:Ladder> holder_provision_id=<provision:Plus grant>
|
||||
|
||||
+1
@@ -29,6 +29,7 @@ ListSubscriptionDisplacements
|
||||
GetLivePoolProvisionsBySubscriptionID
|
||||
ListActiveScheduledChangesBySubscription
|
||||
GetPriceMappingByStripeID
|
||||
INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)
|
||||
commit
|
||||
== logs
|
||||
INFO reconcile: product not conferred; another plan holds its ladder subscription_id=<subscription> product_id=<product:Plan> plan_ladder_id=<ladder:Ladder> holder_provision_id=<provision:Plus grant>
|
||||
|
||||
@@ -18,6 +18,12 @@ CreateSubscriptionChange
|
||||
LockResourcePool
|
||||
SELECT core.sync_source_status($1, $2, $3, $4, $5)
|
||||
<materialize>
|
||||
GetPriceMappingByStripeID
|
||||
GetPrice
|
||||
GetProductByID
|
||||
GetLivePoolProvisionsBySubscriptionID
|
||||
ListConferralShapes
|
||||
ListSubscriptionDisplacements
|
||||
commit
|
||||
== logs
|
||||
== rows
|
||||
|
||||
Vendored
+1
@@ -30,6 +30,7 @@ GetLivePoolProvisionsBySubscriptionID
|
||||
ListActiveScheduledChangesBySubscription
|
||||
GetPriceMappingByStripeID
|
||||
MarkScheduledChangeApplied
|
||||
INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)
|
||||
commit
|
||||
stripe POST /v1/subscription_schedules/sub_sched_mock/release
|
||||
probe: the subscription lock is free
|
||||
|
||||
@@ -12,8 +12,11 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
||||
internalstripe "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/store"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/workflows/common"
|
||||
"github.com/google/uuid"
|
||||
stripego "github.com/stripe/stripe-go/v81"
|
||||
"github.com/stripe/stripe-go/v81/customer"
|
||||
"github.com/stripe/stripe-go/v81/price"
|
||||
@@ -322,6 +325,8 @@ func (a *OutboxActivities) executeAction(ctx context.Context, entry OutboxEntry)
|
||||
return a.executeCreateStripeProduct(ctx, entry)
|
||||
case "create_stripe_price":
|
||||
return a.executeCreateStripePrice(ctx, entry)
|
||||
case entitlements.ReconcileSubscriptionAction:
|
||||
return a.executeReconcileSubscription(ctx, entry)
|
||||
default:
|
||||
a.Logger.Info("outbox action: unrecognized type (no-op)",
|
||||
slog.Int64("entry_id", entry.ID),
|
||||
@@ -330,6 +335,28 @@ func (a *OutboxActivities) executeAction(ctx context.Context, entry OutboxEntry)
|
||||
}
|
||||
}
|
||||
|
||||
// ReconcileSubscriptionPayload is the outbox payload of a
|
||||
// reconcile_subscription entry: the core subscription to reconcile.
|
||||
type ReconcileSubscriptionPayload struct {
|
||||
SubscriptionID string `json:"subscription_id"`
|
||||
}
|
||||
|
||||
// executeReconcileSubscription reconciles the entry's subscription and makes
|
||||
// the Stripe call its collection pause needs (fulfillment.ApplySubscriptionCollection).
|
||||
// The call needs no idempotency key of its own: it sets a state, so repeating it
|
||||
// is harmless. A missing or malformed subscription_id can never succeed, so it
|
||||
// is returned non-retryable.
|
||||
func (a *OutboxActivities) executeReconcileSubscription(ctx context.Context, entry OutboxEntry) error {
|
||||
var payload ReconcileSubscriptionPayload
|
||||
if err := json.Unmarshal(entry.Payload, &payload); err != nil || payload.SubscriptionID == "" || uuid.Validate(payload.SubscriptionID) != nil {
|
||||
return temporal.NewNonRetryableApplicationError(
|
||||
fmt.Sprintf("outbox entry %d: reconcile_subscription payload has no subscription_id", entry.ID),
|
||||
"MalformedOutboxPayload", err)
|
||||
}
|
||||
return classifyStripeError(fulfillment.ApplySubscriptionCollection(ctx, a.DB, a.Logger, sdkKeyMode(),
|
||||
payload.SubscriptionID, fmt.Sprintf("outbox:reconcile_subscription:%d", entry.ID)))
|
||||
}
|
||||
|
||||
// executeCreateStripeCustomer parses the outbox payload, creates a Stripe
|
||||
// Customer via the API, and writes a customer_mappings row with sync_status = 'synced'.
|
||||
func (a *OutboxActivities) executeCreateStripeCustomer(ctx context.Context, entry OutboxEntry) error {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
||||
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
||||
|
||||
package workflows_test
|
||||
|
||||
// The outbox's reconcile_subscription action (openspec change
|
||||
// grant-pauses-subscription-billing, design D1, task 3.7): a reconcile that
|
||||
// makes the Stripe call a collection pause needs.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
stripe "github.com/stripe/stripe-go/v81"
|
||||
"go.temporal.io/sdk/temporal"
|
||||
"go.temporal.io/sdk/testsuite"
|
||||
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/entitlements"
|
||||
stripewf "git.coopcloud.tech/wiki-cafe/member-console/internal/integrations/stripe/workflows"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/stripetest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/dbtest"
|
||||
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit/world"
|
||||
)
|
||||
|
||||
// displacedSubscription is a subscription on a ladder's lower tier that a grant
|
||||
// of the higher tier displaced, mapped to Stripe, with the mock installed to
|
||||
// answer its fetch as active.
|
||||
func displacedSubscription(t *testing.T, database *sql.DB) (coreID, stripeID string, mock *stripetest.MockBackend) {
|
||||
t.Helper()
|
||||
w := world.New(t, database)
|
||||
o := w.Org("Reconcile Entry", w.OrgType("rse"), w.Person("Owner"))
|
||||
account := w.BillingAccount(o, "Reconcile Entry")
|
||||
w.MapAccount(account)
|
||||
plan, pro := w.Product("Plan"), w.Product("Pro")
|
||||
w.Rule(plan, siteLimit(1))
|
||||
w.Rule(pro, siteLimit(5))
|
||||
price := w.Price(plan, 1200)
|
||||
w.MapPrice(price)
|
||||
w.Ladder("Reconcile Entry", plan, pro)
|
||||
sub := w.Subscribe(o, world.SubOpts{}, plan)
|
||||
w.MapSubscription(sub)
|
||||
w.Issue(o, pro, world.IssueOpts{})
|
||||
|
||||
stripeID = "sub_" + sub.ID
|
||||
mock = &stripetest.MockBackend{Sub: &stripe.Subscription{
|
||||
ID: stripeID,
|
||||
Status: stripe.SubscriptionStatusActive,
|
||||
Customer: &stripe.Customer{ID: "cus_" + account.ID},
|
||||
CurrentPeriodStart: 1700000000,
|
||||
CurrentPeriodEnd: 1702600000,
|
||||
Items: &stripe.SubscriptionItemList{Data: []*stripe.SubscriptionItem{
|
||||
{ID: "si_" + sub.ID, Quantity: 1, Price: &stripe.Price{ID: "price_" + price.ID}},
|
||||
}},
|
||||
}}
|
||||
t.Cleanup(stripetest.Install(mock))
|
||||
return sub.ID, stripeID, mock
|
||||
}
|
||||
|
||||
func runOutboxEntry(t *testing.T, database *sql.DB, payload string) error {
|
||||
t.Helper()
|
||||
var id int64
|
||||
if err := database.QueryRowContext(context.Background(),
|
||||
`INSERT INTO core.outbox (provider, action_type, payload) VALUES ('stripe', $1, $2) RETURNING id`,
|
||||
entitlements.ReconcileSubscriptionAction, payload).Scan(&id); err != nil {
|
||||
t.Fatalf("insert the outbox entry: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = database.ExecContext(context.Background(), `DELETE FROM core.outbox WHERE id = $1`, id) })
|
||||
acts := stripewf.NewOutboxActivities(database, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
var suite testsuite.WorkflowTestSuite
|
||||
env := suite.NewTestActivityEnvironment()
|
||||
env.RegisterActivity(acts)
|
||||
_, err := env.ExecuteActivity(acts.ExecuteOutboxEntry, stripewf.OutboxEntry{ID: id})
|
||||
return err
|
||||
}
|
||||
|
||||
func nonRetryable(err error) bool {
|
||||
var app *temporal.ApplicationError
|
||||
return errors.As(err, &app) && app.NonRetryable()
|
||||
}
|
||||
|
||||
func TestOutbox_ReconcileSubscriptionAction(t *testing.T) {
|
||||
database := dbtest.Open(t)
|
||||
coreID, stripeID, mock := displacedSubscription(t, database)
|
||||
mock.Handle = func(c stripetest.Call) (any, error, bool) {
|
||||
if c.Method == "POST" {
|
||||
mock.Sub.PauseCollection = &stripe.SubscriptionPauseCollection{Behavior: stripe.SubscriptionPauseCollectionBehaviorVoid}
|
||||
mock.Sub.Metadata = map[string]string{"member_console_collection": "paused_for_grant"}
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
if err := runOutboxEntry(t, database, fmt.Sprintf(`{"subscription_id":%q}`, coreID)); err != nil {
|
||||
t.Fatalf("executeAction(reconcile_subscription): %v", err)
|
||||
}
|
||||
posts := mock.CallsTo("POST", "/v1/subscriptions/"+stripeID)
|
||||
if len(posts) != 1 || posts[0].Form.Get("pause_collection[behavior]") != "void" {
|
||||
t.Errorf("executeAction(reconcile_subscription) sent %v, want the pause", posts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutbox_ReconcileSubscriptionActionRefusals(t *testing.T) {
|
||||
database := dbtest.Open(t)
|
||||
coreID, _, mock := displacedSubscription(t, database)
|
||||
|
||||
for _, payload := range []string{`{"subscription_id":""}`, `{"subscription_id":"not-a-uuid"}`} {
|
||||
if err := runOutboxEntry(t, database, payload); err == nil || !nonRetryable(err) {
|
||||
t.Errorf("the malformed payload %s is retryable: %v", payload, err)
|
||||
}
|
||||
}
|
||||
mock.Handle = func(c stripetest.Call) (any, error, bool) {
|
||||
if c.Method == "POST" {
|
||||
return nil, &stripe.Error{HTTPStatusCode: 400, Msg: "bad request"}, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
if err := runOutboxEntry(t, database, fmt.Sprintf(`{"subscription_id":%q}`, coreID)); err == nil || !nonRetryable(err) {
|
||||
t.Errorf("a 400 from Stripe is retryable: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -259,7 +259,8 @@ func (q DeliveryQueue) NeedsAttention() bool { return q.DeadLetter > 0 }
|
||||
func (q DeliveryQueue) Queued() int64 { return q.Pending + q.Retrying }
|
||||
|
||||
// loadDeliveryQueue probes the shared integration outbox (core.outbox).
|
||||
// Today only Stripe enqueues into it (operator_billing.go); an unavailable
|
||||
// Only Stripe actions are enqueued into it today, by operator_billing.go and
|
||||
// by every caller of entitlements.RequestSubscriptionReconcile; an unavailable
|
||||
// probe leaves Available false rather than a set of zeroes neither caller
|
||||
// could stand behind. A nil querier (a handler built without one, as some
|
||||
// tests do) also degrades to unavailable rather than panicking.
|
||||
|
||||
@@ -167,7 +167,7 @@ Pick: (a), `entitlements.DeliverDisplacedSubscriptionsTx(ctx, tx, poolID, except
|
||||
Reason: #270 asks for the same transaction and no Stripe event. (b) confers a default and supersedes it, writing two transitions and pushing an entitlement change to every integration, and keeps the default while Temporal is down. (c) leaves the ladder vacant for those seconds.
|
||||
|
||||
Shape:
|
||||
- Each act calls it when it ended at least one provision of the ending plan, after `ResumeReplacedGrantsTx` and before `ReapplyDefaultsIfVacant`, with the reason `subscription-delivery:revocation:<grant id>`, `subscription-delivery:expiration:<grant id>` or `subscription-delivery:subscription:<subscription id>`. An act that ended nothing delivers nothing, as it resumes nothing, so a replay is inert.
|
||||
- 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>`, `subscription-delivery:subscription:<subscription id>` or `subscription-delivery:dropped:<subscription id>`. The last two differ by the code path that writes them: the holding subscription's end (`reconcileEnded`, after `core.end_conferral`) writes `subscription-delivery:subscription:`, and the holding subscription's reconcile while it stays live (the active branch, after `endSurplusConferrals` ended a surplus provision because the subscription dropped the item) writes `subscription-delivery:dropped:`. 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, 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.
|
||||
@@ -332,7 +332,7 @@ The grant form's warning, `issueGrantSupersedeWarning`, reads "Products marked
|
||||
|
||||
The Overview: `SumMonthlyRecurringByCurrency` gains `AND s.pause_collection_behavior IS NULL`. The caption is unchanged: a subscription whose collection is paused keeps its `active` status and is counted as active.
|
||||
|
||||
The Tier changes list reads the delivery's three reasons through `humanizeTransitionReason` (`internal/server/operator_tier_changes.go:22-58`), for actor `system` only, as a resumption's are (Copy, T1 to T3).
|
||||
The Tier changes list reads the delivery's four reasons through `humanizeTransitionReason` (`internal/server/operator_tier_changes.go:22-58`), for actor `system` only, as a resumption's are (Copy, T1 to T4).
|
||||
|
||||
### D17. The displacement rule moves into `internal/entitlements`
|
||||
|
||||
@@ -522,7 +522,8 @@ 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 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 |
|
||||
| T3 | The same after a subscription that held the ladder ended | `Subscription delivers again after a subscription ended` | approved; the holding subscription ended |
|
||||
| T4 | The same after a live subscription dropped the item that held the ladder (reason `subscription-delivery:dropped:`; only an edit in the Stripe Dashboard reaches it) | `Subscription delivers again after a subscription dropped its tier` | approved |
|
||||
|
||||
`<ladders>` and `<holder>` are as `displacementTitle` fills them today. `<grant holder>` is `a grant holds` when one grant provision holds every ladder its sentence names and `grants hold` when several do (question 5); a paused sentence names no other holder, since the rule pauses only under grants.
|
||||
|
||||
@@ -600,13 +601,9 @@ A subscription the console paused stays paused under the old binary, which never
|
||||
|
||||
## Open questions
|
||||
|
||||
Question 13 is open; the rest are settled.
|
||||
All questions 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):
|
||||
**Settled** (1 and 11 by the designer, 2 to 10, 12 and 13 with the maintainer):
|
||||
|
||||
1. The paid card while the pause is pending or failed: the mirror decides, with the existing lines (M5).
|
||||
2. The switch's label on the granted tier's card: the existing "Upgrade" (M6).
|
||||
@@ -615,6 +612,7 @@ Question 13 is open; the rest are settled.
|
||||
5. The paused titles under several grants: "grants hold {ladders}", and "a grant holds" for one grant (O0 to O2).
|
||||
6. The cancelled paused card: M0, Keep plan and the heading's existing "cancels on {date}" badge, no new string; a downgrade scheduled before the grant reads M8.
|
||||
7. The Tier changes labels: T1 to T3 as written.
|
||||
13. A fourth label for a tier dropped by a live subscription (option B).
|
||||
8. A grant of the subscription's own tier: the card reads M0 with the shared name ("Paused while Plus is granted"), and Cancel plan's confirmation reads M9.
|
||||
9. The switch's proration credit for voided time: accepted until #280, D14's fifth cost, named in `docs/stripe.md` (task 11.5).
|
||||
10. An item with no entitlement set rides the pause: stated in D2 and in `docs/stripe.md` (task 4.6).
|
||||
|
||||
@@ -53,7 +53,7 @@ None.
|
||||
- `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"; 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), "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).
|
||||
- `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 four 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).
|
||||
|
||||
+6
-1
@@ -101,7 +101,7 @@ The composite's plan audit list SHALL be headed "Tier changes" (the term "positi
|
||||
|
||||
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.
|
||||
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; Subscription delivers again after a subscription dropped its tier; 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
|
||||
|
||||
@@ -151,6 +151,11 @@ The Reason cell SHALL read in words. A row whose reason the machinery wrote show
|
||||
- **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 subscription dropped its tier
|
||||
|
||||
- **WHEN** a live subscription that held a ladder drops the item that held it in the Stripe Dashboard while another subscription waits on that ladder
|
||||
- **THEN** the waiting subscription's "Started" row reads "Subscription delivers again after a subscription dropped its tier"
|
||||
|
||||
#### Scenario: A subscription delivers again after a revocation
|
||||
|
||||
- **WHEN** an operator revokes the grant that displaced a subscription
|
||||
|
||||
@@ -41,13 +41,13 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
|
||||
## 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, 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.
|
||||
- [ ] 3.7 Tests:
|
||||
- [x] 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.
|
||||
- [x] 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, "")`).
|
||||
- [x] 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.
|
||||
- [x] 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.
|
||||
- [x] 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.
|
||||
- [x] 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.
|
||||
- [x] 3.7 Tests:
|
||||
- `TestCollectionPauseWanted` (`internal/entitlements/collection_test.go`, no database), rows through `checkPauseWanted`: `active, every product left alone by grants` (true); `trialing, the same` (true); `past_due` and `unpaid`, the same (true); `paused`, `incomplete`, `canceled` (false); `no product with a set` (false); `one product left alone, one not` (false); `left alone by another subscription` (false); `left alone by a grant and by a purchase` (false). Failure text: `CollectionPauseWanted(%s) = %v, want %v`.
|
||||
- `TestDecideCollection` (`internal/fulfillment/collection_test.go`, no database), one row per line of design D2's table, with the stale marker under both wants and the console's pause with `mark_uncollectible`. Failure text: `decideCollection(%s) = %v, %v, want %v, %v`.
|
||||
- `TestReconcile_AGrantOverTheSubscriptionRequestsThePause` (`internal/fulfillment/displaced_subscription_test.go`): the fixture of `TestReconcile_AGrantOverTheSubscriptionKeepsTheLadder`, reconciled by `ReconcileSubscription`; one `core.outbox` row with `action_type = 'reconcile_subscription'` and the subscription's id, and no `POST /v1/subscriptions/` call. Failure texts: `reconcile_subscription entries for %s = %d, want 1`; `the reconcile called Stripe for the pause: %v`.
|
||||
@@ -60,9 +60,9 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `TestApplyCollection_NoMappingIsASkip`: a subscription with no Stripe mapping; nil, no Stripe call, L3. Failure text: `an unmapped subscription = %v, want nil`.
|
||||
- `TestApplyCollection_PausesAPastDueSubscription` (`internal/fulfillment/suspended_subscription_test.go`): a `past_due` subscription a grant displaced; the pause call is sent, and nothing voids its open invoice. Failure text: `the past-due subscription's pause call = %v`.
|
||||
- `TestOutbox_ReconcileSubscriptionAction` (`internal/integrations/stripe/workflows/outbox_activity_test.go`): an entry with the action runs `ApplySubscriptionCollection`'s path against the mock (the pause call sent), a malformed payload is non-retryable, and a 400 from Stripe classifies as non-retryable. Failure texts: `executeAction(reconcile_subscription) sent %v, want the pause`; `a malformed payload is retryable`.
|
||||
- [ ] 3.8 Trace goldens, rewritten with `-update` and read: `internal/fulfillment/testdata/reconcile_trace/grant_over_subscription.golden`, `grant_over_suspended_recovery.golden` and `internal/fulfillment/testdata/scheduled_change_trace/downgrade_lands_while_displaced.golden` each gain the line `INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)` before `commit`, and their `== rows` gain nothing (the trace prints no outbox rows); `reconcile_trace/past_due.golden` gains the suspended branch's reads after the suspension and its `<materialize>` line, before `commit` (`GetPriceMappingByStripeID`, `GetPrice`, `GetProductByID`, `GetLivePoolProvisionsBySubscriptionID`, `ListConferralShapes`, `ListSubscriptionDisplacements`), and no insert, because no grant holds its ladder; it is the only trace whose subscription is `past_due` or `unpaid`. Any other golden's change is a stop.
|
||||
- [ ] 3.9 Docs: `docs/stripe.md`, the restricted-key paragraph after "Plan changes" names `POST /v1/subscriptions/{id}` with `pause_collection` among the calls the console makes, a permission the upgrade already needs; "Do not do in Stripe" gains: **Do not remove the console's collection marker** (metadata `member_console_collection`) or resume collection of a subscription the console paused; the console pauses it again while a grant holds its ladder, and a subscription paused without the marker is left as it is. `test/AGENTS.md:304-305` (the key's scopes list, which reads only) gains the subscription write the pause needs. `docs/database-locks.md`, "Subscription reconcile", gains the suspended branch's reads under the pool row and the outbox's call after the commit with no lock held.
|
||||
- [ ] 3.10 Breaks:
|
||||
- [x] 3.8 Trace goldens, rewritten with `-update` and read: `internal/fulfillment/testdata/reconcile_trace/grant_over_subscription.golden`, `grant_over_suspended_recovery.golden` and `internal/fulfillment/testdata/scheduled_change_trace/downgrade_lands_while_displaced.golden` each gain the line `INSERT INTO core.outbox (provider, action_type, payload) VALUES ($1, $2, $3)` before `commit`, and their `== rows` gain nothing (the trace prints no outbox rows); `reconcile_trace/past_due.golden` gains the suspended branch's reads after the suspension and its `<materialize>` line, before `commit` (`GetPriceMappingByStripeID`, `GetPrice`, `GetProductByID`, `GetLivePoolProvisionsBySubscriptionID`, `ListConferralShapes`, `ListSubscriptionDisplacements`), and no insert, because no grant holds its ladder; it is the only trace whose subscription is `past_due` or `unpaid`. Any other golden's change is a stop.
|
||||
- [x] 3.9 Docs: `docs/stripe.md`, the restricted-key paragraph after "Plan changes" names `POST /v1/subscriptions/{id}` with `pause_collection` among the calls the console makes, a permission the upgrade already needs; "Do not do in Stripe" gains: **Do not remove the console's collection marker** (metadata `member_console_collection`) or resume collection of a subscription the console paused; the console pauses it again while a grant holds its ladder, and a subscription paused without the marker is left as it is. `test/AGENTS.md:304-305` (the key's scopes list, which reads only) gains the subscription write the pause needs. `docs/database-locks.md`, "Subscription reconcile", gains the suspended branch's reads under the pool row and the outbox's call after the commit with no lock held.
|
||||
- [x] 3.10 Breaks:
|
||||
- the rule ignoring the holder's source (`d.HolderSource != "grant"` test removed from `CollectionPauseWanted`): caught by `TestCollectionPauseWanted`, `want_new` `CollectionPauseWanted(left alone by another subscription) =`;
|
||||
- the rule satisfied by one product (`return false` for a desired product missing from `left` replaced by `continue`): caught by the same, `want_new` `CollectionPauseWanted(one product left alone, one not) =`;
|
||||
- a foreign pause cleared (the marker test removed from the clear line of `decideCollection`): caught by `TestDecideCollection`, `want_new` `decideCollection(not paused, foreign) =`, and by `TestApplyCollection_LeavesAForeignPause`, `want_new` `a pause made outside the console was changed`;
|
||||
@@ -74,7 +74,7 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- the suspended branch not deciding (the `collectionInputs` call guarded by `false`): caught by `TestApplyCollection_PausesAPastDueSubscription`, `want_new` `the past-due subscription's pause call =`, and by `TestReconcileTrace/past_due`, `want_new` `testdata/reconcile_trace/past_due.golden differs from what the code produced`;
|
||||
- the second run after the call dropped: caught by `TestApplyCollection_DecidesAgainAfterItsCall`, `want_new` `fetches =`;
|
||||
- the executor's case removed: caught by `TestOutbox_ReconcileSubscriptionAction`, `want_new` `executeAction(reconcile_subscription) sent`.
|
||||
- [ ] 3.11 `make screens`: no change.
|
||||
- [x] 3.11 `make screens`: no change.
|
||||
|
||||
## 4. Every act that can change who holds a ladder asks for a reconcile
|
||||
|
||||
@@ -159,8 +159,8 @@ 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` 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.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, the provisions `core.end_conferral` ended and the reason `subscription-delivery:subscription:<subscription id>`; the active branch calls it after `endSurplusConferrals` when that ended one, with the subscription excepted, the provisions `endSurplusConferrals` ended, which it returns (3.3), and the reason `subscription-delivery:dropped:<subscription id>` (the subscription is still live; only a Dashboard edit reaches it). `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 four prefixes, for actor `system`, read T1, T2, T3 and T4 (`subscription-delivery:dropped:` reads "Subscription delivers again after a subscription dropped its tier").
|
||||
- [ ] 7.5 Tests (`internal/entitlements/subscription_delivery_db_test.go`):
|
||||
- `TestDeliverDisplaced_ARevocationDeliversTheSubscription`: the revocation's transaction confers Plus sourced by S, and no default is conferred. Failure texts: `after the revocation, S holds %v on the ladder, want Plus`; `the floor conferred the default over a subscription it should have delivered`.
|
||||
- `TestDeliverDisplaced_AnExpiryDeliversTheSubscription`. Failure text: `after the expiry, S holds %v, want Plus`.
|
||||
@@ -172,8 +172,9 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- `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, 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, 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.
|
||||
- `TestDeliverDisplaced_ADroppedItemDeliversTheWaitingSubscription` (`internal/fulfillment`): S1 holds a ladder and stays active, S2 waits on it, S1's item for that tier is dropped and its reconcile ends the surplus provision; S2's conferral carries the reason `subscription-delivery:dropped:<S1>`. Failure text: `after S1 dropped the item, S2's delivery reason = %q, want the dropped prefix`.
|
||||
- `TestHumanizeTransitionReason` rows for the four 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, 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 T4 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`;
|
||||
@@ -186,6 +187,8 @@ Sections 1 to 12 are one commit each, and their items are that commit's parts; s
|
||||
- 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 active branch writing the ended prefix `subscription-delivery:subscription:` instead of `subscription-delivery:dropped:`: caught by `TestDeliverDisplaced_ADroppedItemDeliversTheWaitingSubscription`, `want_new` `after S1 dropped the item, S2's delivery reason =`;
|
||||
- the T4 label mapped to T3's string: caught by `TestHumanizeTransitionReason`, `want_new` `humanizeTransitionReason("subscription-delivery:dropped:`;
|
||||
- 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.
|
||||
|
||||
|
||||
+2
-1
@@ -302,7 +302,8 @@ Replay a past event with `stripe events resend <evt_id>`. Forwarding is
|
||||
account-global — see the parallel-stack constraint below.
|
||||
|
||||
The app's restricted key (`rk_`) must include **read** scope for *Subscriptions*,
|
||||
*Invoices* and *Charges* (plus *Customers* and *Prices*). Subscription
|
||||
*Invoices* and *Charges* (plus *Customers* and *Prices*), and **write** scope
|
||||
for *Subscriptions*, which setting or clearing a collection pause needs. Subscription
|
||||
fulfillment refetches authoritative state from the Stripe API rather than
|
||||
trusting the webhook payload (OpenSpec change `stripe-fulfillment-reconcile`),
|
||||
and invoice events read the invoice, its lines and its payment intent's
|
||||
|
||||
Reference in New Issue
Block a user