Repository navigation
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR introduces external credit purchase payment settlement capabilities by adding new adapter interfaces ( Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Service
participant Adapter
participant Handler
participant DB
Client->>Service: UpdateExternalCreditPurchasePaymentState(ctx, input)
Service->>Adapter: GetCreditPurchaseCharge(chargeID, expanded)
Adapter->>DB: Query charge with realizations
DB-->>Adapter: chargeEntity
Adapter-->>Service: CreditPurchaseCharge
alt TargetPaymentState == Authorized
Service->>Handler: HandleExternalCreditPurchasePaymentAuthorized(ctx, charge)
Handler->>Service: LedgerTransactionGroupReference
Service->>Adapter: CreateExternalPaymentSettlement(ctx, input)
Adapter->>DB: Insert ChargeExternalPaymentSettlement
DB-->>Adapter: ExternalPaymentSettlement
Adapter->>Adapter: UpdateCreditPurchaseCharge(charge)
Adapter->>DB: Update charge with settlement link
else TargetPaymentState == Settled
Service->>Adapter: GetCreditPurchaseCharge(chargeID, expanded)
Adapter-->>Service: CreditPurchaseCharge
Service->>Handler: HandleExternalCreditPurchasePaymentSettled(ctx, charge)
Handler->>Service: LedgerTransactionGroupReference
Service->>Adapter: UpdateExternalPaymentSettlement(ctx, settlement)
Adapter->>DB: Update ChargeExternalPaymentSettlement to Settled
DB-->>Adapter: Updated settlement
Adapter->>Adapter: UpdateCreditPurchaseCharge(charge)
Adapter->>DB: Mark charge as Final
end
Adapter-->>Service: Updated CreditPurchaseCharge
Service-->>Client: CreditPurchaseCharge
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
1d91585 to
2a3ff5b
Compare
41b1b02 to
4cb527b
Compare
66e8bec to
642bd36
Compare
642bd36 to
a2d4847
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
openmeter/billing/charges/chargecreditpurchase.go (1)
415-427: Fail fast on unsupported target payment states.
Validate()accepts any validPaymentSettlementStatus, but onlyauthorized/settledare handled later. Rejecting unsupported states here avoids unnecessary transaction+DB work.As per coding guidelines, "Performance should be a priority in critical code paths. Anything related to ... database operations ... should be vetted for potential performance bottlenecks."💡 Suggested fix
if err := i.TargetPaymentState.Validate(); err != nil { errs = append(errs, fmt.Errorf("target payment state: %w", err)) + } else if i.TargetPaymentState != PaymentSettlementStatusAuthorized && + i.TargetPaymentState != PaymentSettlementStatusSettled { + errs = append(errs, fmt.Errorf("target payment state must be authorized or settled")) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 415 - 427, Update the Validate method on UpdateExternalCreditPurchasePaymentStateInput to fail fast for unsupported PaymentSettlementStatus values: after validating i.TargetPaymentState (and its Validate if needed), explicitly check that i.TargetPaymentState is one of the handled values (authorized or settled) and return an error (or append and return) if it is any other enum value; update the validation logic in UpdateExternalCreditPurchasePaymentStateInput.Validate to reject unsupported statuses so later transaction/DB work is not executed for invalid targets.openmeter/billing/charges/service/service_test.go (1)
524-529: Typo: "initated" should be "initiated".Minor typo that appears in several places (
initatedCallback,initatedTrnsID).Suggested fix (example for one occurrence)
- initatedCallback := newCountedLedgerTransactionCallback[charges.CreditPurchaseCharge]() - s.CreditPurchaseTestHandler.onCreditPurchaseInitiated = initatedCallback.Handler(s.T(), func(t *testing.T, charge charges.CreditPurchaseCharge) { + initiatedCallback := newCountedLedgerTransactionCallback[charges.CreditPurchaseCharge]() + s.CreditPurchaseTestHandler.onCreditPurchaseInitiated = initiatedCallback.Handler(s.T(), func(t *testing.T, charge charges.CreditPurchaseCharge) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/service_test.go` around lines 524 - 529, Rename the misspelled identifiers from "initated" to "initiated" across the test file; specifically update variables like initatedCallback and initatedTrnsID and any references where they are passed into or returned from helpers such as newCountedLedgerTransactionCallback and assignments like s.CreditPurchaseTestHandler.onCreditPurchaseInitiated so all usages (declarations, assignments, Handler calls, and assertions) consistently use initiatedCallback / initiatedTrnsID etc.openmeter/billing/charges/service/creditpurchase/creditpurchase.go (1)
16-28: Minor: Consider using "nil" instead of "null" in error messages.Go convention typically uses "nil" terminology. Small thing, but keeps the language consistent with Go idioms.
Suggested change
func (c Config) Validate() error { var errs []error if c.Adapter == nil { - errs = append(errs, errors.New("adapter cannot be null")) + errs = append(errs, errors.New("adapter cannot be nil")) } if c.CreditPurchaseHandler == nil { - errs = append(errs, errors.New("credit purchase handler cannot be null")) + errs = append(errs, errors.New("credit purchase handler cannot be nil")) } return errors.Join(errs...) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/creditpurchase/creditpurchase.go` around lines 16 - 28, Update the error messages in Config.Validate() to use "nil" instead of "null": replace "adapter cannot be null" with "adapter cannot be nil" and "credit purchase handler cannot be null" with "credit purchase handler cannot be nil" (these strings are in the Validate method of the Config type). Keep the rest of the logic unchanged.openmeter/billing/charges/adapter/creditpurchase.go (1)
45-52: Manual propagation of ExternalPaymentSettlement could be fragile.The pattern of mapping from DB with
ExpandNoneand then manually copyingExternalPaymentSettlementfrom the input works, but it's a bit subtle. If someone later changes the mapping logic or forgets this pattern exists, it could lead to data being lost silently.A brief comment explaining why this is necessary would help future maintainers:
Suggested documentation
mapped, err := MapCreditPurchaseChargeFromDB(dbEntity, charges.ExpandNone) if err != nil { return charges.CreditPurchaseCharge{}, err } + // ExternalPaymentSettlement is managed separately and not loaded with ExpandNone, + // so we preserve the in-memory state from the input. mapped.State.ExternalPaymentSettlement = charge.State.ExternalPaymentSettlement return mapped, nil🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/creditpurchase.go` around lines 45 - 52, The mapping copies ExternalPaymentSettlement manually after calling MapCreditPurchaseChargeFromDB(dbEntity, charges.ExpandNone) — add a concise inline comment above the manual assignment (mapped.State.ExternalPaymentSettlement = charge.State.ExternalPaymentSettlement) explaining that MapCreditPurchaseChargeFromDB is invoked with charges.ExpandNone and therefore intentionally omits ExternalPaymentSettlement, so we must explicitly propagate charge.State.ExternalPaymentSettlement here to preserve that field; reference MapCreditPurchaseChargeFromDB, charges.ExpandNone, mapped.State.ExternalPaymentSettlement and charge.State.ExternalPaymentSettlement in the comment so future maintainers understand the rationale and avoid accidental removal.openmeter/billing/charges/service/creditpurchase/external.go (1)
59-88: Consider persisting the charge after creating the external payment settlement.The function creates the external payment settlement and assigns it to
charge.State.ExternalPaymentSettlement, but the charge itself isn't persisted afterward. This seems intentional sinceonExternalCreditPurchasecalls this and may persist later, but whenHandleExternalCreditPurchasePaymentAuthorizedis called directly (e.g., viaUpdateExternalCreditPurchasePaymentStatein tests), the charge state might be out of sync with what's stored.If this is intentional (caller is responsible for persistence), it might be worth documenting that contract in a comment.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/creditpurchase/external.go` around lines 59 - 88, HandleExternalCreditPurchasePaymentAuthorized assigns paymentSettlement to charge.State.ExternalPaymentSettlement but does not persist the updated charge; update the function to persist the charge after calling s.adapter.CreateExternalPaymentSettlement (i.e., after you set charge.State.ExternalPaymentSettlement) by invoking the service's charge persistence method (the adapter/repository method your codebase uses to save charges) so storage and in-memory state stay in sync when this handler is called directly (e.g., from UpdateExternalCreditPurchasePaymentState in tests); if the design intentionally leaves persistence to callers, add a brief comment in HandleExternalCreditPurchasePaymentAuthorized stating that the caller is responsible for persisting the returned charge.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 153-173: The code assumes cp.CreditGrantedAt is non-nil when
cp.CreditGrantTransactionGroupID is set and calls
cp.CreditGrantedAt.In(time.UTC), which can panic; update the block that builds
charges.TimedLedgerTransactionGroupReference (where cp,
CreditGrantTransactionGroupID and CreditGrantedAt are used) to first check
cp.CreditGrantedAt != nil and only call .In(time.UTC) when non-nil, otherwise
leave the Time as the zero value (or omit setting it if the Time field is a
pointer), so that creating the TimedLedgerTransactionGroupReference is safe when
CreditGrantedAt is nil.
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 276-279: Update the error message to match the renamed struct:
when unmarshalling into ExternalCreditPurchaseSettlement (the variable v of type
ExternalCreditPurchaseSettlement), change the fmt.Errorf message so it
references ExternalCreditPurchaseSettlement instead of
ExternalAuthorizedCreditPurchaseSettlement; locate the json.Unmarshal call where
v := &ExternalCreditPurchaseSettlement{} and adjust the wrapped error string
accordingly.
- Around line 440-444: The comment's flow documentation references a
non-existent method name; update the text to reference the actual interface
method OnCreditPurchaseInitiated (instead of OnCreditPurchase) and ensure
subsequent bullet points consistently use the real method names like
OnCreditPurchasePaymentAuthorized and OnCreditPurchasePaymentSettled so the flow
doc matches the interface and implementation.
In `@openmeter/billing/charges/service/service.go`:
- Around line 21-24: Handlers.Validate() currently only validates the FlatFee
handler, so add validation for the new CreditPurchase field in the Handlers
struct: update the Handlers.Validate() method to call the CreditPurchase
handler's Validate (or equivalent) just like FlatFee, propagate/return any
validation errors with clear context (e.g., "credit purchase handler validation
failed") so invalid configs are caught early during service construction;
reference the Handlers struct, Handlers.Validate(), FlatFee and CreditPurchase
symbols when making the change.
In
`@tools/migrate/migrations/20260304081726_billing-charges-credit-purchase.down.sql`:
- Line 16: The down migration drops "credit_granted_at" and
"credit_grant_transaction_group_id" then re-adds "status" as NOT NULL which will
fail on non-empty tables; instead, add "status" as nullable on table
charge_credit_purchases, backfill existing rows to the initial state value
"created" (UPDATE charge_credit_purchases SET status = 'created' WHERE status IS
NULL), and then ALTER TABLE charge_credit_purchases ALTER COLUMN status SET NOT
NULL to enforce the constraint; reference the "charge_credit_purchases" table
and the "status" column when implementing these steps.
In
`@tools/migrate/migrations/20260304081726_billing-charges-credit-purchase.up.sql`:
- Line 30: Remove the redundant unique index creation and its corresponding
drop: delete the CREATE UNIQUE INDEX "chargeexternalpaymentsettlement_id"
statement that references table "charge_external_payment_settlements" (it
duplicates the PRIMARY KEY already created for that table) and also remove the
matching DROP INDEX "chargeexternalpaymentsettlement_id" from the down migration
so the migration no longer creates/drops a redundant index.
---
Nitpick comments:
In `@openmeter/billing/charges/adapter/creditpurchase.go`:
- Around line 45-52: The mapping copies ExternalPaymentSettlement manually after
calling MapCreditPurchaseChargeFromDB(dbEntity, charges.ExpandNone) — add a
concise inline comment above the manual assignment
(mapped.State.ExternalPaymentSettlement =
charge.State.ExternalPaymentSettlement) explaining that
MapCreditPurchaseChargeFromDB is invoked with charges.ExpandNone and therefore
intentionally omits ExternalPaymentSettlement, so we must explicitly propagate
charge.State.ExternalPaymentSettlement here to preserve that field; reference
MapCreditPurchaseChargeFromDB, charges.ExpandNone,
mapped.State.ExternalPaymentSettlement and
charge.State.ExternalPaymentSettlement in the comment so future maintainers
understand the rationale and avoid accidental removal.
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 415-427: Update the Validate method on
UpdateExternalCreditPurchasePaymentStateInput to fail fast for unsupported
PaymentSettlementStatus values: after validating i.TargetPaymentState (and its
Validate if needed), explicitly check that i.TargetPaymentState is one of the
handled values (authorized or settled) and return an error (or append and
return) if it is any other enum value; update the validation logic in
UpdateExternalCreditPurchasePaymentStateInput.Validate to reject unsupported
statuses so later transaction/DB work is not executed for invalid targets.
In `@openmeter/billing/charges/service/creditpurchase/creditpurchase.go`:
- Around line 16-28: Update the error messages in Config.Validate() to use "nil"
instead of "null": replace "adapter cannot be null" with "adapter cannot be nil"
and "credit purchase handler cannot be null" with "credit purchase handler
cannot be nil" (these strings are in the Validate method of the Config type).
Keep the rest of the logic unchanged.
In `@openmeter/billing/charges/service/creditpurchase/external.go`:
- Around line 59-88: HandleExternalCreditPurchasePaymentAuthorized assigns
paymentSettlement to charge.State.ExternalPaymentSettlement but does not persist
the updated charge; update the function to persist the charge after calling
s.adapter.CreateExternalPaymentSettlement (i.e., after you set
charge.State.ExternalPaymentSettlement) by invoking the service's charge
persistence method (the adapter/repository method your codebase uses to save
charges) so storage and in-memory state stay in sync when this handler is called
directly (e.g., from UpdateExternalCreditPurchasePaymentState in tests); if the
design intentionally leaves persistence to callers, add a brief comment in
HandleExternalCreditPurchasePaymentAuthorized stating that the caller is
responsible for persisting the returned charge.
In `@openmeter/billing/charges/service/service_test.go`:
- Around line 524-529: Rename the misspelled identifiers from "initated" to
"initiated" across the test file; specifically update variables like
initatedCallback and initatedTrnsID and any references where they are passed
into or returned from helpers such as newCountedLedgerTransactionCallback and
assignments like s.CreditPurchaseTestHandler.onCreditPurchaseInitiated so all
usages (declarations, assignments, Handler calls, and assertions) consistently
use initiatedCallback / initiatedTrnsID etc.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 65b5949b-2d8e-4c06-8dc8-382754570885
⛔ Files ignored due to path filters (31)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_delete.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (31)
openmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/charge.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/creditpurchase.goopenmeter/billing/charges/adapter/external.goopenmeter/billing/charges/adapter/faltfee.goopenmeter/billing/charges/adapter/get.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeflatfee.goopenmeter/billing/charges/chargeusagebased.goopenmeter/billing/charges/errors.goopenmeter/billing/charges/payment.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase.goopenmeter/billing/charges/service/creditpurchase/creditpurchase.goopenmeter/billing/charges/service/creditpurchase/external.goopenmeter/billing/charges/service/creditpurchase/promotional.goopenmeter/billing/charges/service/flatfee/flatfee.goopenmeter/billing/charges/service/flatfee/payment.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/service/invoicependinglines.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/service/service_test.goopenmeter/billing/charges/stdinvoice.goopenmeter/ent/schema/charges.gotools/migrate/migrations/20260304081726_billing-charges-credit-purchase.down.sqltools/migrate/migrations/20260304081726_billing-charges-credit-purchase.up.sql
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
openmeter/billing/charges/chargecreditpurchase.go (2)
440-444:⚠️ Potential issue | 🟡 MinorAlign the flow docs with the actual handler method names.
The comments still mention
OnCreditPurchase, but the interface method isOnCreditPurchaseInitiated.📝 Suggested fix
-// Cost basis > 0 credit purchases are handled by the OnCreditPurchase method, which is the initial call. +// Cost basis > 0 credit purchases are handled by the OnCreditPurchaseInitiated method, which is the initial call. // Happy path: -// - OnCreditPurchase is called +// - OnCreditPurchaseInitiated is called // - OnCreditPurchasePaymentAuthorized is called // - OnCreditPurchasePaymentSettled is called🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 440 - 444, The inline flow comment references the wrong handler name: replace mentions of OnCreditPurchase with the actual interface method name OnCreditPurchaseInitiated and ensure the sequence lists the correct handlers (OnCreditPurchaseInitiated -> OnCreditPurchasePaymentAuthorized -> OnCreditPurchasePaymentSettled); update the comment block around the flow (the lines documenting the "Happy path") to use those exact identifiers so it matches the implemented handler names.
276-279:⚠️ Potential issue | 🟡 MinorUpdate the stale external settlement type name in the unmarshal error text.
The code unmarshals into
ExternalCreditPurchaseSettlement, but the wrapped error still saysExternalAuthorizedCreditPurchaseSettlement.✏️ Suggested fix
v := &ExternalCreditPurchaseSettlement{} if err := json.Unmarshal(bytes, v); err != nil { - return fmt.Errorf("failed to JSON deserialize ExternalAuthorizedCreditPurchaseSettlement: %w", err) + return fmt.Errorf("failed to JSON deserialize ExternalCreditPurchaseSettlement: %w", err) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargecreditpurchase.go` around lines 276 - 279, The unmarshal error message is using the stale type name "ExternalAuthorizedCreditPurchaseSettlement" while the code creates v := &ExternalCreditPurchaseSettlement{}; update the fmt.Errorf call wrapped around json.Unmarshal(bytes, v) to reference the correct type name "ExternalCreditPurchaseSettlement" so the error text matches the actual struct (look for the json.Unmarshal call that populates ExternalCreditPurchaseSettlement and change the string passed to fmt.Errorf).
🧹 Nitpick comments (3)
openmeter/billing/charges/errors.go (1)
72-77: Consider making settlement error wording state-agnostic for clarity.
ErrPaymentAlreadySettledis currently used when status is “not authorized” (seeopenmeter/billing/charges/service/flatfee/payment.goLine 47 andopenmeter/billing/charges/service/creditpurchase/external.goLine 99), so the message can read too narrowly. Small wording tweaks here would make behavior clearer for future states too.♻️ Suggested wording update
var ErrPaymentAlreadySettled = models.NewValidationIssue( ErrCodePaymentAlreadySettled, - "payment already settled", + "payment cannot be settled from current state", models.WithCriticalSeverity(), commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest), ) var ErrCannotSettleNotAuthorizedPayment = models.NewValidationIssue( ErrCodeCannotSettleNotAuthorizedPayment, - "cannot settle not authorized payment", + "cannot settle payment that is not authorized", models.WithCriticalSeverity(), commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest), )As per coding guidelines, "In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them."
Also applies to: 79-86
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/errors.go` around lines 72 - 77, The validation error ErrPaymentAlreadySettled currently uses the message "payment already settled" which is too specific for cases where the payment is in other terminal/invalid states (e.g., "not authorized"); update the human-facing message to a state-agnostic phrase (for example "payment cannot be processed in its current state" or similar) in ErrPaymentAlreadySettled and the adjacent related errors (lines around the other error declarations at 79-86) so callers like the functions in payment.go and external.go get a clearer, generic description while keeping the same error code and attributes (models.NewValidationIssue, ErrCodePaymentAlreadySettled, models.WithCriticalSeverity(), commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest)).openmeter/billing/charges/service/service_test.go (1)
596-710: Please extend the manual-settlement test with persisted-state + invalid-transition checks.This path currently verifies happy-path responses from update calls, but not post-update DB reloads or failure transitions (for example, settle-before-authorize / duplicate settle). Adding those would harden regression coverage for the state machine.
As per coding guidelines, "
**/*_test.go: Make sure the tests are comprehensive and cover the changes."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/service_test.go` around lines 596 - 710, The test TestExternalAuthorizedCreditPurchaseManuallySettled only asserts immediate handler callbacks and response objects; extend it to also reload the persisted charge from storage and assert the DB state after each UpdateExternalCreditPurchasePaymentState call, and add negative tests for invalid transitions (e.g., calling UpdateExternalCreditPurchasePaymentState to Settled before Authorized and duplicate Settled calls) to ensure proper errors/status unchanged; locate the test in ChargesServiceTestSuite and use the existing helpers (CreateTestCustomer, Charges.CreateCharges, Charges.UpdateExternalCreditPurchasePaymentState, and the CreditPurchaseTestHandler callbacks) to perform the post-update reloads and the failing-transition calls and assert the returned error types/status and that the persisted charge state did not change.openmeter/billing/charges/service/create.go (1)
163-175: Avoid repeated full-list scans when grouping pending invoice lines.This does a full
gatheringLinesToCreatefilter for each unique customer/currency key. In larger create batches, that becomes quadratic and can hurt this DB-heavy path.As per coding guidelines, "Performance should be a priority in critical code paths ... database operations ... should be vetted for potential performance bottlenecks."♻️ Suggested one-pass grouping
- uniqueCurrencyAndCustomerIDs := lo.Uniq( - lo.Map(gatheringLinesToCreate, func(item gatheringLineWithCustomerID, _ int) currencyAndCustomerID { - return currencyAndCustomerID{ - Currency: item.gatheringLine.Currency, - CustomerID: item.customerID, - } - }), - ) - - for _, custAndCurrency := range uniqueCurrencyAndCustomerIDs { - gatheringLinesForCurrencyAndCustomer := lo.FilterMap(gatheringLinesToCreate, func(item gatheringLineWithCustomerID, _ int) (billing.GatheringLine, bool) { - return item.gatheringLine, item.customerID == custAndCurrency.CustomerID && item.gatheringLine.Currency == custAndCurrency.Currency - }) + grouped := make(map[currencyAndCustomerID][]billing.GatheringLine, len(gatheringLinesToCreate)) + for _, item := range gatheringLinesToCreate { + key := currencyAndCustomerID{ + Currency: item.gatheringLine.Currency, + CustomerID: item.customerID, + } + grouped[key] = append(grouped[key], item.gatheringLine) + } + + for custAndCurrency, gatheringLinesForCurrencyAndCustomer := range grouped { if len(gatheringLinesForCurrencyAndCustomer) == 0 { continue }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/create.go` around lines 163 - 175, The current loop constructs uniqueCurrencyAndCustomerIDs and then, for each key, re-scans gatheringLinesToCreate with lo.FilterMap (creating gatheringLinesForCurrencyAndCustomer), causing O(n^2) behavior; instead perform a single-pass grouping: iterate once over gatheringLinesToCreate (items of type gatheringLineWithCustomerID) and build a map keyed by a stable composite key (e.g., currency + ":" + customerID or a struct like currencyAndCustomerID) mapping to []billing.GatheringLine, then produce the list of unique keys from that map and iterate the map entries to replace the existing uniqueCurrencyAndCustomerIDs / inner FilterMap logic; update references to currencyAndCustomerID, gatheringLinesForCurrencyAndCustomer, and gatheringLineWithCustomerID accordingly so downstream code consumes the grouped slices.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/payment.go`:
- Around line 36-39: The error message in PaymentSettlementStatus.Validate is
too specific ("invalid standard invoice payment settlement status"); update the
fmt.Errorf call in the PaymentSettlementStatus.Validate method to use a generic
message like "invalid payment settlement status" (or similar) and include the
invalid value (o) so the validator remains correct but no longer references
"standard invoice". Ensure you update the string in the return statement inside
the Validate() method of PaymentSettlementStatus.
In
`@tools/migrate/migrations/20260304081726_billing-charges-credit-purchase.up.sql`:
- Around line 23-24: The migration creates an unconditional unique index
charge_external_payment_settlements_charge_id_key on charge_id which prevents
reinserting a settlement for the same charge after a soft-delete; update the
migration to either remove the unique constraint or make the index conditional
to only apply to non-deleted rows (add WHERE deleted_at IS NULL) to match the
project’s soft-delete pattern, and if this was generated from ent's
edge.To(...).Unique() in charges.go (around the edge definition), remove the
edge.Unique() there instead so future migrations don't reintroduce the
unconditional unique index.
---
Duplicate comments:
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 440-444: The inline flow comment references the wrong handler
name: replace mentions of OnCreditPurchase with the actual interface method name
OnCreditPurchaseInitiated and ensure the sequence lists the correct handlers
(OnCreditPurchaseInitiated -> OnCreditPurchasePaymentAuthorized ->
OnCreditPurchasePaymentSettled); update the comment block around the flow (the
lines documenting the "Happy path") to use those exact identifiers so it matches
the implemented handler names.
- Around line 276-279: The unmarshal error message is using the stale type name
"ExternalAuthorizedCreditPurchaseSettlement" while the code creates v :=
&ExternalCreditPurchaseSettlement{}; update the fmt.Errorf call wrapped around
json.Unmarshal(bytes, v) to reference the correct type name
"ExternalCreditPurchaseSettlement" so the error text matches the actual struct
(look for the json.Unmarshal call that populates
ExternalCreditPurchaseSettlement and change the string passed to fmt.Errorf).
---
Nitpick comments:
In `@openmeter/billing/charges/errors.go`:
- Around line 72-77: The validation error ErrPaymentAlreadySettled currently
uses the message "payment already settled" which is too specific for cases where
the payment is in other terminal/invalid states (e.g., "not authorized"); update
the human-facing message to a state-agnostic phrase (for example "payment cannot
be processed in its current state" or similar) in ErrPaymentAlreadySettled and
the adjacent related errors (lines around the other error declarations at 79-86)
so callers like the functions in payment.go and external.go get a clearer,
generic description while keeping the same error code and attributes
(models.NewValidationIssue, ErrCodePaymentAlreadySettled,
models.WithCriticalSeverity(),
commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest)).
In `@openmeter/billing/charges/service/create.go`:
- Around line 163-175: The current loop constructs uniqueCurrencyAndCustomerIDs
and then, for each key, re-scans gatheringLinesToCreate with lo.FilterMap
(creating gatheringLinesForCurrencyAndCustomer), causing O(n^2) behavior;
instead perform a single-pass grouping: iterate once over gatheringLinesToCreate
(items of type gatheringLineWithCustomerID) and build a map keyed by a stable
composite key (e.g., currency + ":" + customerID or a struct like
currencyAndCustomerID) mapping to []billing.GatheringLine, then produce the list
of unique keys from that map and iterate the map entries to replace the existing
uniqueCurrencyAndCustomerIDs / inner FilterMap logic; update references to
currencyAndCustomerID, gatheringLinesForCurrencyAndCustomer, and
gatheringLineWithCustomerID accordingly so downstream code consumes the grouped
slices.
In `@openmeter/billing/charges/service/service_test.go`:
- Around line 596-710: The test
TestExternalAuthorizedCreditPurchaseManuallySettled only asserts immediate
handler callbacks and response objects; extend it to also reload the persisted
charge from storage and assert the DB state after each
UpdateExternalCreditPurchasePaymentState call, and add negative tests for
invalid transitions (e.g., calling UpdateExternalCreditPurchasePaymentState to
Settled before Authorized and duplicate Settled calls) to ensure proper
errors/status unchanged; locate the test in ChargesServiceTestSuite and use the
existing helpers (CreateTestCustomer, Charges.CreateCharges,
Charges.UpdateExternalCreditPurchasePaymentState, and the
CreditPurchaseTestHandler callbacks) to perform the post-update reloads and the
failing-transition calls and assert the returned error types/status and that the
persisted charge state did not change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: dcb51b35-3936-491b-b3dc-c4540bdc56ad
⛔ Files ignored due to path filters (31)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_delete.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/ent.gois excluded by!**/ent/db/**openmeter/ent/db/expose.gois excluded by!**/ent/db/**openmeter/ent/db/hook/hook.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/paginate.gois excluded by!**/ent/db/**openmeter/ent/db/predicate/predicate.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**openmeter/ent/db/tx.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (31)
openmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/charge.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/creditpurchase.goopenmeter/billing/charges/adapter/external.goopenmeter/billing/charges/adapter/faltfee.goopenmeter/billing/charges/adapter/get.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeflatfee.goopenmeter/billing/charges/chargeusagebased.goopenmeter/billing/charges/errors.goopenmeter/billing/charges/payment.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/creditpurchase.goopenmeter/billing/charges/service/creditpurchase/creditpurchase.goopenmeter/billing/charges/service/creditpurchase/external.goopenmeter/billing/charges/service/creditpurchase/promotional.goopenmeter/billing/charges/service/flatfee/flatfee.goopenmeter/billing/charges/service/flatfee/payment.goopenmeter/billing/charges/service/handlers_test.goopenmeter/billing/charges/service/invoice.goopenmeter/billing/charges/service/invoicependinglines.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/service/service_test.goopenmeter/billing/charges/stdinvoice.goopenmeter/ent/schema/charges.gotools/migrate/migrations/20260304081726_billing-charges-credit-purchase.down.sqltools/migrate/migrations/20260304081726_billing-charges-credit-purchase.up.sql
🚧 Files skipped from review as they are similar to previous changes (8)
- tools/migrate/migrations/20260304081726_billing-charges-credit-purchase.down.sql
- openmeter/billing/charges/service/invoicependinglines.go
- openmeter/billing/charges/adapter/charge.go
- openmeter/billing/charges/adapter/creditpurchase.go
- openmeter/billing/charges/service/flatfee/flatfee.go
- openmeter/billing/charges/service/service.go
- openmeter/billing/charges/service/creditpurchase/promotional.go
- openmeter/billing/charges/chargeusagebased.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/charges/service/service_test.go (1)
623-655: Minor typo in variable names.There's a small typo:
initatedCallbackandinitatedTrnsIDshould beinitiatedCallbackandinitiatedTrnsID(missing 'i').✏️ Suggested fix
- var initatedTrnsID string + var initiatedTrnsID string s.Run("initiated", func() { defer s.CreditPurchaseTestHandler.Reset() // First the initiated callback should be called, without any grant realizations or payment settlements - initatedCallback := newCountedLedgerTransactionCallback[charges.CreditPurchaseCharge]() - s.CreditPurchaseTestHandler.onCreditPurchaseInitiated = initatedCallback.Handler(s.T(), func(t *testing.T, charge charges.CreditPurchaseCharge) { + initiatedCallback := newCountedLedgerTransactionCallback[charges.CreditPurchaseCharge]() + s.CreditPurchaseTestHandler.onCreditPurchaseInitiated = initiatedCallback.Handler(s.T(), func(t *testing.T, charge charges.CreditPurchaseCharge) { assert.Equal(t, charge.Intent.Settlement.Type(), charges.CreditPurchaseSettlementTypeExternal) assert.Nil(t, charge.State.CreditGrantRealization, "credit grant realization should not be set") assert.Nil(t, charge.State.ExternalPaymentSettlement, "external payment settlement should not be set") @@ ... creditPurchaseCharge, err := res[0].AsCreditPurchaseCharge() s.NoError(err) - s.Equal(1, initatedCallback.nrInvocations) - s.Equal(initatedCallback.id, creditPurchaseCharge.State.CreditGrantRealization.LedgerTransactionGroupReference.TransactionGroupID) + s.Equal(1, initiatedCallback.nrInvocations) + s.Equal(initiatedCallback.id, creditPurchaseCharge.State.CreditGrantRealization.LedgerTransactionGroupReference.TransactionGroupID) s.Equal(charges.ChargeStatusActive, creditPurchaseCharge.Status) chargeID = creditPurchaseCharge.GetChargeID() - initatedTrnsID = initatedCallback.id + initiatedTrnsID = initiatedCallback.id })Note: The same typo appears on lines 666 (
initatedTrnsID).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/service_test.go` around lines 623 - 655, Rename the misspelled variables `initatedCallback` and `initatedTrnsID` to `initiatedCallback` and `initiatedTrnsID` throughout the test block (and any other occurrences in the file), and update any references that use those names (e.g., the handler assignment, assertions, and the assignment to `initiatedTrnsID`). Ensure the new names are used consistently where `initatedCallback` was declared and where `initatedTrnsID` was set/used so the test compiles and reads correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/billing/charges/service/service_test.go`:
- Around line 623-655: Rename the misspelled variables `initatedCallback` and
`initatedTrnsID` to `initiatedCallback` and `initiatedTrnsID` throughout the
test block (and any other occurrences in the file), and update any references
that use those names (e.g., the handler assignment, assertions, and the
assignment to `initiatedTrnsID`). Ensure the new names are used consistently
where `initatedCallback` was declared and where `initatedTrnsID` was set/used so
the test compiles and reads correctly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d5114748-5204-4bca-9c0c-7b2eeae717e7
📒 Files selected for processing (4)
openmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/service/service_test.go
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
openmeter/ent/schema/charges.go (1)
315-316:⚠️ Potential issue | 🟠 MajorMake external settlement uniqueness soft-delete aware.
Right now the one-to-one edge on
charge_idcreates a hard unique constraint, which prevents inserting a replacement row after soft-delete. Since this entity hasdeleted_at, this will bite on re-creation flows.A cleaner pattern here is: enforce active-row uniqueness with a partial unique index (
WHERE deleted_at IS NULL) and avoid edge-level hard uniqueness that generates unconditional uniqueness.Possible schema adjustment
func (ChargeCreditPurchase) Edges() []ent.Edge { return []ent.Edge{ edge.From("charge", Charge.Type). Ref("credit_purchase"). Unique(). Required(), edge.To("charge_external_payment_settlement", ChargeExternalPaymentSettlement.Type). - Unique(), + // Active-row uniqueness is enforced by a partial unique index. } } func (ChargeExternalPaymentSettlement) Indexes() []ent.Index { return []ent.Index{ - index.Fields("namespace", "charge_id"), - index.Fields("charge_id"), + index.Fields("namespace", "charge_id"). + Unique(). + Annotations(entsql.IndexWhere("deleted_at IS NULL")), + index.Fields("charge_id"). + Annotations(entsql.IndexWhere("deleted_at IS NULL")), } } func (ChargeExternalPaymentSettlement) Edges() []ent.Edge { return []ent.Edge{ edge.From("charge_credit_purchase", ChargeCreditPurchase.Type). Ref("charge_external_payment_settlement"). Field("charge_id"). - Unique(). Required(). Immutable(), } }Also applies to: 596-600, 603-610
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ent/schema/charges.go` around lines 315 - 316, The one-to-one edge declaration that uses edge.To("charge_external_payment_settlement", ChargeExternalPaymentSettlement.Type).Unique() creates an unconditional DB uniqueness that prevents re-creating a soft-deleted ChargeExternalPaymentSettlement; remove the edge-level Unique() on that edge (and any similar Unique() usages around the other occurrences noted) so the ORM does not emit a hard unique constraint, and instead add a partial unique index at the DB schema level for the charge_id column constrained WHERE deleted_at IS NULL to enforce uniqueness only among active rows (create the index in the migration for the ChargeExternalPaymentSettlement table).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/payment.go`:
- Around line 85-98: The validator currently allows contradictory states and
temporal inconsistencies; tighten checks in the validation around r.Status
(PaymentSettlementStatusAuthorized, PaymentSettlementStatusSettled) so: when
r.Status == PaymentSettlementStatusAuthorized ensure r.Authorized is non-nil AND
r.Settled is nil (reject if Settled is present), and when r.Status ==
PaymentSettlementStatusSettled ensure both r.Settled and r.Authorized are
non-nil and that r.Settled.Timestamp (or equivalent settlement time field) is
not before r.Authorized.Timestamp (reject if Settled time < Authorized time);
update the error messages to reference the specific invariant violated (e.g.,
"settled data present for authorized status", "authorized/settled missing for
settled status", "settlement time before authorization time") and perform these
checks in the same validation function that inspects r.Status, r.Authorized and
r.Settled.
In
`@tools/migrate/migrations/20260304115231_billing-charges-credit-purchase.up.sql`:
- Line 2: This migration is destructive because it drops the status column
immediately and also contains redundant/unsafe unique indexes; instead, remove
the DROP COLUMN "status" so this file only ADDs
"credit_grant_transaction_group_id" and "credit_granted_at" (keep them
nullable), and create a follow-up migration that backfills the new columns from
"status" and switches readers/writers before dropping "status"; also remove the
redundant unique index on "id" (since PRIMARY KEY("id") exists) and revisit the
unique index on "charge_id" to account for soft-deletes (deleted_at) — either
make it a partial unique index that excludes soft-deleted rows or drop/alter it
in a controlled migration.
---
Duplicate comments:
In `@openmeter/ent/schema/charges.go`:
- Around line 315-316: The one-to-one edge declaration that uses
edge.To("charge_external_payment_settlement",
ChargeExternalPaymentSettlement.Type).Unique() creates an unconditional DB
uniqueness that prevents re-creating a soft-deleted
ChargeExternalPaymentSettlement; remove the edge-level Unique() on that edge
(and any similar Unique() usages around the other occurrences noted) so the ORM
does not emit a hard unique constraint, and instead add a partial unique index
at the DB schema level for the charge_id column constrained WHERE deleted_at IS
NULL to enforce uniqueness only among active rows (create the index in the
migration for the ChargeExternalPaymentSettlement table).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4bd1258c-a865-4653-8d5b-8713ca41b497
⛔ Files ignored due to path filters (2)
openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (4)
openmeter/billing/charges/payment.goopenmeter/ent/schema/charges.gotools/migrate/migrations/20260304115231_billing-charges-credit-purchase.down.sqltools/migrate/migrations/20260304115231_billing-charges-credit-purchase.up.sql
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
openmeter/billing/charges/payment.go (1)
83-96:⚠️ Potential issue | 🟠 MajorTighten status invariants in base validation.
Right now, invalid combinations still pass:
status=authorizedwithSettledpresentstatus=settledwhereSettled.Timeis beforeAuthorized.TimeSince this validator gates persistence, these should be blocked here.
Suggested patch
switch r.Status { case PaymentSettlementStatusAuthorized: if r.Authorized == nil { errs = append(errs, fmt.Errorf("authorization transaction data is missing for authorized status")) } + if r.Settled != nil { + errs = append(errs, fmt.Errorf("settlement transaction data must be empty for authorized status")) + } case PaymentSettlementStatusSettled: if r.Settled == nil { errs = append(errs, fmt.Errorf("settlement transaction data is missing for settled status")) } if r.Authorized == nil { errs = append(errs, fmt.Errorf("authorization transaction data is missing for settled status")) } + if r.Authorized != nil && r.Settled != nil && r.Settled.Time.Before(r.Authorized.Time) { + errs = append(errs, fmt.Errorf("settlement time cannot be before authorization time")) + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/payment.go` around lines 83 - 96, The current validator only checks for presence of Authorized/Settled based on r.Status but allows invalid combos; update the validation (the switch over r.Status, e.g., in the payment settlement Validate function) to also: (1) when r.Status == PaymentSettlementStatusAuthorized, error if r.Settled != nil (disallow a settlement record when status is "authorized"); (2) when r.Status == PaymentSettlementStatusSettled, require r.Authorized != nil and r.Settled != nil and additionally validate that r.Settled.Time is not before r.Authorized.Time (error if Settled.Time < Authorized.Time) so invalid temporal combinations are rejected before persistence. Ensure error messages reference the offending fields (r.Authorized / r.Settled) and statuses (PaymentSettlementStatusAuthorized / PaymentSettlementStatusSettled).
🧹 Nitpick comments (2)
openmeter/billing/charges/service/flatfee/payment.go (1)
39-47: Consider atomicity of payment creation and charge updateThere's a subtle consistency risk here: if
CreateStandardInvoicePaymentSettlementsucceeds butUpdateFlatFeeChargefails, you'll have an orphaned payment settlement record that isn't reflected in the charge state. Same pattern appears inPostPaymentSettledbelow.Might be worth either:
- Wrapping both operations in a transaction
- Adding rollback/compensation logic if the second call fails
- Documenting this as an acceptable eventual-consistency tradeoff if the system handles it elsewhere
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/service/flatfee/payment.go` around lines 39 - 47, The current flow creates a payment via s.adapter.CreateStandardInvoicePaymentSettlement and then updates the charge via s.adapter.UpdateFlatFeeCharge which can leave a paymentSettlement orphan if the second call fails; update the implementation to ensure atomicity by either (a) performing both operations inside a single transactional boundary provided by the adapter (add a new adapter method like PerformCreatePaymentAndUpdateChargeTransaction or use an existing transaction API so CreateStandardInvoicePaymentSettlement and UpdateFlatFeeCharge are committed together), or (b) adding rollback/compensation logic in the same function (on UpdateFlatFeeCharge failure call a compensation method such as s.adapter.DeletePaymentSettlement or CancelPaymentSettlement using the paymentSettlement identifier), and apply the same change pattern to PostPaymentSettled to avoid inconsistent state; reference the methods CreateStandardInvoicePaymentSettlement, UpdateFlatFeeCharge, PostPaymentSettled and the s.adapter surface when making the change.openmeter/billing/charges/adapter/mapper.go (1)
311-323: Consider extracting shared settlement-base mapping helper.Both standard-invoice and external settlement mappers build the same
PaymentSettlementBaseshape. A tiny helper would reduce duplication and future drift.As per coding guidelines,
In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them.Also applies to: 378-401
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/mapper.go` around lines 311 - 323, The two mappers duplicate construction of the PaymentSettlementBase struct (see PaymentSettlementBase, mapTimedLedgerTransactionGroupReferenceFromDB, ServicePeriod/Annotations/Status/Amount/Authorized/Settled) — extract a small helper function (e.g., buildPaymentSettlementBaseFromEntity or mapPaymentSettlementBase) that accepts the entity (or the required fields: Annotations, ServicePeriodFrom/To, Status, Amount, AuthorizedTransactionGroupID/AuthorizedAt, SettledTransactionGroupID/SettledAt) and returns the populated PaymentSettlementBase; replace the inlined constructions in both the standard-invoice and external settlement mapping sites with calls to that helper to remove duplication and keep behavior identical.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@tools/migrate/migrations/20260304130221_billing-charges-credit-purchase.down.sql`:
- Around line 3-4: The down migration adds a NOT NULL column "status" to table
"charge_credit_purchases" which will fail if rows exist; update the ALTER TABLE
in the migration (20260304130221_billing-charges-credit-purchase.down.sql) to
either add "status" with a safe DEFAULT (e.g., DEFAULT 'pending') so existing
rows get a value, or add it as nullable and then backfill existing rows and
ALTER COLUMN to NOT NULL in a separate step; reference the ALTER TABLE that
currently does ADD COLUMN "status" character varying NOT NULL and adjust
accordingly.
In
`@tools/migrate/migrations/20260304132121_billing-charges-fix-std-payments-edge.down.sql`:
- Around line 7-8: The down migration currently adds charge_id as NOT NULL which
will fail on existing rows and also omits recreating the indexes; change the
migration to add "charge_id" on table
"charge_standard_invoice_payment_settlements" in a data-safe way (e.g., add as
NULLable or with a sensible DEFAULT, backfill existing rows appropriately, then
alter to NOT NULL if required) and recreate the two indexes removed earlier by
adding back "charge_standard_invoice_payment_settlements_charge_id_key" (unique
on "charge_id") and
"chargestandardinvoicepaymentsettlement_namespace_charge_id_line" (unique on
"namespace","charge_id","line_id" with the WHERE clause ((line_id IS NOT NULL)
AND (deleted_at IS NULL))). Ensure the backfill and NULLability steps prevent
failures on existing data before enforcing NOT NULL.
In
`@tools/migrate/migrations/20260304132121_billing-charges-fix-std-payments-edge.up.sql`:
- Around line 1-2: Before dropping the column "charge_id" from the
"charge_standard_invoice_payment_settlements" table, first DROP the two
dependent indexes named
charge_standard_invoice_payment_settlements_charge_id_key and
chargestandardinvoicepaymentsettlement_namespace_charge_id_line; then run ALTER
TABLE "charge_standard_invoice_payment_settlements" DROP COLUMN "charge_id".
Ensure the DROP INDEX statements reference those exact index names and are
placed immediately before the ALTER TABLE ... DROP COLUMN "charge_id" statement.
---
Duplicate comments:
In `@openmeter/billing/charges/payment.go`:
- Around line 83-96: The current validator only checks for presence of
Authorized/Settled based on r.Status but allows invalid combos; update the
validation (the switch over r.Status, e.g., in the payment settlement Validate
function) to also: (1) when r.Status == PaymentSettlementStatusAuthorized, error
if r.Settled != nil (disallow a settlement record when status is "authorized");
(2) when r.Status == PaymentSettlementStatusSettled, require r.Authorized != nil
and r.Settled != nil and additionally validate that r.Settled.Time is not before
r.Authorized.Time (error if Settled.Time < Authorized.Time) so invalid temporal
combinations are rejected before persistence. Ensure error messages reference
the offending fields (r.Authorized / r.Settled) and statuses
(PaymentSettlementStatusAuthorized / PaymentSettlementStatusSettled).
---
Nitpick comments:
In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 311-323: The two mappers duplicate construction of the
PaymentSettlementBase struct (see PaymentSettlementBase,
mapTimedLedgerTransactionGroupReferenceFromDB,
ServicePeriod/Annotations/Status/Amount/Authorized/Settled) — extract a small
helper function (e.g., buildPaymentSettlementBaseFromEntity or
mapPaymentSettlementBase) that accepts the entity (or the required fields:
Annotations, ServicePeriodFrom/To, Status, Amount,
AuthorizedTransactionGroupID/AuthorizedAt, SettledTransactionGroupID/SettledAt)
and returns the populated PaymentSettlementBase; replace the inlined
constructions in both the standard-invoice and external settlement mapping sites
with calls to that helper to remove duplication and keep behavior identical.
In `@openmeter/billing/charges/service/flatfee/payment.go`:
- Around line 39-47: The current flow creates a payment via
s.adapter.CreateStandardInvoicePaymentSettlement and then updates the charge via
s.adapter.UpdateFlatFeeCharge which can leave a paymentSettlement orphan if the
second call fails; update the implementation to ensure atomicity by either (a)
performing both operations inside a single transactional boundary provided by
the adapter (add a new adapter method like
PerformCreatePaymentAndUpdateChargeTransaction or use an existing transaction
API so CreateStandardInvoicePaymentSettlement and UpdateFlatFeeCharge are
committed together), or (b) adding rollback/compensation logic in the same
function (on UpdateFlatFeeCharge failure call a compensation method such as
s.adapter.DeletePaymentSettlement or CancelPaymentSettlement using the
paymentSettlement identifier), and apply the same change pattern to
PostPaymentSettled to avoid inconsistent state; reference the methods
CreateStandardInvoicePaymentSettlement, UpdateFlatFeeCharge, PostPaymentSettled
and the s.adapter surface when making the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: df62fda0-82c5-4f79-ab42-332f1b61b60d
⛔ Files ignored due to path filters (30)
openmeter/ent/db/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/chargecreditpurchase.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargecreditpurchase_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/chargeexternalpaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeexternalpaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee/chargeflatfee.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeflatfee_update.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/chargestandardinvoicepaymentsettlement.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargestandardinvoicepaymentsettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/runtime.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (15)
openmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/creditpurchase.goopenmeter/billing/charges/adapter/external.goopenmeter/billing/charges/adapter/faltfee.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/adapter/stdinvoice.goopenmeter/billing/charges/payment.goopenmeter/billing/charges/service/creditpurchase/external.goopenmeter/billing/charges/service/flatfee/payment.goopenmeter/billing/charges/stdinvoice.goopenmeter/ent/schema/charges.gotools/migrate/migrations/20260304130221_billing-charges-credit-purchase.down.sqltools/migrate/migrations/20260304130221_billing-charges-credit-purchase.up.sqltools/migrate/migrations/20260304132121_billing-charges-fix-std-payments-edge.down.sqltools/migrate/migrations/20260304132121_billing-charges-fix-std-payments-edge.up.sql
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/billing/charges/adapter/creditpurchase.go
- openmeter/billing/charges/adapter.go
|
closing as merged on reference |
Pull request was closed
Overview
This patch implements the promotional an externally settled charge types.
Notes for reviewer
Summary by CodeRabbit
Release Notes
New Features
Refactor