billing: record a failed bank debit as a payment failure, not a refund
Final review finding C (Astra 3, Ruling 24): payment_failure_refund is a delayed payment method failing after its charge succeeded, not a failed refund; the charge's own failure_balance_transaction carries it. It was mapped to refund_failure, expected a refund source and was never read from the charge, so meeting one could hold the reconcile for good. - billing: MovementPaymentFailure "payment_failure" and ReasonPaymentFailed "payment_failed". - billingstripe: payment_failure_refund maps to MovementPaymentFailure; its charge is the source when the source is a charge, else the charge the source names, anything else refused. ChargePayments expands failure_balance_transaction and adds a refund row with reason payment_failed, Source the charge, the charge's amount and tax negated, Settled and Fee from the failure, SettledTax by SettledShare. - console: the reconcile reads the charge for a payment failure and holds the window when it is not recorded (Ruling 15); a domain charge's failure keeps its reason when it matches the purchase. The refund-shaped fixture is replaced by the documented charge source. Tests: TestMoneyMovementsMapsTypes, TestMoneyMovementKinds, TestMoneyMovementsRefusesMalformed, TestChargePaymentsPaymentFailed, TestReconcilePaymentFailure, TestRecordPaymentDomainPaymentFailure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+205
−31
internal/billing/payments.go+12 −4internal/billingstripe/money.go+47 −6internal/billingstripe/money_test.go+70 −17internal/console/billingmoneypass.go+3 −2internal/console/billingmoneypass_test.go+43 −0internal/console/billingpayments_store.go+2 −2internal/console/billingpayments_store_test.go+28 −0
diff --git a/internal/billing/payments.go b/internal/billing/payments.go| index 050e54911..b877bddb1 100644 |
| --- a/internal/billing/payments.go |
| +++ b/internal/billing/payments.go |
| @@ -13,8 +13,11 @@ const ( |
| MovementCharge MovementKind = "charge" |
| MovementRefund MovementKind = "refund" |
| MovementRefundFailure MovementKind = "refund_failure" |
| - MovementFee MovementKind = "fee" |
| - MovementOther MovementKind = "other" |
| + // MovementPaymentFailure is a delayed payment method (a bank debit) |
| + // failing after its charge succeeded: the money goes back out. |
| + MovementPaymentFailure MovementKind = "payment_failure" |
| + MovementFee MovementKind = "fee" |
| + MovementOther MovementKind = "other" |
| ) |
| // Movement is one movement of the provider's balance: money arriving, |
| @@ -24,7 +27,7 @@ type Movement struct { |
| 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 |
| + Charge string // for charge, refund, refund failure and payment failure: the charge |
| // Amount and Fee are settled, signed, in Currency's minor units. |
| Amount, Fee int64 |
| Currency string // settlement |
| @@ -49,6 +52,9 @@ const ( |
| ReasonDomain = "domain" |
| ReasonOther = "other" |
| ReasonReversed = "reversed" // a refund that failed and came back |
| + // ReasonPaymentFailed is a charge's payment failing after it |
| + // succeeded (a bank debit returned): the money went back out. |
| + ReasonPaymentFailed = "payment_failed" |
| ) |
| // Payment is one balance movement as the money record keeps it: what was |
| @@ -77,7 +83,9 @@ type Payment struct { |
| // 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. |
| +// with its own Movement; and, when the charge's payment failed after it |
| +// succeeded, that failure (Kind refund, Reason payment_failed, Source the |
| +// charge, the charge's amount and tax negated). |
| type ChargeRecord struct { |
| Captured bool |
| Charge Payment |
diff --git a/internal/billingstripe/money.go b/internal/billingstripe/money.go| index bbea89fce..96b6cdeab 100644 |
| --- a/internal/billingstripe/money.go |
| +++ b/internal/billingstripe/money.go |
| @@ -125,6 +125,7 @@ type stripeCharge struct { |
| Customer string |
| PaymentIntent string |
| Txn *balanceTxn |
| + FailureTxn *balanceTxn // the money taken back when the payment failed after succeeding |
| Invoice *chargeInvoice |
| Refunds []stripeRefund |
| RefundsMore bool |
| @@ -143,6 +144,7 @@ func (c *stripeCharge) UnmarshalJSON(b []byte) error { |
| Customer idOrExpanded `json:"customer"` |
| PaymentIntent idOrExpanded `json:"payment_intent"` |
| BalanceTransaction idOrExpanded `json:"balance_transaction"` |
| + FailureTxn idOrExpanded `json:"failure_balance_transaction"` |
| Invoice idOrExpanded `json:"invoice"` |
| Refunds *struct { |
| Data []stripeRefund `json:"data"` |
| @@ -162,9 +164,13 @@ func (c *stripeCharge) UnmarshalJSON(b []byte) error { |
| if err != nil { |
| return err |
| } |
| + failure, err := expandedTxn(raw.FailureTxn) |
| + if err != nil { |
| + return err |
| + } |
| *c = stripeCharge{ |
| ID: *raw.ID, LiveMode: *raw.LiveMode, Amount: raw.Amount, Currency: raw.Currency, Captured: raw.Captured, |
| - Customer: raw.Customer.ID, PaymentIntent: raw.PaymentIntent.ID, Txn: txn, |
| + Customer: raw.Customer.ID, PaymentIntent: raw.PaymentIntent.ID, Txn: txn, FailureTxn: failure, |
| } |
| if raw.AmountCaptured != nil { |
| c.Amount = *raw.AmountCaptured |
| @@ -199,8 +205,10 @@ func movementKindOf(typ string) billing.MovementKind { |
| return billing.MovementCharge |
| case "refund", "payment_refund": |
| return billing.MovementRefund |
| - case "refund_failure", "payment_failure_refund": |
| + case "refund_failure": |
| return billing.MovementRefundFailure |
| + case "payment_failure_refund": |
| + return billing.MovementPaymentFailure |
| case "stripe_fee", "stripe_fx_fee", "tax_fee": |
| return billing.MovementFee |
| default: |
| @@ -259,8 +267,8 @@ func movementOf(t balanceTxn) (billing.Movement, error) { |
| ID: t.ID, Kind: movementKindOf(t.Type), Type: t.Type, Source: t.Source.ID, |
| Amount: t.Amount, Fee: t.Fee, Currency: t.Currency, At: t.Created, |
| } |
| - // A charge, refund or refund failure must name its charge: the |
| - // money pass reads the charge to record and attribute it. |
| + // A charge, refund, refund failure or payment failure must name its |
| + // charge: the money pass reads the charge to record and attribute it. |
| switch m.Kind { |
| case billing.MovementCharge: |
| if !validID(t.Source.ID) { |
| @@ -281,6 +289,26 @@ func movementOf(t balanceTxn) (billing.Movement, error) { |
| return billing.Movement{}, errors.New("billingstripe: refund movement names no charge") |
| } |
| m.Charge = r.Charge.ID |
| + case billing.MovementPaymentFailure: |
| + // The charge whose payment failed: the source itself when it is |
| + // the charge, else the charge the source names. |
| + if t.Source.Object == nil || !validID(t.Source.ID) { |
| + return billing.Movement{}, errors.New("billingstripe: payment failure source not expanded") |
| + } |
| + var src struct { |
| + Object string `json:"object"` |
| + Charge idOrExpanded `json:"charge"` |
| + } |
| + if err := json.Unmarshal(t.Source.Object, &src); err != nil { |
| + return billing.Movement{}, err |
| + } |
| + m.Charge = src.Charge.ID |
| + if src.Object == "charge" { |
| + m.Charge = t.Source.ID |
| + } |
| + if !validID(m.Charge) { |
| + return billing.Movement{}, errors.New("billingstripe: payment failure names no charge") |
| + } |
| } |
| return m, nil |
| } |
| @@ -305,14 +333,14 @@ func chargeKindOf(inv *chargeInvoice) (billing.PaymentKind, string) { |
| } |
| // ChargePayments reads a charge and its refunds: one Payment per balance |
| -// movement they made. ErrNotFound when Stripe has no such charge; Captured |
| +// movement they made, the charge's payment failure among the refunds. ErrNotFound when Stripe has no such charge; Captured |
| // false, and nothing else, when no money moved. |
| func (p *Provider) ChargePayments(ctx context.Context, charge string) (billing.ChargeRecord, error) { |
| if !validID(charge) { |
| return billing.ChargeRecord{}, &Error{Code: CodeInvalidID} |
| } |
| q := url.Values{"expand[]": { |
| - "balance_transaction", "invoice", "refunds", |
| + "balance_transaction", "failure_balance_transaction", "invoice", "refunds", |
| "refunds.data.balance_transaction", "refunds.data.failure_balance_transaction", |
| }} |
| var ch stripeCharge |
| @@ -362,6 +390,19 @@ func (p *Provider) ChargePayments(ctx context.Context, charge string) (billing.C |
| } |
| c.SettledTax = billing.SettledShare(c.Tax, c.Amount, c.Settled) |
| rec := billing.ChargeRecord{Captured: true, Charge: c} |
| + if ch.FailureTxn != nil { |
| + // The payment failed after it succeeded: the whole charge, tax |
| + // and all, went back out. |
| + f := billing.Payment{ |
| + Movement: ch.FailureTxn.ID, Source: ch.ID, Kind: billing.PaymentRefund, Reason: billing.ReasonPaymentFailed, |
| + Customer: c.Customer, Subscription: c.Subscription, PaymentIntent: c.PaymentIntent, Charge: ch.ID, |
| + Amount: -c.Amount, Tax: -c.Tax, Currency: c.Currency, |
| + Settled: ch.FailureTxn.Amount, Fee: ch.FailureTxn.Fee, SettledCurrency: ch.FailureTxn.Currency, |
| + At: ch.FailureTxn.Created, LiveMode: ch.LiveMode, |
| + } |
| + f.SettledTax = billing.SettledShare(f.Tax, f.Amount, f.Settled) |
| + rec.Refunds = append(rec.Refunds, f) |
| + } |
| for _, r := range refunds { |
| if r.Txn == nil && r.FailureTxn == nil { |
diff --git a/internal/billingstripe/money_test.go b/internal/billingstripe/money_test.go| index 799959000..1e5e246f6 100644 |
| --- a/internal/billingstripe/money_test.go |
| +++ b/internal/billingstripe/money_test.go |
| @@ -28,6 +28,11 @@ func TestMoneyMovementsMapsTypes(t *testing.T) { |
| failed := `{"id":"re_2","object":"refund","amount":1000,"charge":"ch_1","currency":"eur","status":"failed"}` |
| // Stripe lists newest first. |
| page := []string{ |
| + // A delayed payment method failing after the charge succeeded: |
| + // Stripe's source is the charge itself (documented shape), or an |
| + // object naming it. |
| + txnJSON("txn_9", "payment_failure_refund", -2000, 0, "eur", moneyT0.Add(9*time.Hour), `{"id":"pyr_9","object":"payment_refund","charge":"py_9"}`), |
| + txnJSON("txn_8", "payment_failure_refund", -2904, 0, "eur", moneyT0.Add(8*time.Hour), `{"id":"py_2","object":"charge","status":"failed"}`), |
| txnJSON("txn_7", "stripe_fx_fee", -12, 0, "eur", moneyT0.Add(7*time.Hour), `null`), |
| txnJSON("txn_6", "payout", -5000, 0, "eur", moneyT0.Add(6*time.Hour), `"po_1"`), |
| txnJSON("txn_5", "stripe_fee", -45, 0, "eur", moneyT0.Add(5*time.Hour), `null`), |
| @@ -63,6 +68,8 @@ func TestMoneyMovementsMapsTypes(t *testing.T) { |
| {ID: "txn_5", Kind: billing.MovementFee, Type: "stripe_fee", Amount: -45, Currency: "eur", At: moneyT0.Add(5 * time.Hour)}, |
| {ID: "txn_6", Kind: billing.MovementOther, Type: "payout", Source: "po_1", Amount: -5000, Currency: "eur", At: moneyT0.Add(6 * time.Hour)}, |
| {ID: "txn_7", Kind: billing.MovementFee, Type: "stripe_fx_fee", Amount: -12, Currency: "eur", At: moneyT0.Add(7 * time.Hour)}, |
| + {ID: "txn_8", Kind: billing.MovementPaymentFailure, Type: "payment_failure_refund", Source: "py_2", Charge: "py_2", Amount: -2904, Currency: "eur", At: moneyT0.Add(8 * time.Hour)}, |
| + {ID: "txn_9", Kind: billing.MovementPaymentFailure, Type: "payment_failure_refund", Source: "pyr_9", Charge: "py_9", Amount: -2000, Currency: "eur", At: moneyT0.Add(9 * time.Hour)}, |
| } |
| if len(ms) != len(want) { |
| t.Fatalf("got %d movements: %+v", len(ms), ms) |
| @@ -138,7 +145,7 @@ func TestMoneyMovementKinds(t *testing.T) { |
| for typ, want := range map[string]billing.MovementKind{ |
| "charge": billing.MovementCharge, "payment": billing.MovementCharge, |
| "refund": billing.MovementRefund, "payment_refund": billing.MovementRefund, |
| - "refund_failure": billing.MovementRefundFailure, "payment_failure_refund": billing.MovementRefundFailure, |
| + "refund_failure": billing.MovementRefundFailure, "payment_failure_refund": billing.MovementPaymentFailure, |
| "stripe_fee": billing.MovementFee, "tax_fee": billing.MovementFee, "stripe_fx_fee": billing.MovementFee, |
| "payout": billing.MovementOther, "adjustment": billing.MovementOther, "": billing.MovementOther, |
| } { |
| @@ -168,18 +175,21 @@ func TestMoneyMovementsIncomplete(t *testing.T) { |
| func TestMoneyMovementsRefusesMalformed(t *testing.T) { |
| for name, obj := range map[string]string{ |
| - "no id": `{"object":"balance_transaction","type":"charge","amount":1,"currency":"eur","created":1}`, |
| - "bad id": `{"id":"txn 1","type":"charge","amount":1,"currency":"eur","created":1}`, |
| - "no created": `{"id":"txn_1","type":"charge","amount":1,"currency":"eur"}`, |
| - "null": `null`, |
| - "refund source unexpanded": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `"re_1"`), |
| - "refund source null": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `null`), |
| - "refund source no charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund"}`), |
| - "refund source null charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund","charge":null}`), |
| - "refund source bad charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund","charge":"ch/1"}`), |
| - "failure source unexpanded": txnJSON("txn_1", "refund_failure", 1, 0, "eur", moneyT0, `"re_1"`), |
| - "failure source no charge": txnJSON("txn_1", "payment_failure_refund", 1, 0, "eur", moneyT0, `{"id":"re_1"}`), |
| - "charge source null": txnJSON("txn_1", "charge", 1, 0, "eur", moneyT0, `null`), |
| + "no id": `{"object":"balance_transaction","type":"charge","amount":1,"currency":"eur","created":1}`, |
| + "bad id": `{"id":"txn 1","type":"charge","amount":1,"currency":"eur","created":1}`, |
| + "no created": `{"id":"txn_1","type":"charge","amount":1,"currency":"eur"}`, |
| + "null": `null`, |
| + "refund source unexpanded": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `"re_1"`), |
| + "refund source null": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `null`), |
| + "refund source no charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund"}`), |
| + "refund source null charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund","charge":null}`), |
| + "refund source bad charge": txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `{"id":"re_1","object":"refund","charge":"ch/1"}`), |
| + "failure source unexpanded": txnJSON("txn_1", "refund_failure", 1, 0, "eur", moneyT0, `"re_1"`), |
| + "failure source no charge": txnJSON("txn_1", "payment_failure_refund", 1, 0, "eur", moneyT0, `{"id":"re_1"}`), |
| + "payment failure unexpanded": txnJSON("txn_1", "payment_failure_refund", -1, 0, "eur", moneyT0, `"py_1"`), |
| + "payment failure null": txnJSON("txn_1", "payment_failure_refund", -1, 0, "eur", moneyT0, `null`), |
| + "payment failure bad charge": txnJSON("txn_1", "payment_failure_refund", -1, 0, "eur", moneyT0, `{"id":"py 1","object":"charge"}`), |
| + "charge source null": txnJSON("txn_1", "charge", 1, 0, "eur", moneyT0, `null`), |
| // A good movement first: a later bad one still fails the whole list. |
| "bad after good": txnJSON("txn_0", "charge", 1, 0, "eur", moneyT0, `"ch_1"`) + "," + |
| txnJSON("txn_1", "refund", -1, 0, "eur", moneyT0, `"re_1"`), |
| @@ -249,23 +259,27 @@ type chargeFixture struct { |
| amount int64 |
| captured bool |
| txn string // "" null |
| + failure string // the charge's failure_balance_transaction; "" null |
| invoice string // "" null |
| refunds []string |
| refundsHasMore bool |
| } |
| func (f chargeFixture) json() string { |
| - txn, inv := f.txn, f.invoice |
| + txn, inv, failure := f.txn, f.invoice, f.failure |
| if txn == "" { |
| txn = "null" |
| } |
| + if failure == "" { |
| + failure = "null" |
| + } |
| if inv == "" { |
| inv = "null" |
| } |
| return fmt.Sprintf(`{"id":"ch_1","object":"charge","livemode":false,"amount":%d,"amount_captured":%d,"currency":%q,"captured":%v,`+ |
| - `"customer":"cus_1","payment_intent":"pi_1","created":%d,"balance_transaction":%s,"invoice":%s,`+ |
| + `"customer":"cus_1","payment_intent":"pi_1","created":%d,"balance_transaction":%s,"failure_balance_transaction":%s,"invoice":%s,`+ |
| `"refunds":{"object":"list","data":[%s],"has_more":%v}}`, |
| - f.amount, f.amount, f.currency, f.captured, moneyT0.Unix(), txn, inv, strings.Join(f.refunds, ","), f.refundsHasMore) |
| + f.amount, f.amount, f.currency, f.captured, moneyT0.Unix(), txn, failure, inv, strings.Join(f.refunds, ","), f.refundsHasMore) |
| } |
| func invoiceJSON(reason string, tax int64, sub string) string { |
| @@ -310,7 +324,7 @@ func TestChargePaymentsSubscriptionFirst(t *testing.T) { |
| t.Errorf("record %+v\nwant charge %+v", rec, want) |
| } |
| q := cs.queries["/v1/charges/ch_1"][0] |
| - wantExpand := []string{"balance_transaction", "invoice", "refunds", "refunds.data.balance_transaction", "refunds.data.failure_balance_transaction"} |
| + wantExpand := []string{"balance_transaction", "failure_balance_transaction", "invoice", "refunds", "refunds.data.balance_transaction", "refunds.data.failure_balance_transaction"} |
| if got := slices.Sorted(slices.Values(q["expand[]"])); !slices.Equal(got, wantExpand) { |
| t.Errorf("expand %v", got) |
| } |
| @@ -398,6 +412,45 @@ func TestChargePaymentsFailedRefund(t *testing.T) { |
| } |
| } |
| +// A delayed payment method (a bank debit) failing after the charge |
| +// succeeded: the charge's own failure_balance_transaction takes the money |
| +// back, recorded as a refund row with reason payment_failed that cancels |
| +// the charge, tax and all. |
| +func TestChargePaymentsPaymentFailed(t *testing.T) { |
| + cs := &chargeServer{t: t, charge: chargeFixture{ |
| + currency: "eur", amount: 2904, captured: true, |
| + txn: txnJSON("txn_ch", "payment", 2904, 60, "eur", moneyT0, `"ch_1"`), |
| + failure: txnJSON("txn_pf", "payment_failure_refund", -2904, 0, "eur", moneyT0.Add(72*time.Hour), `"ch_1"`), |
| + invoice: invoiceJSON("subscription_cycle", 504, "sub_1"), |
| + }.json()} |
| + rec, err := chargePayments(t, cs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(rec.Refunds) != 1 { |
| + t.Fatalf("refunds %+v; want the payment failure", rec.Refunds) |
| + } |
| + want := billing.Payment{ |
| + Movement: "txn_pf", Source: "ch_1", Kind: billing.PaymentRefund, Reason: billing.ReasonPaymentFailed, |
| + Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_1", Charge: "ch_1", |
| + Amount: -2904, Tax: -504, Currency: "eur", Settled: -2904, SettledTax: -504, SettledCurrency: "eur", |
| + At: moneyT0.Add(72 * time.Hour), |
| + } |
| + if got := rec.Refunds[0]; got != want { |
| + t.Errorf("payment failure\n got %+v\nwant %+v", got, want) |
| + } |
| + c, f := rec.Charge, rec.Refunds[0] |
| + if c.Amount+f.Amount != 0 || c.Tax+f.Tax != 0 || c.Settled+f.Settled != 0 || c.SettledTax+f.SettledTax != 0 { |
| + t.Errorf("charge and failure do not cancel: %+v %+v", c, f) |
| + } |
| + // An unexpanded failure transaction is refused, not read as none. |
| + cs.charge = chargeFixture{currency: "eur", amount: 1, captured: true, |
| + txn: txnJSON("txn_ch", "charge", 1, 0, "eur", moneyT0, `"ch_1"`), failure: `"txn_pf"`}.json() |
| + if _, err := chargePayments(t, cs); err == nil { |
| + t.Error("unexpanded failure transaction accepted") |
| + } |
| +} |
| + |
| func TestChargePaymentsUpdateIsOnceOff(t *testing.T) { |
| cs := &chargeServer{t: t, charge: chargeFixture{ |
| currency: "eur", amount: 1200, captured: true, |
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go| index ce5332fc2..08a6363ed 100644 |
| --- a/internal/console/billingmoneypass.go |
| +++ b/internal/console/billingmoneypass.go |
| @@ -60,7 +60,8 @@ func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) { |
| // 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. |
| +// of it, a payment failure among them); a fee is recorded from the |
| +// movement; anything else is logged. |
| // A charge-kind movement still unrecorded after its charge's read (not |
| // found, not captured, or a read that lacks it) fails the window, unless |
| // its charge was skipped for being in the other mode. The cursor moves to a window's end only once all of the window is |
| @@ -111,7 +112,7 @@ func (s *Server) reconcilePayments(ctx context.Context, now time.Time) error { |
| continue |
| } |
| switch m.Kind { |
| - case billing.MovementCharge, billing.MovementRefund, billing.MovementRefundFailure: |
| + case billing.MovementCharge, billing.MovementRefund, billing.MovementRefundFailure, billing.MovementPaymentFailure: |
| pending = append(pending, m) |
| if !inSet[m.Charge] { |
| inSet[m.Charge] = true |
diff --git a/internal/console/billingmoneypass_test.go b/internal/console/billingmoneypass_test.go| index 2b34df592..e23cdd352 100644 |
| --- a/internal/console/billingmoneypass_test.go |
| +++ b/internal/console/billingmoneypass_test.go |
| @@ -297,6 +297,49 @@ func TestReconcileRefundOfUnrecordedCharge(t *testing.T) { |
| } |
| } |
| +// A delayed payment method failing after its charge succeeded: the |
| +// failure movement is read through its charge and recorded beside it, and |
| +// the two cancel. |
| +func TestReconcilePaymentFailure(t *testing.T) { |
| + bf := newBillingFixture(t) |
| + now := billingNow |
| + chargeAt, failAt := now.Add(-50*time.Minute), now.Add(-20*time.Minute) |
| + m, rec := testChargeRecord("ch_1", chargeAt, 1200) |
| + rec.Refunds = []billing.Payment{{Movement: "mv_pf_1", Source: "ch_1", Kind: billing.PaymentRefund, Reason: billing.ReasonPaymentFailed, |
| + Customer: "cus_1", Subscription: "sub_1", PaymentIntent: "pi_ch_1", Charge: "ch_1", Amount: -1200, Tax: -200, Currency: "eur", |
| + Settled: -1200, SettledTax: -200, SettledCurrency: "eur", At: failAt}} |
| + bf.setCharge("ch_1", rec) |
| + bf.seedMovement(m) |
| + bf.seedMovement(billing.Movement{ID: "mv_pf_1", Kind: billing.MovementPaymentFailure, Source: "ch_1", Charge: "ch_1", Amount: -1200, Currency: "eur", At: failAt}) |
| + 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) |
| + f, ok := rows["mv_pf_1"] |
| + if len(rows) != 2 || !ok { |
| + t.Fatalf("rows = %v; want the charge and its failure", rows) |
| + } |
| + if f.Reason != billing.ReasonPaymentFailed || f.AccountID != bf.acct.ID { |
| + t.Errorf("failure row %+v", f) |
| + } |
| + if c := rows["mv_ch_1"]; c.Settled-c.SettledTax+f.Settled-f.SettledTax != 0 { |
| + t.Errorf("charge and failure leave revenue %d", c.Settled-c.SettledTax+f.Settled-f.SettledTax) |
| + } |
| + |
| + // A failure movement its charge's read does not carry holds the window. |
| + bf2 := newBillingFixture(t) |
| + m2, rec2 := testChargeRecord("ch_2", chargeAt, 1200) |
| + bf2.setCharge("ch_2", rec2) |
| + bf2.seedMovement(m2) |
| + bf2.seedMovement(billing.Movement{ID: "mv_pf_2", Kind: billing.MovementPaymentFailure, Source: "ch_2", Charge: "ch_2", Amount: -1200, Currency: "eur", At: failAt}) |
| + setCursor(t, bf2.st, now.Add(-2*time.Hour)) |
| + if err := bf2.srv.reconcilePayments(context.Background(), now); err == nil || !strings.Contains(err.Error(), "mv_pf_2") { |
| + t.Fatalf("reconcile = %v; want the window held on mv_pf_2", err) |
| + } |
| + wantCursor(t, bf2.st, now.Add(-2*time.Hour)) |
| +} |
| + |
| func TestReconcileFailedRefundNeverRecorded(t *testing.T) { |
| bf := newBillingFixture(t) |
| now := billingNow |
diff --git a/internal/console/billingpayments_store.go b/internal/console/billingpayments_store.go| index 2b9b65128..0184634f7 100644 |
| --- a/internal/console/billingpayments_store.go |
| +++ b/internal/console/billingpayments_store.go |
| @@ -90,8 +90,8 @@ func matchPayment(q sqlQueryer, r *paymentRow) error { |
| switch { |
| case err == nil: |
| r.AccountID, r.Detail = account, domain |
| - // A reversal keeps its reason: it stays reversed. |
| - if p.Reason != billing.ReasonReversed { |
| + // A reversal or a failed payment keeps its reason. |
| + if p.Reason != billing.ReasonReversed && p.Reason != billing.ReasonPaymentFailed { |
| p.Reason = billing.ReasonDomain |
| } |
| // Only a charge's tax comes from the quoted price; refunds and |
diff --git a/internal/console/billingpayments_store_test.go b/internal/console/billingpayments_store_test.go| index a4cf4b94a..e6ea120bc 100644 |
| --- a/internal/console/billingpayments_store_test.go |
| +++ b/internal/console/billingpayments_store_test.go |
| @@ -175,6 +175,34 @@ func TestRecordPaymentDomainRefundInheritsTax(t *testing.T) { |
| } |
| } |
| +// A domain charge whose payment failed after it succeeded: the failure |
| +// row carries the charge's payment intent, so it matches the domain |
| +// purchase, but keeps its reason and takes the charge's whole tax back. |
| +func TestRecordPaymentDomainPaymentFailure(t *testing.T) { |
| + s, ids := planStore(t, "bab") |
| + if err := s.CreateDomainPurchase(DomainPurchase{AccountID: ids["bab"], Domain: "shop.example.com", App: "web", |
| + Currency: "eur", Amount: 10000, PaymentIntent: "pi_dom"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + recordPayment(t, s, billing.Payment{ |
| + Movement: "mv_dom", Source: "ch_dom", Kind: billing.PaymentOnceOff, Reason: billing.ReasonOther, |
| + PaymentIntent: "pi_dom", Charge: "ch_dom", |
| + Amount: 12000, Currency: "eur", Settled: 12000, Fee: 400, SettledCurrency: "eur", At: paymentAt, |
| + }) |
| + recordPayment(t, s, billing.Payment{ |
| + Movement: "mv_pf", Source: "ch_dom", Kind: billing.PaymentRefund, Reason: billing.ReasonPaymentFailed, |
| + PaymentIntent: "pi_dom", Charge: "ch_dom", Amount: -12000, Currency: "eur", Settled: -12000, SettledCurrency: "eur", |
| + At: paymentAt.Add(72 * time.Hour), |
| + }) |
| + c, f := paymentByMovement(t, s, "mv_dom"), paymentByMovement(t, s, "mv_pf") |
| + if f.Reason != billing.ReasonPaymentFailed || f.AccountID != ids["bab"] || f.Detail != "shop.example.com" { |
| + t.Errorf("failure reason %q account %d detail %q; want payment_failed on bab's domain", f.Reason, f.AccountID, f.Detail) |
| + } |
| + if f.Tax != -c.Tax || f.SettledTax != -c.SettledTax { |
| + t.Errorf("failure tax %d/%d, want the charge's %d/%d negated", f.Tax, f.SettledTax, c.Tax, c.SettledTax) |
| + } |
| +} |
| + |
| func TestRecordPaymentUnmatched(t *testing.T) { |
| s, _ := planStore(t, "bab") |
| p := testCharge("mv_1", "ch_1") |