Skip to content

[PM-46970] feat: Post non-charge cash application transactions - #8997

Draft
clayhere wants to merge 2 commits into
mainfrom
billing/PM-46970/non-charge-cash-application-transactions
Draft

clayhere wants to merge 2 commits into
mainfrom
billing/PM-46970/non-charge-cash-application-transactions

Conversation

@clayhere

@clayhere clayhere commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

🎟️ Tracking

PM-46970

📔 Objective

Billing Operations cash application applies payments received by check, wire or bank transfer, with no Stripe charge,
to Stripe invoices as Payment Records: in the Stripe Dashboard ("Mark as paid" > "Add an external payment" or "Apply existing
payments") or through the API. Stripe creates no charge, so charge.succeeded never fires and no Bitwarden Transaction
is written; Billing Operations re-enters every payment in Admin. This change posts them automatically.

Events. invoice_payment.paid fires once per payment applied to a subscription invoice (verified in Stripe test
mode on API version 2026-06-24.dahlia). invoice.paid is handled as error handling only: Bitwarden bills only through
subscriptions, but a subscription invoice can lose its subscription link (for example through a manually added pending
invoice item), and Stripe then sends no invoice_payment.paid for its payments. Both handlers check the event payload
first, so card payments, invoices that still have their subscription link (for invoice.paid) and credit-only invoices
cost no extra Stripe call, then hand the payment to NonChargeCashApplicationRecorder.

What is posted. One Transaction per invoice payment whose Payment Record has a custom payment method or processor:

  • Type Credit, Gateway Bank, GatewayId the invoice payment ID (inpay_...), matching manual Admin entries.
    The existing unique index on (Gateway, GatewayId) makes redelivery and concurrent delivery idempotent, and an
    already-recorded payment is found before any Stripe call.
  • Owner one organization, user or provider, by fixed precedence organizationId, then userId, then providerId:
    from the metadata Stripe copied onto the invoice, else the invoice's own subscription, else, as for card charges, the
    first of the customer's subscriptions that is not canceled and has an owner. IDs are read from the start of the value,
    so text appended on purpose and surrounding spaces are ignored; malformed IDs never throw. With no owner, nothing is
    written and a warning is logged.
  • Amount the invoice payment's amount_paid; date its paid_at (as card charges use charge.Created);
    payment method check, wire, otherwise bank account; Details in the manual-entry style, built from the
    date received and paying entity that Billing Operations enters in the Payment Record's reference
    (<date> - <payer>), plus the payment type and amount: 11/10/2026 - EXAMPLE PAYER LTD on a $671.34 wire becomes
    11/10/2026 In Wire - EXAMPLE PAYER LTD $671.34. A trailing amount in the reference equal to the payment is dropped; a
    different one (the total of a wire that paid several invoices) is kept as $1,200.00 of $5,000.00. Without a
    reference, the Stripe customer name is the payer. Max 100 characters.

What is not posted.

  • The record Stripe generates for a bare out-of-band payment ("Paid out of band", custom payment method without a
    custom type). That is how Bitwarden's PayPal flow settles invoices, so PayPal is unaffected.
  • Fees (payment type starting or ending with the word FEE, e.g. a "Wire Fee" applied alongside a short wire); the actual
    payment on the same invoice still posts at its own amount.
  • Stripe charges, Stripe-processed Payment Records, unpaid and zero-amount payments; non-USD payments are logged and
    skipped.

An audit log line for every posted row is built in under the Bit.Billing.NonChargeCashApplicationAudit category, off
by default (None in appsettings.json).

Feature flag. Released dark behind pm-46970-post-stripe-cash-application-transactions
(FeatureFlagKeys.PM46970_PostStripeCashApplicationTransactions, Billing Team section). While it is off the handlers do
nothing beyond Billing's standard cloud-region check. Each environment's Stripe webhook endpoint needs
invoice_payment.paid and invoice.paid added, starting with USDEV and USQA for QA.

📸 Test cases

Automated: Billing.Test 432 passed (124 new), 100% line coverage of the recorder and both handlers. The two new
Billing.IntegrationTest scenarios (PostingStripeCashApplicationTransactionsTests) cover the invoice,
invoice.customer and payments expands and are gated on RUN_STRIPE_INTEGRATION_TESTS like the rest of the project.

Run locally against Stripe test mode, with the flag on:

# Case Result
1 invoice_payment.paid, wire applied to a subscription invoice through the API with reference 11/10/2026 - EXAMPLE PAYER LTD (integration test) 1 Transaction for the organization, Details 11/10/2026 In Wire - EXAMPLE PAYER LTD $150.00; redelivery adds nothing
2 invoice.paid, check applied to an invoice without a subscription link (integration test) 1 Transaction for the owner of the customer's subscription
3 Dashboard "Mark as paid" > "Add an external payment" (check, and a back-dated wire) Payment Record with a custom payment method; posted, dated with the Dashboard's effective date
4 Invoice paid out of band with no payment details (the PayPal flow) Stripe's "Paid out of band" record; nothing posted
5 Refund reported on a Payment Record Stripe sends no event; nothing changes
6 Signed events through the local Billing host and SQL Server: duplicate and concurrent delivery, owner ID with appended text and leading space, flag off One row per payment; appended-text ID resolves; flag off writes nothing

🤖 AI-assisted review

Standard local review (/bitwarden-code-review:code-review-local) on the final commit: approved, no findings. No
skips and no deferred findings.

Billing Operations cash application applies payments received directly
(check, wire, bank transfer), not processed by Stripe, to Stripe
invoices as Payment Records: in the Dashboard ("Mark as paid" > "Add an
external payment" or "Apply existing payments") or through the API
(attach a reported Payment Record). No charge is created, so
charge.succeeded never fires and no Bitwarden Transaction is written;
Billing Operations re-enters each payment in Admin. This posts them
automatically, so cash application can run at scale with customer
billing history kept accurate.

Handle invoice_payment.paid. Captured in Stripe test mode on API version
2026-06-24.dahlia, Dashboard and API entries both emit it once per
payment applied to a subscription invoice, with payment.type =
payment_record.

Also handle invoice.paid, as error handling only. Bitwarden bills only
through subscriptions, but a subscription invoice can lose its
subscription link (e.g. through a manually added pending invoice item).
Stripe then sends no invoice_payment.paid for its payments, only
invoice.paid, so the handler reads the invoice's payments and posts each
one the same way. Invoices that still have their subscription link, and
credit-only invoices, are filtered from the event payload at no extra
Stripe call.

For payments whose Payment Record has a custom (not Stripe-processed)
payment method or processor, create one Transaction per invoice payment:

- Type Credit, Gateway Bank, GatewayId = invoice payment ID, matching
  transactions entered manually in Admin. The unique (Gateway,
  GatewayId) index makes replays and concurrent deliveries idempotent; a
  replay never changes the saved row (a different amount, e.g. edited in
  Admin, logs a warning).
- Owner: one organization, user or provider, by fixed precedence
  organizationId, then userId, then providerId. Taken from the metadata
  Stripe copied onto the invoice, else the invoice's own subscription
  (even if since canceled), else, as for card charges, the first of the
  customer's subscriptions that is not canceled and has an owner. With
  no owner, nothing is written and a warning is logged. IDs are read
  from the start of the value, so text appended on purpose and
  surrounding spaces are ignored; malformed IDs never throw.
- The record Stripe generates when an invoice is paid out of band with
  no payment details ("Paid out of band", custom payment method without
  a custom type) is skipped: that is how Bitwarden's PayPal flow settles
  invoices, and cash application always records the payment details.
- Fees applied to settle an invoice (a payment type starting or ending
  with the word FEE, e.g. "Wire Fee") are skipped; the actual payment on
  the same invoice still posts at its own amount.
- Method from the payment type entered in Stripe: check, wire, anything
  else bank account. Details in the manual style: Billing Operations
  enters the date received and the paying entity in the reference as
  "<date> - <payer>" (checks add "#<check number>"), and the payment
  type and amount are added, e.g. "11/10/2026 - EXAMPLE PAYER LTD" on a
  $671.34 wire becomes "11/10/2026 In Wire - EXAMPLE PAYER LTD $671.34".
  A trailing amount in the reference equal to the payment is dropped;
  a different one, such as the total of a wire that paid several
  invoices, is kept as "of $X" (e.g. "... LTD $1,200.00 of $5,000.00").
  Without a reference, the Stripe customer name is the payer. Shortened
  to 100 characters if needed.
- Date is the invoice payment's paid_at, Stripe's exact UTC timestamp,
  as card charges use charge.Created.
- Amount is the invoice payment's amount_paid, so only new money is
  recorded: credit already in Stripe is never posted again.
- Ignores Stripe charges, Stripe-processed Payment Records, unpaid and
  zero-amount payments; logs and skips non-USD payments.
- Every row written can be logged as an audit trail under the
  Bit.Billing.NonChargeCashApplicationAudit category; off by default
  (None in appsettings.json).

Recording lives in NonChargeCashApplicationRecorder, shared by both
handlers. Adds both events to the cloud-region check, InvoicePayment and
PaymentRecord retrieval to IStripeFacade and IStripeEventService,
sanitized test fixtures captured from Stripe test mode, and Stripe
integration scenarios for both events in Billing.IntegrationTest.

Released dark behind the LaunchDarkly flag
pm-46970-post-stripe-cash-application-transactions: while it is off, the
handlers do nothing beyond the standard cloud-region check. The Stripe
webhook endpoints must be subscribed to invoice_payment.paid and
invoice.paid.
@clayhere clayhere added the ai-review Request a Claude code review label Nov 25, 2026
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Bitwarden Claude Code Review

Overall Assessment: APPROVE

Re-reviewed the PR at d574958. The only change since the previous review is the IsFee refactor in NonChargeCashApplicationRecorder, which splits the check into hasFeeAtStart and hasFeeAtEnd. Both checks still require words.Length > 0, so a blank or missing payment type cannot cause an index-out-of-range error. The rest of the change was checked again: the invoice_payment.paid and invoice.paid handlers, the feature flag, idempotency through the lookup before insert plus the unique IX_Transaction_Gateway_GatewayId index, cloud-region validation for both new event types, TryAdd* DI registration, and the audit log category. No findings met the bar for posting.

@clayhere clayhere added the t:feature Change Type - Feature Development label Nov 25, 2026
@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.71598% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.33%. Comparing base (2cbc150) to head (d574958).

Files with missing lines Patch % Lines
...mplementations/NonChargeCashApplicationRecorder.cs 94.36% 0 Missing and 15 partials ⚠️
...c/Billing/Services/Implementations/StripeFacade.cs 0.00% 5 Missing ⚠️
...ing/Services/Implementations/StripeEventService.cs 66.66% 2 Missing and 2 partials ⚠️
src/Billing/Startup.cs 0.00% 3 Missing ⚠️
...vices/Implementations/InvoicePaymentPaidHandler.cs 93.33% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8997      +/-   ##
==========================================
+ Coverage   69.26%   69.33%   +0.07%     
==========================================
  Files        2774     2777       +3     
  Lines      119039   119375     +336     
  Branches    10937    11001      +64     
==========================================
+ Hits        82453    82772     +319     
+ Misses      34029    34028       -1     
- Partials     2557     2575      +18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-review Request a Claude code review t:feature Change Type - Feature Development

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant