billing: neutral payment records and a fake to feed them
Add Movement, Payment and ChargeRecord with their kinds and reasons, SettledShare and FeePayment, and EventPayment (Object is a charge id). The fake gains Movements, Charges and AccountOpened and serves MoneyMovements (windowed, oldest first, paged like list), ChargePayments and AccountCreated, ready for Task 3 to add them to billing.Provider.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+361
−3
internal/billing/billing.go+4 −1internal/billing/billingtest/fake.go+13 −2internal/billing/billingtest/fake_money.go+82 −0internal/billing/billingtest/fake_money_test.go+104 −0internal/billing/payments.go+120 −0internal/billing/payments_test.go+38 −0
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index 7e0196d04..404c5209d 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -88,13 +88,16 @@ const ( |
| EventSubscription EventKind = "subscription" |
| EventCheckout EventKind = "checkout" |
| EventIgnored EventKind = "ignored" |
| + // EventPayment says money moved on a charge: Event.Object is the |
| + // charge id. |
| + EventPayment EventKind = "payment" |
| ) |
| // Event is a verified provider event, reduced to what to read next. |
| type Event struct { |
| ID string |
| Kind EventKind |
| - Object string // the subscription or checkout id |
| + Object string // the subscription, checkout or charge id |
| LiveMode bool |
| } |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index fc8654b47..ee3c7f550 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -141,11 +141,19 @@ type Fake struct { |
| Invoices map[string]*Invoice |
| paymentSessions map[string]*paymentSession |
| + // Movements is the provider's balance movements, Charges its charges |
| + // with their refunds by charge id, and AccountOpened when the |
| + // provider account was created (see fake_money.go). |
| + Movements []billing.Movement |
| + Charges map[string]billing.ChargeRecord |
| + AccountOpened time.Time |
| + |
| // CallsBy counts requests by method name: "Subscription", |
| // "CheckoutSubscription", "Check", "Send", "Checkout", "PortalURL", |
| // "ClockProbe", and one per list page under |
| // "LiveSubscriptions", "CustomerCheckouts", "RenewalInvoice" (invoice |
| - // pages) and "RenewalInvoiceLines" (line pages). A request that fails |
| + // pages), "RenewalInvoiceLines" (line pages) and "MoneyMovements". |
| + // "ChargePayments" and "AccountCreated" count one each. A request that fails |
| // still counts; a CrashBeforeSend does not (nothing was sent). |
| CallsBy map[string]int |
| // Sent is every Prepared Send received, in order (not those stopped by |
| @@ -279,6 +287,9 @@ func (f *Fake) init() { |
| if f.Invoices == nil { |
| f.Invoices = map[string]*Invoice{} |
| } |
| + if f.Charges == nil { |
| + f.Charges = map[string]billing.ChargeRecord{} |
| + } |
| if f.CallsBy == nil { |
| f.CallsBy = map[string]int{} |
| } |
| @@ -541,7 +552,7 @@ func (f *Fake) ParseEvent(raw []byte, header http.Header, _ time.Time) (billing. |
| return billing.Event{}, billing.ErrBadEvent |
| } |
| switch billing.EventKind(e.Kind) { |
| - case billing.EventSubscription, billing.EventCheckout, billing.EventIgnored: |
| + case billing.EventSubscription, billing.EventCheckout, billing.EventIgnored, billing.EventPayment: |
| default: |
| return billing.Event{}, billing.ErrBadEvent |
| } |
diff --git a/internal/billing/billingtest/fake_money.go b/internal/billing/billingtest/fake_money.go| new file mode 100644 |
| index 000000000..e9ac402c2 |
| --- /dev/null |
| +++ b/internal/billing/billingtest/fake_money.go |
| @@ -0,0 +1,82 @@ |
| +package billingtest |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// 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. |
| +func (f *Fake) MoneyMovements(ctx context.Context, from, to time.Time) ([]billing.Movement, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var in []billing.Movement |
| + for _, m := range f.Movements { |
| + if !m.At.Before(from) && m.At.Before(to) { |
| + in = append(in, m) |
| + } |
| + } |
| + slices.SortStableFunc(in, func(a, b billing.Movement) int { |
| + if c := a.At.Compare(b.At); c != 0 { |
| + return c |
| + } |
| + return strings.Compare(a.ID, b.ID) |
| + }) |
| + ids := make([]string, len(in)) |
| + byID := make(map[string]billing.Movement, len(in)) |
| + for i, m := range in { |
| + ids[i] = m.ID |
| + byID[m.ID] = m |
| + } |
| + out := []billing.Movement{} |
| + if err := f.list(ctx, "MoneyMovements", ids, func(id string) { |
| + out = append(out, byID[id]) |
| + }); err != nil { |
| + return nil, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// ChargePayments returns Charges[charge], or billing.ErrNotFound. |
| +func (f *Fake) ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("ChargePayments") |
| + defer f.end() |
| + if f.Err != nil { |
| + return billing.ChargeRecord{}, f.Err |
| + } |
| + if f.timedOut() { |
| + return billing.ChargeRecord{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + rec, ok := f.Charges[charge] |
| + if !ok { |
| + return billing.ChargeRecord{}, billing.ErrNotFound |
| + } |
| + rec.Refunds = slices.Clone(rec.Refunds) |
| + return rec, nil |
| +} |
| + |
| +// AccountCreated returns AccountOpened. |
| +func (f *Fake) AccountCreated(ctx context.Context) (time.Time, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("AccountCreated") |
| + defer f.end() |
| + if f.Err != nil { |
| + return time.Time{}, f.Err |
| + } |
| + if f.timedOut() { |
| + return time.Time{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + return f.AccountOpened, nil |
| +} |
diff --git a/internal/billing/billingtest/fake_money_test.go b/internal/billing/billingtest/fake_money_test.go| new file mode 100644 |
| index 000000000..23d3874b7 |
| --- /dev/null |
| +++ b/internal/billing/billingtest/fake_money_test.go |
| @@ -0,0 +1,104 @@ |
| +package billingtest |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func movementsAt(n int) []billing.Movement { |
| + out := make([]billing.Movement, n) |
| + // Seeded newest first, so the Fake has to order them itself. |
| + for i := range n { |
| + at := t0.Add(time.Duration(n-1-i) * time.Hour) |
| + out[i] = billing.Movement{ID: fmt.Sprintf("mv_%02d", n-1-i), Kind: billing.MovementCharge, |
| + Source: "ch_1", Charge: "ch_1", Amount: 1000, Fee: -45, Currency: "eur", At: at} |
| + } |
| + return out |
| +} |
| + |
| +func TestFakeMoneyMovementsWindowAndPages(t *testing.T) { |
| + ctx := context.Background() |
| + f := newFake(t) |
| + f.Movements = movementsAt(5) // at t0, t0+1h, ... t0+4h |
| + got, err := f.MoneyMovements(ctx, t0.Add(time.Hour), t0.Add(4*time.Hour)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var ids []string |
| + for _, m := range got { |
| + ids = append(ids, m.ID) |
| + } |
| + if fmt.Sprint(ids) != "[mv_01 mv_02 mv_03]" { |
| + t.Fatalf("window [t0+1h, t0+4h) = %v, want mv_01..mv_03 oldest first", ids) |
| + } |
| + if f.CallsBy["MoneyMovements"] != 1 { |
| + t.Fatalf("pages counted = %d, want 1", f.CallsBy["MoneyMovements"]) |
| + } |
| + |
| + f = newFake(t) |
| + f.Movements = movementsAt(11) |
| + f.PageSize = 1 |
| + if _, err := f.MoneyMovements(ctx, t0, t0.Add(24*time.Hour)); !errors.Is(err, billing.ErrIncomplete) { |
| + t.Fatalf("eleven one-movement pages: err = %v, want ErrIncomplete", err) |
| + } |
| + if f.CallsBy["MoneyMovements"] != billing.MaxListPages { |
| + t.Fatalf("pages counted = %d, want %d", f.CallsBy["MoneyMovements"], billing.MaxListPages) |
| + } |
| + |
| + f = newFake(t) |
| + f.Movements = movementsAt(10) |
| + f.PageSize = 1 |
| + if got, err := f.MoneyMovements(ctx, t0, t0.Add(24*time.Hour)); err != nil || len(got) != 10 { |
| + t.Fatalf("ten one-movement pages: %d, %v; want all ten", len(got), err) |
| + } |
| +} |
| + |
| +func TestFakeChargePaymentsAndAccountCreated(t *testing.T) { |
| + ctx := context.Background() |
| + f := newFake(t) |
| + rec := billing.ChargeRecord{Captured: true, Charge: billing.Payment{Movement: "mv_1", Source: "ch_1", Kind: billing.PaymentSubscription, |
| + Reason: billing.ReasonFirst, Customer: "cus_1", Charge: "ch_1", Amount: 2800, Tax: 400, Currency: "eur"}} |
| + f.Charges = map[string]billing.ChargeRecord{"ch_1": rec} |
| + f.AccountOpened = t0.AddDate(-1, 0, 0) |
| + |
| + got, err := f.ChargePayments(ctx, "ch_1") |
| + if err != nil || !got.Captured || got.Charge.Movement != "mv_1" { |
| + t.Fatalf("ChargePayments(ch_1) = %+v, %v", got, err) |
| + } |
| + if _, err := f.ChargePayments(ctx, "ch_none"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("ChargePayments(ch_none) err = %v, want ErrNotFound", err) |
| + } |
| + if at, err := f.AccountCreated(ctx); err != nil || !at.Equal(f.AccountOpened) { |
| + t.Fatalf("AccountCreated = %v, %v", at, err) |
| + } |
| + |
| + f.Err = ErrInjected |
| + if _, err := f.MoneyMovements(ctx, t0, t0.Add(time.Hour)); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("MoneyMovements under Err: %v", err) |
| + } |
| + if _, err := f.ChargePayments(ctx, "ch_1"); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("ChargePayments under Err: %v", err) |
| + } |
| + if _, err := f.AccountCreated(ctx); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("AccountCreated under Err: %v", err) |
| + } |
| +} |
| + |
| +func TestFakeParsesPaymentEvent(t *testing.T) { |
| + f := newFake(t) |
| + h := http.Header{} |
| + h.Set("Fake-Signature", "ok") |
| + ev, err := f.ParseEvent([]byte(`{"id":"evt_1","kind":"payment","object":"ch_1","live":true}`), h, t0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ev.Kind != billing.EventPayment || ev.Object != "ch_1" || !ev.LiveMode { |
| + t.Fatalf("event = %+v", ev) |
| + } |
| +} |
diff --git a/internal/billing/payments.go b/internal/billing/payments.go| new file mode 100644 |
| index 000000000..ce0073756 |
| --- /dev/null |
| +++ b/internal/billing/payments.go |
| @@ -0,0 +1,120 @@ |
| +package billing |
| + |
| +import "time" |
| + |
| +// MovementKind is what a balance movement is, in neutral words. |
| +type MovementKind string |
| + |
| +const ( |
| + MovementCharge MovementKind = "charge" |
| + MovementRefund MovementKind = "refund" |
| + MovementRefundFailure MovementKind = "refund_failure" |
| + MovementFee MovementKind = "fee" |
| + MovementOther MovementKind = "other" |
| +) |
| + |
| +// Movement is one movement of the provider's balance: money arriving, |
| +// leaving or being charged by the provider itself. |
| +type Movement struct { |
| + ID string |
| + Kind MovementKind |
| + Type string // the provider's own word, for logs |
| + Source string // the charge or refund it settles |
| + Charge string // for charge, refund and refund failure: the charge |
| + // Amount and Fee are settled, signed, in Currency's minor units. |
| + Amount, Fee int64 |
| + Currency string // settlement |
| + At time.Time |
| +} |
| + |
| +// PaymentKind is what a recorded payment is. |
| +type PaymentKind string |
| + |
| +const ( |
| + PaymentSubscription PaymentKind = "subscription" |
| + PaymentOnceOff PaymentKind = "once_off" |
| + PaymentRefund PaymentKind = "refund" |
| + PaymentFee PaymentKind = "fee" |
| +) |
| + |
| +// Payment reasons. |
| +const ( |
| + ReasonFirst = "first" |
| + ReasonRenewal = "renewal" |
| + ReasonChange = "change" |
| + ReasonDomain = "domain" |
| + ReasonOther = "other" |
| + ReasonReversed = "reversed" // a refund that failed and came back |
| +) |
| + |
| +// Payment is one balance movement as the money record keeps it: what was |
| +// charged (Amount, Tax, Currency) and what settled (Settled, Fee, |
| +// SettledTax, SettledCurrency). |
| +type Payment struct { |
| + Movement string // the provider's balance-movement id: the record's key |
| + Source string // the charge or refund it settles; "" for a fee |
| + Kind PaymentKind |
| + Reason string |
| + |
| + Customer, Subscription, PaymentIntent, Charge string |
| + |
| + // Amount and Tax are as charged, signed: negative for refund debits |
| + // and fees, positive for reversals. |
| + Amount, Tax int64 |
| + Currency string |
| + |
| + Settled, Fee, SettledTax int64 |
| + SettledCurrency string |
| + |
| + At time.Time |
| + LiveMode bool |
| +} |
| + |
| +// ChargeRecord is a charge and its refunds. Refunds holds, per refund, its |
| +// debit (Kind refund, negative) and, when the refund failed, its reversal |
| +// (Kind refund, Reason reversed, positive, the debit's tax negated), each |
| +// with its own Movement. |
| +type ChargeRecord struct { |
| + Captured bool |
| + Charge Payment |
| + Refunds []Payment |
| +} |
| + |
| +// SettledShare is round(part × settled / whole), rounding halves away from |
| +// zero, and 0 when whole is 0: the settled tax of a charge, or a refund's |
| +// share of it. The sign follows settled. |
| +func SettledShare(part, whole, settled int64) int64 { |
| + if whole == 0 { |
| + return 0 |
| + } |
| + n := part * settled |
| + q, r := n/whole, n%whole |
| + if 2*abs64(r) >= abs64(whole) { |
| + if (n < 0) != (whole < 0) { |
| + q-- |
| + } else { |
| + q++ |
| + } |
| + } |
| + return q |
| +} |
| + |
| +func abs64(v int64) int64 { |
| + if v < 0 { |
| + return -v |
| + } |
| + return v |
| +} |
| + |
| +// FeePayment records a fee movement: the provider charging the balance |
| +// directly, with nothing charged to a customer. |
| +func FeePayment(m Movement, live bool) Payment { |
| + return Payment{ |
| + Movement: m.ID, |
| + Kind: PaymentFee, |
| + Settled: m.Amount, |
| + SettledCurrency: m.Currency, |
| + At: m.At, |
| + LiveMode: live, |
| + } |
| +} |
diff --git a/internal/billing/payments_test.go b/internal/billing/payments_test.go| new file mode 100644 |
| index 000000000..f1f0f2f66 |
| --- /dev/null |
| +++ b/internal/billing/payments_test.go |
| @@ -0,0 +1,38 @@ |
| +package billing |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestSettledShare(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + part, whole, settled int64 |
| + want int64 |
| + }{ |
| + {"tax of a eur charge settled in eur after conversion", 400, 2800, 2610, 373}, |
| + {"nothing charged", 400, 0, 2610, 0}, |
| + {"a refund keeps its sign", 400, 2800, -2610, -373}, |
| + {"exact", 500, 1000, 300, 150}, |
| + {"half rounds away from zero", 1, 2, 1, 1}, |
| + {"negative half rounds away from zero", 1, 2, -1, -1}, |
| + } |
| + for _, c := range cases { |
| + if got := SettledShare(c.part, c.whole, c.settled); got != c.want { |
| + t.Errorf("%s: SettledShare(%d, %d, %d) = %d, want %d", c.name, c.part, c.whole, c.settled, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestFeePayment(t *testing.T) { |
| + at := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC) |
| + m := Movement{ID: "mv_1", Kind: MovementFee, Type: "provider_fee", Amount: -45, Currency: "eur", At: at} |
| + p := FeePayment(m, true) |
| + if p.Kind != PaymentFee || p.Settled != -45 || p.Fee != 0 || p.Movement != m.ID || p.Source != "" { |
| + t.Fatalf("FeePayment = %+v", p) |
| + } |
| + if p.SettledCurrency != "eur" || !p.At.Equal(at) || !p.LiveMode { |
| + t.Fatalf("FeePayment currency/time/mode = %+v", p) |
| + } |
| +} |