Skip to content

fix(charges): persist fiat payment amounts - #4779

Merged
turip merged 2 commits into
mainfrom
feat/charge-payment-fiat-amount
Jul 24, 2026
Merged

turip merged 2 commits into
mainfrom
feat/charge-payment-fiat-amount

Conversation

@turip

@turip turip commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Summary

  • make charge payment amounts explicitly represent fiat amounts while preserving the existing database column
  • persist the final invoice-line total for invoiced credit purchases
  • derive external credit-purchase fiat amounts from cost basis using the settlement currency precision
  • backfill existing invoiced credit-purchase payment rows from their invoice-line totals
  • cover invoiced and external credit purchases in the ledger-backed integration suite

Testing

  • nix develop --impure .#ci -c make lint-go-fast
  • nix develop --impure .#ci -c make test-nocache (6321 passed, 9 skipped)

Summary by CodeRabbit

  • Bug Fixes

    • Payment settlements now consistently store and surface the correct fiat amount across credit purchases, flat-fee charges, and usage-based billing.
    • External credit-purchase payments are now authorized/settled using a currency-rounded fiat amount.
    • Invoice payment and external payment records now reconcile to the same line totals.
  • Data Updates

    • Added a migration to backfill and validate existing credit-purchase invoiced payment amounts so they match their corresponding invoice line totals.

Greptile Summary

This PR corrects persisted payment amounts to represent fiat value consistently.

  • Renames the payment model and generated Ent field from Amount to FiatAmount while retaining the existing database column.
  • Persists invoice-line totals for invoiced credit purchases and cost-basis-derived, currency-rounded totals for external purchases.
  • Backfills existing invoiced credit-purchase payments and expands integration coverage for invoiced and external settlement paths.

Confidence Score: 5/5

The PR appears safe to merge, with no blocking failures remaining from the reviewed follow-up threads.

No blocking failure remains.

Important Files Changed

Filename Overview
openmeter/billing/charges/creditpurchase/service/invoice.go Persists the finalized invoice-line total as the invoiced credit-purchase fiat amount.
openmeter/billing/charges/creditpurchase/service/realizations/service.go Derives external-payment fiat amounts from credit quantity and cost basis, rounded to settlement-currency precision.
openmeter/billing/charges/models/payment/models.go Makes the payment amount's fiat semantics explicit in the domain model and validation.
openmeter/billing/charges/models/payment/mixin.go Maps the renamed Ent field to the existing physical amount database column.
tools/migrate/migrations/20260724082957_backfill_credit_purchase_invoice_fiat_amount.up.sql Validates invoice-line references and backfills invoiced credit-purchase payment amounts from line totals.

Reviews (2): Last reviewed commit: "fix(charges): address payment review fee..." | Re-trigger Greptile

Context used:

@turip
turip requested a review from a team as a code owner July 24, 2026 09:16
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Payment settlements now expose FiatAmount, with persistence and validation updated accordingly. External authorization calculates rounded fiat values from settlement cost basis, invoice flows use invoice-line totals, related tests are updated, and a migration backfills existing invoice payment amounts.

Changes

Fiat amount settlement alignment

Layer / File(s) Summary
Fiat amount payment contract
openmeter/billing/charges/models/payment/*
Payment settlement fields, JSON serialization, validation, database accessors, and mutation paths now use FiatAmount.
Rounded external fiat amount
openmeter/billing/charges/creditpurchase/service/realizations/*, openmeter/billing/charges/creditpurchase/service/external_test.go, openmeter/billing/charges/service/creditpurchase_test.go
External authorization computes a rounded fiat amount from the external settlement cost basis and stores it in the payment payload; related fixtures and assertions are updated.
Invoice and usage payment propagation
openmeter/billing/charges/creditpurchase/service/invoice.go, openmeter/billing/charges/flatfee/service/payment.go, openmeter/billing/charges/usagebased/service/run/*, openmeter/ledger/chargeadapter/usagebased_test.go
Invoice and usage-based payment creation uses invoice-line totals as FiatAmount, with matching test fixtures and settlement assertions.
Invoice payment amount backfill
tools/migrate/migrations/20260724082957_backfill_credit_purchase_invoice_fiat_amount.up.sql
A transactional migration validates invoice-line references and totals, backfills mismatched stored amounts, and verifies completion.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CreditPurchase
  participant ExternalAuthorization
  participant PaymentPersistence
  CreditPurchase->>ExternalAuthorization: credit amount and settlement
  ExternalAuthorization->>ExternalAuthorization: calculate rounded fiat amount
  ExternalAuthorization->>PaymentPersistence: create payment with FiatAmount
  PaymentPersistence-->>CreditPurchase: persisted settlement
Loading

Possibly related PRs

Suggested labels: area/billing

Suggested reviewers: tothandras, mark-vass-konghq

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: persisting fiat payment amounts across charge payment flows.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/charge-payment-fiat-amount

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@@ -0,0 +1,59 @@
-- Repair invoiced credit-purchase payments that stored the purchased credit amount

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Backfill lacks migration coverage

This hand-written data repair has no dedicated migration test covering representative existing rows and its abort conditions, leaving upgrade behavior and destructive backfill mistakes outside the repository's migration test safeguards.

Knowledge Base Used: Data layer: ent schema, migrations, and generated client

Prompt To Fix With AI
This is a comment left during a code review.
Path: tools/migrate/migrations/20260724082957_backfill_credit_purchase_invoice_fiat_amount.up.sql
Line: 1

Comment:
**Backfill lacks migration coverage**

This hand-written data repair has no dedicated migration test covering representative existing rows and its abort conditions, leaving upgrade behavior and destructive backfill mistakes outside the repository's migration test safeguards.

**Knowledge Base Used:** [Data layer: ent schema, migrations, and generated client](https://app.greptile.com/openmeter/-/custom-context/knowledge-base/openmeterio/openmeter/-/docs/data-layer.md)

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving a dedicated migration test out intentionally per maintainer direction for this change. The SQL consistency guards remain in place, and Atlas migration validation and lint both pass locally.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/billing/charges/creditpurchase/service/external_test.go (1)

155-158: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep an assertion for the created payment’s fiat amount.

This test no longer verifies the behavior introduced by this PR. With a rounded credit amount of 100.12 and a cost basis of 0.5, the external payment should receive 50.06; regressions in multiplication or settlement-currency rounding would currently pass.

Suggested assertion
 err = stateMachine.FireAndActivate(t.Context(), billing.TriggerAuthorized)
 require.NoError(t, err)
 
+require.Equal(t, 50.06, adapter.createdExternalPayment.Base.FiatAmount.InexactFloat64())
 handler.AssertExpectations(t)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/creditpurchase/service/external_test.go` around
lines 155 - 158, The payment authorization test should continue asserting the
created external payment’s fiat amount. In the flow around
stateMachine.FireAndActivate, retrieve the created payment from the existing
test setup and assert its fiat amount is 50.06, covering multiplication and
settlement-currency rounding.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@openmeter/billing/charges/creditpurchase/service/external_test.go`:
- Around line 155-158: The payment authorization test should continue asserting
the created external payment’s fiat amount. In the flow around
stateMachine.FireAndActivate, retrieve the created payment from the existing
test setup and assert its fiat amount is 50.06, covering multiplication and
settlement-currency rounding.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cbd8c5dd-3ffe-4ee0-859a-30b1bf8c4f16

📥 Commits

Reviewing files that changed from the base of the PR and between fab8c28 and d949483.

⛔ Files ignored due to path filters (23)
  • openmeter/ent/db/chargecreditpurchaseexternalpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment/chargecreditpurchaseexternalpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseexternalpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseinvoicedpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseinvoicedpayment/chargecreditpurchaseinvoicedpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseinvoicedpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseinvoicedpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargecreditpurchaseinvoicedpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrunpayment/chargeusagebasedrunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrunpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrunpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrunpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (12)
  • openmeter/billing/charges/creditpurchase/service/external_test.go
  • openmeter/billing/charges/creditpurchase/service/invoice.go
  • openmeter/billing/charges/creditpurchase/service/realizations/service.go
  • openmeter/billing/charges/flatfee/service/payment.go
  • openmeter/billing/charges/models/payment/mixin.go
  • openmeter/billing/charges/models/payment/models.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/usagebased/service/run/payment.go
  • openmeter/billing/charges/usagebased/service/run/payment_test.go
  • openmeter/ledger/chargeadapter/usagebased_test.go
  • tools/migrate/migrations/20260724082957_backfill_credit_purchase_invoice_fiat_amount.down.sql
  • tools/migrate/migrations/20260724082957_backfill_credit_purchase_invoice_fiat_amount.up.sql

@turip turip added the release-note/bug-fix Release note: Bug Fixes label Jul 24, 2026
@turip

turip commented Jul 24, 2026

Copy link
Copy Markdown
Member Author

Addressed the external fiat-amount coverage suggestion in 2d2fec9 by extending the ledger-backed integration scenario instead of restoring the service unit assertion. The scenario supplies 100.123 credits, exercises normalization to 100.12 through the production path, and asserts a 50.06 fiat payment.

@turip
turip merged commit 6457e4b into main Jul 24, 2026
27 of 29 checks passed
@turip
turip deleted the feat/charge-payment-fiat-amount branch July 24, 2026 10:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants