console: reconcile payments hourly, from the webhook too
billingMoneyPass runs after the subscription sync in the billing worker's round (billingRound). reconcilePayments reads balance movements from the cursor less an hour (or from the account's opening, the backfill) in 31-day windows, halving on an incomplete list down to one hour, records each charge's movements via one charge read and fees from the movement, and moves the cursor only past a fully recorded window. A payment webhook event records its charge (503 on error). The Fake gains MoneyErr (the money reads only) and ChargeErr (one charge).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+740
−8
internal/billing/billingtest/fake.go+5 −0internal/billing/billingtest/fake_money.go+18 −3internal/billing/billingtest/fake_money_test.go+40 −0internal/console/billingmoneypass.go+160 −0internal/console/billingmoneypass_test.go+440 −0internal/console/billingpass.go+12 −3internal/console/billingwebhook.go+11 −1internal/console/billingwebhook_test.go+53 −0internal/console/jobs_test.go+1 −1
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index ee3c7f550..011a8fbc3 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -147,6 +147,11 @@ type Fake struct { |
| Movements []billing.Movement |
| Charges map[string]billing.ChargeRecord |
| AccountOpened time.Time |
| + // MoneyErr fails only the three money reads (MoneyMovements, |
| + // ChargePayments, AccountCreated): a key without their permissions. |
| + MoneyErr error |
| + // ChargeErr fails ChargePayments for one charge only. |
| + ChargeErr map[string]error |
| // CallsBy counts requests by method name: "Subscription", |
| // "CheckoutSubscription", "Check", "Send", "Checkout", "PortalURL", |
diff --git a/internal/billing/billingtest/fake_money.go b/internal/billing/billingtest/fake_money.go| index e9ac402c2..ac97700e7 100644 |
| --- a/internal/billing/billingtest/fake_money.go |
| +++ b/internal/billing/billingtest/fake_money.go |
| @@ -13,7 +13,7 @@ import ( |
| // MoneyMovements pages through the Movements at or after from and before |
| // to, oldest first (ties by id), one counted request per page under |
| // "MoneyMovements". More than billing.MaxListPages pages is |
| -// billing.ErrIncomplete. |
| +// billing.ErrIncomplete. Err or MoneyErr fail it. |
| func (f *Fake) MoneyMovements(ctx context.Context, from, to time.Time) ([]billing.Movement, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| @@ -35,6 +35,11 @@ func (f *Fake) MoneyMovements(ctx context.Context, from, to time.Time) ([]billin |
| ids[i] = m.ID |
| byID[m.ID] = m |
| } |
| + if f.MoneyErr != nil && f.Err == nil { |
| + f.begin("MoneyMovements") |
| + f.end() |
| + return nil, f.MoneyErr |
| + } |
| out := []billing.Movement{} |
| if err := f.list(ctx, "MoneyMovements", ids, func(id string) { |
| out = append(out, byID[id]) |
| @@ -44,7 +49,8 @@ func (f *Fake) MoneyMovements(ctx context.Context, from, to time.Time) ([]billin |
| return out, nil |
| } |
| -// ChargePayments returns Charges[charge], or billing.ErrNotFound. |
| +// ChargePayments returns Charges[charge], or billing.ErrNotFound; Err, |
| +// MoneyErr or ChargeErr[charge] fail it. |
| func (f *Fake) ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| @@ -53,6 +59,12 @@ func (f *Fake) ChargePayments(ctx context.Context, charge string) (billing.Charg |
| if f.Err != nil { |
| return billing.ChargeRecord{}, f.Err |
| } |
| + if f.MoneyErr != nil { |
| + return billing.ChargeRecord{}, f.MoneyErr |
| + } |
| + if err := f.ChargeErr[charge]; err != nil { |
| + return billing.ChargeRecord{}, err |
| + } |
| if f.timedOut() { |
| return billing.ChargeRecord{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| } |
| @@ -65,7 +77,7 @@ func (f *Fake) ChargePayments(ctx context.Context, charge string) (billing.Charg |
| return rec, nil |
| } |
| -// AccountCreated returns AccountOpened. |
| +// AccountCreated returns AccountOpened; Err or MoneyErr fail it. |
| func (f *Fake) AccountCreated(ctx context.Context) (time.Time, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| @@ -74,6 +86,9 @@ func (f *Fake) AccountCreated(ctx context.Context) (time.Time, error) { |
| if f.Err != nil { |
| return time.Time{}, f.Err |
| } |
| + if f.MoneyErr != nil { |
| + return time.Time{}, f.MoneyErr |
| + } |
| if f.timedOut() { |
| return time.Time{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| } |
diff --git a/internal/billing/billingtest/fake_money_test.go b/internal/billing/billingtest/fake_money_test.go| index 23d3874b7..ea493b879 100644 |
| --- a/internal/billing/billingtest/fake_money_test.go |
| +++ b/internal/billing/billingtest/fake_money_test.go |
| @@ -102,3 +102,43 @@ func TestFakeParsesPaymentEvent(t *testing.T) { |
| t.Fatalf("event = %+v", ev) |
| } |
| } |
| + |
| +func TestFakeMoneyErrAndChargeErr(t *testing.T) { |
| + ctx := context.Background() |
| + f := newFake(t) |
| + rec := billing.ChargeRecord{Captured: true, Charge: billing.Payment{Movement: "mv_1", Source: "ch_1", Charge: "ch_1"}} |
| + f.Charges = map[string]billing.ChargeRecord{"ch_1": rec, "ch_2": rec} |
| + f.Movements = movementsAt(2) |
| + |
| + // ChargeErr fails one charge only. |
| + f.ChargeErr = map[string]error{"ch_2": ErrInjected} |
| + if _, err := f.ChargePayments(ctx, "ch_2"); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("ChargePayments(ch_2) under ChargeErr: %v", err) |
| + } |
| + if _, err := f.ChargePayments(ctx, "ch_1"); err != nil { |
| + t.Fatalf("ChargePayments(ch_1) beside ChargeErr: %v", err) |
| + } |
| + if f.CallsBy["ChargePayments"] != 2 { |
| + t.Fatalf("ChargePayments counted %d, want 2", f.CallsBy["ChargePayments"]) |
| + } |
| + f.ChargeErr = nil |
| + |
| + // MoneyErr fails the three money reads and nothing else. |
| + f.MoneyErr = ErrInjected |
| + if _, err := f.MoneyMovements(ctx, t0, t0.Add(24*time.Hour)); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("MoneyMovements under MoneyErr: %v", err) |
| + } |
| + if f.CallsBy["MoneyMovements"] != 1 { |
| + t.Fatalf("failed MoneyMovements counted %d, want 1", f.CallsBy["MoneyMovements"]) |
| + } |
| + if _, err := f.ChargePayments(ctx, "ch_1"); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("ChargePayments under MoneyErr: %v", err) |
| + } |
| + if _, err := f.AccountCreated(ctx); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("AccountCreated under MoneyErr: %v", err) |
| + } |
| + f.Subs["sub_1"] = &billing.Subscription{ID: "sub_1", Customer: "cus_1"} |
| + if _, err := f.Subscription(ctx, "sub_1"); err != nil { |
| + t.Fatalf("Subscription under MoneyErr: %v", err) |
| + } |
| +} |
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go| new file mode 100644 |
| index 000000000..40b1eb410 |
| --- /dev/null |
| +++ b/internal/console/billingmoneypass.go |
| @@ -0,0 +1,160 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +const ( |
| + // billingMoneyWindow is the widest span one balance-movement list |
| + // reads. |
| + billingMoneyWindow = 31 * 24 * time.Hour |
| + // billingMoneyMinWindow is the narrowest: a list still too long for |
| + // MaxListPages at this width is an error, not a smaller window. |
| + billingMoneyMinWindow = time.Hour |
| + // billingMoneyOverlap is how far before the cursor each reconcile |
| + // starts, so a movement the provider lists late is still read. |
| + billingMoneyOverlap = time.Hour |
| +) |
| + |
| +// billingMoneyPass is the money half of the billing worker's round, after |
| +// the subscription sync. With billing off or not ready it does nothing. |
| +// Each part's failure is logged and fails the job, and never stops the |
| +// next part or the subscription sync (the money reads never gate |
| +// readiness). |
| +func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) { |
| + if s.billing == nil || !s.billing.ready.Load() { |
| + return |
| + } |
| + ctx = s.billingClock(ctx) |
| + if err := s.reconcilePayments(ctx, now); err != nil { |
| + log.Printf("console: billing money pass: payments: %v", err) |
| + jobFailed(ctx, fmt.Errorf("billing money pass: payments: %w", err)) |
| + } |
| +} |
| + |
| +// reconcilePayments records every balance movement from the cursor (less |
| +// billingMoneyOverlap) to now, one window at a time; with no cursor it is |
| +// the backfill, from when the provider account was opened. A window whose |
| +// list is too long is halved and read again from the same start, down to |
| +// billingMoneyMinWindow. Each charge, refund or refund failure not yet |
| +// recorded has its charge read once (recordCharge records every movement |
| +// of it); a fee is recorded from the movement; anything else is logged. |
| +// The cursor moves to a window's end only once all of the window is |
| +// recorded, so it never passes a movement that was not. Only a run that |
| +// reaches now with no error is a success (SetPaymentsReconciled). |
| +func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| + cfg := s.billing.cfg |
| + through, ok, err := s.store.PaymentCursor() |
| + if err != nil { |
| + return err |
| + } |
| + from := through.Add(-billingMoneyOverlap) |
| + if !ok { |
| + if from, err = cfg.Provider.AccountCreated(ctx); err != nil { |
| + return fmt.Errorf("reading when the account opened: %w", err) |
| + } |
| + } |
| + window := billingMoneyWindow |
| + loggedTypes := map[string]bool{} |
| + for from.Before(now) { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + to := from.Add(window) |
| + if to.After(now) { |
| + to = now |
| + } |
| + moves, err := cfg.Provider.MoneyMovements(ctx, from, to) |
| + if errors.Is(err, billing.ErrIncomplete) { |
| + // Half of what was read: a window cut short by now is |
| + // halved from its real width, not asked again unchanged. |
| + window = to.Sub(from) / 2 |
| + if window < billingMoneyMinWindow { |
| + return fmt.Errorf("balance movements from %s: %w", from.Format(time.RFC3339), err) |
| + } |
| + continue |
| + } |
| + if err != nil { |
| + return fmt.Errorf("balance movements from %s: %w", from.Format(time.RFC3339), err) |
| + } |
| + var charges []string |
| + inSet := map[string]bool{} |
| + for _, m := range moves { |
| + seen, err := s.store.HasPayment(m.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if seen { |
| + continue |
| + } |
| + switch m.Kind { |
| + case billing.MovementCharge, billing.MovementRefund, billing.MovementRefundFailure: |
| + if !inSet[m.Charge] { |
| + inSet[m.Charge] = true |
| + charges = append(charges, m.Charge) |
| + } |
| + case billing.MovementFee: |
| + if _, err := s.store.RecordPayment(billing.FeePayment(m, cfg.LiveMode), now); err != nil { |
| + return fmt.Errorf("recording fee %s: %w", m.ID, err) |
| + } |
| + default: |
| + if !loggedTypes[m.Type] { |
| + loggedTypes[m.Type] = true |
| + log.Printf("console: billing money pass: balance movement %s is a %q, not a payment; not recorded", m.ID, m.Type) |
| + } |
| + } |
| + } |
| + for _, ch := range charges { |
| + if err := s.recordCharge(ctx, ch, now); err != nil { |
| + return fmt.Errorf("charge %s: %w", ch, err) |
| + } |
| + } |
| + if err := s.store.SetPaymentCursor(to); err != nil { |
| + return err |
| + } |
| + from, window = to, billingMoneyWindow |
| + } |
| + if _, err := s.store.RematchPayments(); err != nil { |
| + return fmt.Errorf("rematching payments: %w", err) |
| + } |
| + return s.store.SetPaymentsReconciled(now) |
| +} |
| + |
| +// recordCharge reads a charge and records each balance movement it made: |
| +// the charge first, then every refund debit and reversal, so a refund |
| +// inherits the charge's account and tax share. A charge the provider does |
| +// not have, or has not captured, records nothing; one in the other mode is |
| +// logged and skipped. Recording is once per movement, so the webhook and |
| +// the reconcile may both call it. |
| +func (s *Server) recordCharge(ctx context.Context, charge string, now time.Time) error { |
| + cfg := s.billing.cfg |
| + rec, err := cfg.Provider.ChargePayments(ctx, charge) |
| + if errors.Is(err, billing.ErrNotFound) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if !rec.Captured { |
| + return nil |
| + } |
| + if rec.Charge.LiveMode != cfg.LiveMode { |
| + log.Printf("console: billing money pass: charge %s is in the other mode; not recorded", charge) |
| + return nil |
| + } |
| + if _, err := s.store.RecordPayment(rec.Charge, now); err != nil { |
| + return err |
| + } |
| + for _, p := range rec.Refunds { |
| + if _, err := s.store.RecordPayment(p, now); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/billingmoneypass_test.go b/internal/console/billingmoneypass_test.go| new file mode 100644 |
| index 000000000..089f94f05 |
| --- /dev/null |
| +++ b/internal/console/billingmoneypass_test.go |
| @@ -0,0 +1,440 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/billing/billingtest" |
| + "github.com/carlosframework/platform/internal/usage" |
| +) |
| + |
| +// windowSpy is the Fake with every MoneyMovements window recorded. |
| +type windowSpy struct { |
| + *billingtest.Fake |
| + mu sync.Mutex |
| + windows [][2]time.Time |
| +} |
| + |
| +func (w *windowSpy) MoneyMovements(ctx context.Context, from, to time.Time) ([]billing.Movement, error) { |
| + w.mu.Lock() |
| + w.windows = append(w.windows, [2]time.Time{from, to}) |
| + w.mu.Unlock() |
| + return w.Fake.MoneyMovements(ctx, from, to) |
| +} |
| + |
| +// spyWindows puts a windowSpy in front of the fixture's Fake. |
| +func (bf *billingFixture) spyWindows() *windowSpy { |
| + w := &windowSpy{Fake: bf.fake} |
| + bf.srv.billing.cfg.Provider = w |
| + return w |
| +} |
| + |
| +// testChargeRecord is a captured test-mode subscription charge on cus_1: |
| +// amount eur with a sixth of it tax, settled in full, and its movement. |
| +func testChargeRecord(charge string, at time.Time, amount int64) (billing.Movement, billing.ChargeRecord) { |
| + mv := "mv_" + charge |
| + m := billing.Movement{ID: mv, Kind: billing.MovementCharge, Type: "charge", Source: charge, Charge: charge, |
| + Amount: amount, Fee: -45, Currency: "eur", At: at} |
| + p := billing.Payment{ |
| + Movement: mv, Source: charge, Kind: billing.PaymentSubscription, Reason: billing.ReasonRenewal, |
| + Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_" + charge, Charge: charge, |
| + Amount: amount, Tax: amount / 6, Currency: "eur", |
| + Settled: amount, Fee: 45, SettledTax: amount / 6, SettledCurrency: "eur", At: at, |
| + } |
| + return m, billing.ChargeRecord{Captured: true, Charge: p} |
| +} |
| + |
| +// seedCharge puts a charge and its movement on the Fake. |
| +func (bf *billingFixture) seedCharge(charge string, at time.Time, amount int64) billing.ChargeRecord { |
| + m, rec := testChargeRecord(charge, at, amount) |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + bf.fake.Movements = append(bf.fake.Movements, m) |
| + if bf.fake.Charges == nil { |
| + bf.fake.Charges = map[string]billing.ChargeRecord{} |
| + } |
| + bf.fake.Charges[charge] = rec |
| + return rec |
| +} |
| + |
| +func (bf *billingFixture) seedMovement(m billing.Movement) { |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + bf.fake.Movements = append(bf.fake.Movements, m) |
| +} |
| + |
| +func (bf *billingFixture) setCharge(charge string, rec billing.ChargeRecord) { |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + if bf.fake.Charges == nil { |
| + bf.fake.Charges = map[string]billing.ChargeRecord{} |
| + } |
| + bf.fake.Charges[charge] = rec |
| +} |
| + |
| +func (bf *billingFixture) chargeReads() int { |
| + bf.fake.Lock() |
| + defer bf.fake.Unlock() |
| + return bf.fake.CallsBy["ChargePayments"] |
| +} |
| + |
| +func paymentRows(t *testing.T, s *Store) map[string]paymentRow { |
| + t.Helper() |
| + rows, _, err := s.Payments(paymentFilter{Kind: "all"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out := map[string]paymentRow{} |
| + for _, r := range rows { |
| + out[r.Movement] = r |
| + } |
| + return out |
| +} |
| + |
| +func setCursor(t *testing.T, s *Store, through time.Time) { |
| + t.Helper() |
| + if err := s.SetPaymentCursor(through); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func wantCursor(t *testing.T, s *Store, want time.Time) { |
| + t.Helper() |
| + got, ok, err := s.PaymentCursor() |
| + if err != nil || !ok || !got.Equal(want) { |
| + t.Fatalf("cursor = %v, %v, %v; want %v", got, ok, err, want) |
| + } |
| +} |
| + |
| +func wantReconciled(t *testing.T, s *Store, want time.Time) { |
| + t.Helper() |
| + got, err := s.PaymentsReconciledAt() |
| + if err != nil || !got.Equal(want) { |
| + t.Fatalf("reconciled at %v, %v; want %v", got, err, want) |
| + } |
| +} |
| + |
| +func TestReconcileBackfillsFromAccountCreation(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + opened := now.Add(-90 * 24 * time.Hour) |
| + bf.fake.AccountOpened = opened |
| + for i, ago := range []time.Duration{89 * 24 * time.Hour, 60 * 24 * time.Hour, 31 * 24 * time.Hour, 48 * time.Hour, time.Hour} { |
| + bf.seedCharge(fmt.Sprintf("ch_%d", i), now.Add(-ago), 1200) |
| + } |
| + spy := bf.spyWindows() |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := paymentRows(t, bf.st) |
| + if len(rows) != 5 { |
| + t.Fatalf("recorded %d rows, want 5: %v", len(rows), rows) |
| + } |
| + for mv, r := range rows { |
| + if r.AccountID != bf.acct.ID { |
| + t.Errorf("%s on account %d, want %d", mv, r.AccountID, bf.acct.ID) |
| + } |
| + } |
| + if len(spy.windows) != 3 || !spy.windows[0][0].Equal(opened) || !spy.windows[2][1].Equal(now) { |
| + t.Fatalf("windows = %v; want three from the account's opening to now", spy.windows) |
| + } |
| + for i := 1; i < len(spy.windows); i++ { |
| + if !spy.windows[i][0].Equal(spy.windows[i-1][1]) { |
| + t.Fatalf("windows not contiguous: %v", spy.windows) |
| + } |
| + } |
| + if got := spy.windows[0][1].Sub(spy.windows[0][0]); got != billingMoneyWindow { |
| + t.Fatalf("first window %v, want %v", got, billingMoneyWindow) |
| + } |
| + wantCursor(t, bf.st, now) |
| + wantReconciled(t, bf.st, now) |
| +} |
| + |
| +func TestReconcileFromCursor(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + bf.seedCharge("ch_before", now.Add(-4*time.Hour), 500) |
| + old := bf.seedCharge("ch_old", now.Add(-150*time.Minute), 1200) |
| + bf.seedCharge("ch_new", now.Add(-30*time.Minute), 1800) |
| + recordPayment(t, bf.st, old.Charge) |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + spy := bf.spyWindows() |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(spy.windows) != 1 || !spy.windows[0][0].Equal(now.Add(-3*time.Hour)) || !spy.windows[0][1].Equal(now) { |
| + t.Fatalf("windows = %v; want one from 3 h ago (cursor less the overlap) to now", spy.windows) |
| + } |
| + if n := bf.chargeReads(); n != 1 { |
| + t.Fatalf("ChargePayments read %d times, want 1 (only ch_new)", n) |
| + } |
| + rows := paymentRows(t, bf.st) |
| + if _, ok := rows["mv_ch_new"]; !ok || len(rows) != 2 { |
| + t.Fatalf("rows = %v; want ch_old and ch_new", rows) |
| + } |
| + wantCursor(t, bf.st, now) |
| +} |
| + |
| +func TestReconcileHalvesWindowOnIncomplete(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + bf.fake.PageSize = 1 |
| + // Twelve movements over 28 days: more than MaxListPages one-movement |
| + // pages in 31 days, at most seven in half that. |
| + for i := range 12 { |
| + bf.seedCharge(fmt.Sprintf("ch_%02d", i), now.Add(-time.Duration(i)*60*time.Hour-time.Hour), 100) |
| + } |
| + setCursor(t, bf.st, now.Add(-31*24*time.Hour+billingMoneyOverlap)) |
| + spy := bf.spyWindows() |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(paymentRows(t, bf.st)); n != 12 { |
| + t.Fatalf("recorded %d, want 12", n) |
| + } |
| + if got := spy.windows[1][1].Sub(spy.windows[1][0]); !spy.windows[1][0].Equal(spy.windows[0][0]) || got != billingMoneyWindow/2 { |
| + t.Fatalf("windows = %v; want the same start retried with half the window", spy.windows) |
| + } |
| + wantCursor(t, bf.st, now) |
| + wantReconciled(t, bf.st, now) |
| + |
| + // More than a list holds within the smallest window: an error, and |
| + // the cursor stays. |
| + bf2 := newBillingFixture(t) |
| + bf2.fake.PageSize = 1 |
| + from := now.Add(-48 * time.Hour) |
| + for i := range 11 { |
| + bf2.seedCharge(fmt.Sprintf("ch_%02d", i), from.Add(time.Duration(i)*time.Minute), 100) |
| + } |
| + setCursor(t, bf2.st, from.Add(billingMoneyOverlap)) |
| + if err := bf2.srv.reconcilePayments(context.Background(), now); !errors.Is(err, billing.ErrIncomplete) { |
| + t.Fatalf("err = %v, want ErrIncomplete", err) |
| + } |
| + wantCursor(t, bf2.st, from.Add(billingMoneyOverlap)) |
| + wantReconciled(t, bf2.st, time.Time{}) |
| + if n := len(paymentRows(t, bf2.st)); n != 0 { |
| + t.Fatalf("recorded %d, want none", n) |
| + } |
| +} |
| + |
| +func TestReconcileCursorHoldsOnError(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + cursor := now.Add(-40 * 24 * time.Hour) |
| + from := cursor.Add(-billingMoneyOverlap) |
| + bf.seedCharge("ch_1", from.Add(24*time.Hour), 1200) |
| + bf.seedCharge("ch_2", now.Add(-24*time.Hour), 1200) |
| + setCursor(t, bf.st, cursor) |
| + before := now.Add(-48 * time.Hour) |
| + if err := bf.st.SetPaymentsReconciled(before); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.fake.ChargeErr = map[string]error{"ch_2": billingtest.ErrInjected} |
| + if err := bf.srv.reconcilePayments(context.Background(), now); !errors.Is(err, billingtest.ErrInjected) { |
| + t.Fatalf("err = %v, want the charge read's", err) |
| + } |
| + wantCursor(t, bf.st, from.Add(billingMoneyWindow)) |
| + wantReconciled(t, bf.st, before) |
| + if rows := paymentRows(t, bf.st); len(rows) != 1 { |
| + t.Fatalf("rows = %v; want ch_1 only", rows) |
| + } |
| + |
| + bf.fake.Lock() |
| + bf.fake.ChargeErr = nil |
| + bf.fake.Unlock() |
| + later := now.Add(time.Hour) |
| + if err := bf.srv.reconcilePayments(context.Background(), later); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := paymentRows(t, bf.st)["mv_ch_2"]; !ok { |
| + t.Fatal("ch_2 not recorded once the failure cleared") |
| + } |
| + wantCursor(t, bf.st, later) |
| + wantReconciled(t, bf.st, later) |
| +} |
| + |
| +func TestReconcileRefundOfUnrecordedCharge(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + _, rec := testChargeRecord("ch_1", now.Add(-30*24*time.Hour), 1200) |
| + refundAt := now.Add(-30 * time.Minute) |
| + rec.Refunds = []billing.Payment{{ |
| + Movement: "mv_re_1", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonOther, |
| + Charge: "ch_1", Amount: -600, Currency: "eur", |
| + Settled: -600, SettledCurrency: "eur", At: refundAt, |
| + }} |
| + bf.setCharge("ch_1", rec) |
| + bf.seedMovement(billing.Movement{ID: "mv_re_1", Kind: billing.MovementRefund, Source: "re_1", Charge: "ch_1", |
| + Amount: -600, Currency: "eur", At: refundAt}) |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := paymentRows(t, bf.st) |
| + ch, okc := rows["mv_ch_1"] |
| + re, okr := rows["mv_re_1"] |
| + if !okc || !okr || len(rows) != 2 { |
| + t.Fatalf("rows = %v; want the charge and its refund", rows) |
| + } |
| + if ch.AccountID != bf.acct.ID || re.AccountID != bf.acct.ID { |
| + t.Fatalf("charge on %d, refund on %d; want both on %d", ch.AccountID, re.AccountID, bf.acct.ID) |
| + } |
| + // Recorded after its charge, the refund (which names no tax) takes |
| + // the charge's share: 200 of 1200, so 100 of 600. |
| + if re.Tax != -100 || re.SettledTax != -100 { |
| + t.Fatalf("refund tax %d/%d; want -100/-100 from its charge", re.Tax, re.SettledTax) |
| + } |
| +} |
| + |
| +func TestReconcileFailedRefundNeverRecorded(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + chargeAt := now.Add(-50 * time.Minute) |
| + m, rec := testChargeRecord("ch_1", chargeAt, 1200) |
| + debitAt, backAt := now.Add(-40*time.Minute), now.Add(-20*time.Minute) |
| + rec.Refunds = []billing.Payment{ |
| + {Movement: "mv_re_1", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonOther, |
| + Charge: "ch_1", Amount: -1200, Tax: -200, Currency: "eur", |
| + Settled: -1200, SettledTax: -200, SettledCurrency: "eur", At: debitAt}, |
| + {Movement: "mv_rf_1", Source: "re_1", Kind: billing.PaymentRefund, Reason: billing.ReasonReversed, |
| + Charge: "ch_1", Amount: 1200, Tax: 200, Currency: "eur", |
| + Settled: 1200, SettledTax: 200, SettledCurrency: "eur", At: backAt}, |
| + } |
| + bf.setCharge("ch_1", rec) |
| + bf.seedMovement(m) |
| + bf.seedMovement(billing.Movement{ID: "mv_re_1", Kind: billing.MovementRefund, Source: "re_1", Charge: "ch_1", Amount: -1200, Currency: "eur", At: debitAt}) |
| + bf.seedMovement(billing.Movement{ID: "mv_rf_1", Kind: billing.MovementRefundFailure, Source: "re_1", Charge: "ch_1", Amount: 1200, Currency: "eur", At: backAt}) |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := paymentRows(t, bf.st) |
| + if len(rows) != 3 { |
| + t.Fatalf("rows = %v; want charge, debit and reversal", rows) |
| + } |
| + var settled int64 |
| + for _, mv := range []string{"mv_ch_1", "mv_re_1", "mv_rf_1"} { |
| + r, ok := rows[mv] |
| + if !ok { |
| + t.Fatalf("no row for %s", mv) |
| + } |
| + if r.AccountID != bf.acct.ID { |
| + t.Errorf("%s on account %d, want %d", mv, r.AccountID, bf.acct.ID) |
| + } |
| + settled += r.Settled |
| + } |
| + if settled != rows["mv_ch_1"].Settled { |
| + t.Fatalf("settled sums to %d, want the charge's %d", settled, rows["mv_ch_1"].Settled) |
| + } |
| + if rows["mv_rf_1"].Reason != billing.ReasonReversed { |
| + t.Errorf("reversal reason %q", rows["mv_rf_1"].Reason) |
| + } |
| + reads := bf.chargeReads() |
| + if reads != 1 { |
| + t.Fatalf("charge read %d times, want once for its three movements", reads) |
| + } |
| + if err := bf.srv.reconcilePayments(context.Background(), now.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(paymentRows(t, bf.st)); n != 3 || bf.chargeReads() != reads { |
| + t.Fatalf("second run: %d rows, %d charge reads; want 3 rows and no new read", n, bf.chargeReads()-reads) |
| + } |
| +} |
| + |
| +func TestReconcileFees(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + at := now.Add(-30 * time.Minute) |
| + bf.seedMovement(billing.Movement{ID: "mv_fee", Kind: billing.MovementFee, Type: "provider_fee", Amount: -45, Currency: "eur", At: at}) |
| + bf.seedMovement(billing.Movement{ID: "mv_payout", Kind: billing.MovementOther, Type: "payout", Amount: -10000, Currency: "eur", At: at}) |
| + bf.seedMovement(billing.Movement{ID: "mv_payout2", Kind: billing.MovementOther, Type: "payout", Amount: -10000, Currency: "eur", At: at}) |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + for run := range 2 { |
| + if err := bf.srv.reconcilePayments(context.Background(), now.Add(time.Duration(run)*time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := paymentRows(t, bf.st) |
| + fee, ok := rows["mv_fee"] |
| + if len(rows) != 1 || !ok { |
| + t.Fatalf("run %d: rows = %v; want the fee only", run, rows) |
| + } |
| + if fee.Kind != billing.PaymentFee || fee.Settled != -45 || fee.SettledCurrency != "eur" || fee.LiveMode { |
| + t.Fatalf("fee row = %+v", fee) |
| + } |
| + } |
| +} |
| + |
| +func TestReconcileSkipsOtherMode(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + rec := bf.seedCharge("ch_live", now.Add(-30*time.Minute), 1200) |
| + rec.Charge.LiveMode = true |
| + bf.setCharge("ch_live", rec) |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatalf("other mode: %v, want nil", err) |
| + } |
| + if rows := paymentRows(t, bf.st); len(rows) != 0 { |
| + t.Fatalf("rows = %v; want none", rows) |
| + } |
| +} |
| + |
| +func TestMoneyPassFailureDoesNotStopSync(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + // A storage sweep, so the plan transition's measure has what it needs |
| + // and the subscription sync on its own fails nothing. |
| + day := usage.DayOf(billingNow) |
| + putStoreJSON(t, bf.rel, usage.StorageDayKey(day), usage.StorageDay{V: 1, Date: day, Apps: map[string]usage.AppStorage{}}) |
| + bf.put(bf.personalSub("sub_1", "active", nil)) |
| + if err := bf.st.PutBillingState(billingAccount{AccountID: bf.acct.ID, Subscription: "sub_1", State: "pending", PaidPacks: map[string]int{}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + bf.fake.Lock() |
| + bf.fake.MoneyErr = errors.New("permission denied") |
| + bf.fake.Unlock() |
| + if err := bf.srv.jobs.Run(context.Background(), "StartBillingSyncPass", func(ctx context.Context) error { |
| + return bf.srv.billingRound(ctx, billingNow) |
| + }); err != nil { |
| + t.Fatalf("run returned %v", err) |
| + } |
| + if p := bf.plan(t); p != "personal" { |
| + t.Fatalf("plan = %q; the subscription sync's write is gone", p) |
| + } |
| + job := func() JobStatus { |
| + for _, s := range bf.srv.jobs.Snapshot() { |
| + if s.Name == "StartBillingSyncPass" { |
| + return s |
| + } |
| + } |
| + return JobStatus{} |
| + } |
| + if st := job(); st.State != JobFailed || !strings.Contains(st.Err, "permission denied") { |
| + t.Fatalf("job = %+v; want failed with the money read's error", st) |
| + } |
| + wantReconciled(t, bf.st, time.Time{}) |
| + if _, ok, _ := bf.st.PaymentCursor(); ok { |
| + t.Fatal("cursor set by a failed backfill") |
| + } |
| + |
| + // With the money reads back, the same round succeeds. |
| + bf.fake.Lock() |
| + bf.fake.MoneyErr = nil |
| + bf.fake.AccountOpened = billingNow.Add(-24 * time.Hour) |
| + bf.fake.Unlock() |
| + if err := bf.srv.jobs.Run(context.Background(), "StartBillingSyncPass", func(ctx context.Context) error { |
| + return bf.srv.billingRound(ctx, billingNow.Add(time.Minute)) |
| + }); err != nil { |
| + t.Fatalf("run returned %v", err) |
| + } |
| + if st := job(); st.State != JobOK { |
| + t.Fatalf("job = %+v; want ok once the money reads work", st) |
| + } |
| + wantReconciled(t, bf.st, billingNow.Add(time.Minute)) |
| +} |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index 3023d30e8..10dc234b3 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -60,8 +60,8 @@ func (s *Server) billingReadyCheck(ctx context.Context) error { |
| // StartBillingSyncPass is the billing worker (plans 6a). With billing off |
| // it returns at once. Otherwise it retries the readiness check, backing off |
| // per billingCheckDelay, until it passes, logging a failure only when its |
| -// text changes, then syncs every live subscription now and every |
| -// billingSyncInterval. |
| +// text changes, then runs billingRound (the subscription sync, then the |
| +// money pass) now and every billingSyncInterval. |
| func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| if s.billing == nil { |
| return |
| @@ -90,7 +90,7 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| t := time.NewTicker(billingSyncInterval) |
| defer t.Stop() |
| for { |
| - _ = s.jobs.Run(ctx, "StartBillingSyncPass", func(ctx context.Context) error { s.billingSyncPass(ctx, time.Now()); return nil }) |
| + _ = s.jobs.Run(ctx, "StartBillingSyncPass", func(ctx context.Context) error { return s.billingRound(ctx, time.Now()) }) |
| select { |
| case <-ctx.Done(): |
| return |
| @@ -99,6 +99,15 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| } |
| } |
| +// billingRound is one run of the billing worker: the subscription sync, |
| +// then the money pass, whose failures fail the job but never undo or stop |
| +// the sync. |
| +func (s *Server) billingRound(ctx context.Context, now time.Time) error { |
| + s.billingSyncPass(ctx, now) |
| + s.billingMoneyPass(ctx, now) |
| + return nil |
| +} |
| + |
| // billingSyncPass re-reads every live subscription, serially, paging by |
| // account id, observing each team account's seats after its read |
| // (observeSeats: drift and seats_unpaid, local writes only), then observes |
diff --git a/internal/console/billingwebhook.go b/internal/console/billingwebhook.go| index c16bfb6ff..8bab509fd 100644 |
| --- a/internal/console/billingwebhook.go |
| +++ b/internal/console/billingwebhook.go |
| @@ -25,7 +25,9 @@ const billingWebhookMaxBody = 1 << 20 |
| // - a body over 1 MiB, a refused signature or shape, or the other mode: 400; |
| // - an ignored kind, or a checkout that made no subscription: 204; |
| // - a subscription (or a checkout's subscription) synced: 204, or 503 on |
| -// a transient error. |
| +// a transient error; |
| +// - a payment: the charge read and its balance movements recorded |
| +// (recordCharge): 204, or 503 on an error, and the provider redelivers. |
| func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) { |
| if s.billing == nil { |
| w.WriteHeader(http.StatusNotFound) |
| @@ -57,6 +59,14 @@ func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) { |
| switch ev.Kind { |
| case billing.EventSubscription: |
| subscription = ev.Object |
| + case billing.EventPayment: |
| + if err := s.recordCharge(s.billingClock(r.Context()), ev.Object, now); err != nil { |
| + log.Printf("console: billing webhook: event %s: recording charge %s: %v", ev.ID, ev.Object, err) |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| case billing.EventCheckout: |
| purchases, readErr := s.store.LiveDomainPurchases() |
| if readErr != nil { |
diff --git a/internal/console/billingwebhook_test.go b/internal/console/billingwebhook_test.go| index 36f06ce9f..c2b3ea787 100644 |
| --- a/internal/console/billingwebhook_test.go |
| +++ b/internal/console/billingwebhook_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "net/http" |
| "strings" |
| "testing" |
| + "time" |
| "github.com/carlosframework/platform/internal/billing" |
| ) |
| @@ -177,3 +178,55 @@ func TestStaleEventAppliesTheFreshRead(t *testing.T) { |
| t.Errorf("billing state = %q", b.State) |
| } |
| } |
| + |
| +func TestWebhookPaymentEventRecords(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.seedCharge("ch_1", billingNow.Add(-time.Minute), 1200) |
| + if got := billingDeliver(t, bf.consoleFixture, "payment", "ch_1", false); got != http.StatusNoContent { |
| + t.Fatalf("payment event: %d, want 204", got) |
| + } |
| + r, ok := paymentRows(t, bf.st)["mv_ch_1"] |
| + if !ok || r.AccountID != bf.acct.ID { |
| + t.Fatalf("row = %+v, %v; want the charge on the account", r, ok) |
| + } |
| + // A charge the provider does not have: nothing to record. |
| + if got := billingDeliver(t, bf.consoleFixture, "payment", "ch_none", false); got != http.StatusNoContent { |
| + t.Fatalf("unknown charge: %d, want 204", got) |
| + } |
| +} |
| + |
| +func TestWebhookPaymentEventTransient(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + bf.seedCharge("ch_1", billingNow.Add(-time.Minute), 1200) |
| + bf.fake.Lock() |
| + bf.fake.Err = errors.New("timeout") |
| + bf.fake.Unlock() |
| + if got := billingDeliver(t, bf.consoleFixture, "payment", "ch_1", false); got != http.StatusServiceUnavailable { |
| + t.Fatalf("transient: %d, want 503", got) |
| + } |
| + if rows := paymentRows(t, bf.st); len(rows) != 0 { |
| + t.Fatalf("rows = %v; want none", rows) |
| + } |
| +} |
| + |
| +func TestWebhookThenReconcileOneRow(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + bf.ready(t) |
| + now := billingNow |
| + bf.seedCharge("ch_1", now.Add(-30*time.Minute), 1200) |
| + if got := billingDeliver(t, bf.consoleFixture, "payment", "ch_1", false); got != http.StatusNoContent { |
| + t.Fatalf("payment event: %d, want 204", got) |
| + } |
| + setCursor(t, bf.st, now.Add(-2*time.Hour)) |
| + if err := bf.srv.reconcilePayments(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rows := paymentRows(t, bf.st); len(rows) != 1 { |
| + t.Fatalf("rows = %v; want one", rows) |
| + } |
| + if n := bf.chargeReads(); n != 1 { |
| + t.Fatalf("charge read %d times; the reconcile should skip a recorded movement", n) |
| + } |
| +} |
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go| index 55e118e3b..c83cb72e5 100644 |
| --- a/internal/console/jobs_test.go |
| +++ b/internal/console/jobs_test.go |
| @@ -51,7 +51,7 @@ var jobPassFuncs = map[string][]string{ |
| "StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners", |
| "convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"}, |
| "StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"}, |
| - "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan"}, |
| + "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge"}, |
| "PublishPlansMarker": {"publishPlansMarkerOnce"}, |
| "StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns", |
| "orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd", |