Repository navigation
feat: charges v2 - #3894
feat: charges v2#3894
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:
📝 WalkthroughWalkthroughAdds a full billing charges domain: polymorphic charge models (flat‑fee, usage‑based, credit purchase), validation and errors, service and adapter interfaces plus an ent-backed adapter implementation with transactional Create/Get flows, DB↔domain mappers, and adapter tests. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Service
participant Adapter
participant Database
rect rgba(100, 200, 255, 0.5)
Note over Client,Database: CreateCharges flow
Client->>Service: CreateCharges(ctx, CreateChargeInputs)
Service->>Service: Validate input
Service->>Adapter: Tx(ctx) — begin transaction
Adapter->>Database: Begin transaction
Database-->>Adapter: tx driver
Service->>Adapter: CreateCharges(tx ctx, intents)
Adapter->>Database: Bulk create Charge rows
Adapter->>Database: Bulk create FlatFee / UsageBased / CreditPurchase edges
Adapter->>Database: Link sub-entities to parent charges
Database-->>Adapter: Created entities
Adapter->>Adapter: Map DB entities → domain charges
Adapter-->>Service: Return charges
Service->>Adapter: Commit / finish tx
Database-->>Service: Transaction committed
Service-->>Client: Result charges
end
rect rgba(100, 255, 200, 0.5)
Note over Client,Database: GetCharges flow
Client->>Service: GetChargesByIDs(ctx, namespace, ids)
Service->>Service: Validate namespace/ids
Service->>Adapter: Tx(ctx)
Adapter->>Database: Begin transaction
Database-->>Adapter: tx driver
Service->>Adapter: GetChargesByIDs(tx ctx, namespace, ids)
Adapter->>Database: Query charges with preloaded edges
Database-->>Adapter: Charge entities + edges
Adapter->>Adapter: Map each DB entity → domain charge
Adapter-->>Service: Return charges
Service->>Adapter: Commit / finish tx
Database-->>Service: Transaction committed
Service-->>Client: Result charges
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 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 |
0ac2cdd to
e23c4b4
Compare
e23c4b4 to
6162290
Compare
There was a problem hiding this comment.
Actionable comments posted: 9
🧹 Nitpick comments (15)
openmeter/billing/charges/adapter/adapter_test.go (2)
44-177: Good happy-path coverage — consider adding edge-case andGetChargeByIDtests.The round-trip create-then-get tests for all three charge types are solid. A few gaps to consider for future coverage:
GetChargeByID(from theChargeServiceinterface) isn't exercised here — onlyGetChargesByIDsis tested.- No negative test cases: e.g., retrieving a non-existent ID, creating invalid charges, passing an empty namespace.
- No test for creating multiple charges in a single
CreateChargescall to verify batch behavior.Totally fine to defer these if you're planning to add them in a follow-up PR alongside the "real" logic.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 44 - 177, Tests only cover happy-path CreateCharges -> GetChargesByIDs round-trips; add focused tests on ChargeService.GetChargeByID, negative scenarios, and batch creation: add a new test method(s) on ChargesAdapterTestSuite that calls s.adapter.GetChargeByID (or the ChargeService implementation) to fetch a single created charge by ID, assert equality with the created charge, add tests that request a non-existent ID and assert the expected not-found error/empty result, add tests that call CreateCharges with multiple valid Charge inputs to verify batch behavior and with invalid inputs/empty namespace to assert proper validation/error handling; use existing helpers like newManagedResource, newIntentMeta, CreateTestCustomer and methods CreateCharges/GetChargesByIDs/GetChargeByID to locate code under test.
187-204:newIntentMetahelper doesn't setMetadataorAnnotations— might want to test those fields round-trip too.Currently all optional fields (
TaxConfig,UniqueReferenceID,Subscription,Metadata,Annotations) are left at zero values. Worth having at least one test that populates these to verify they survive the DB round-trip, especially since the mapper layer needs to handle them.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 187 - 204, Update the test helper newIntentMeta in adapter_test.go to populate optional fields (at minimum Metadata and Annotations) on the charges.IntentMeta it returns so the DB round-trip is exercised; set Metadata to a non-empty map (e.g., string keys/values) and Annotations to a non-empty slice (and optionally fill TaxConfig, UniqueReferenceID, Subscription if relevant) and then add/adjust assertions in the test that uses newIntentMeta to verify those fields survive the mapper/DB round-trip. Ensure you reference the charges.IntentMeta fields (Metadata, Annotations, and any additional optional fields you populate) and update the related test expectations accordingly.openmeter/billing/charges/chargecreditpurchase.go (2)
57-65:CreditPurchaseIntenthas its ownCurrencyfield, butIntentMeta(which it embeds) also has aCurrencyfield.This shadows the embedded
IntentMeta.Currency. The intent'sValidate()on Line 74 validatesi.Currencywhich resolves to the outer (CreditPurchaseIntent) field, whilei.IntentMeta.Validate()validates the embedded one independently. If they're meant to represent different things (e.g., credit currency vs. billing currency), a more descriptive name for one of them would help avoid confusion. If they should always match, consider removing the duplicate and relying on the embedded field.🤖 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 57 - 65, CreditPurchaseIntent defines a Currency field that shadows the embedded IntentMeta.Currency causing inconsistent validation between CreditPurchaseIntent.Validate (which checks i.Currency) and i.IntentMeta.Validate (which checks the embedded one); fix by either removing the duplicate Currency from CreditPurchaseIntent and using the embedded IntentMeta.Currency everywhere (update JSON tags/consumers to use the embedded field) or, if they represent different currencies, rename the outer field to a descriptive name like CreditCurrency (and JSON tag "credit_currency"), update all references and the Validate() on CreditPurchaseIntent to explicitly validate both fields and assert they match when required; change references to i.Currency in CreditPurchaseIntent.Validate to the new name or to i.IntentMeta.Currency as appropriate.
15-51: Receiver inconsistency:AsCharge()uses pointer receiver whileValidate(),Type(), and getters use value receivers.
AsCharge()at Line 42 takes*CreditPurchaseCharge(pointer) while everything else usesCreditPurchaseCharge(value). This is fine functionally sinceAsChargestores the pointer in theChargestruct, but worth being aware of — callers with a value-typeCreditPurchaseChargewon't seeAsChargein the method set of the interface if it requires pointer receivers.🤖 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 15 - 51, The receiver for AsCharge is a pointer (*CreditPurchaseCharge) while Validate, Type, and other methods use value receivers, which breaks method-set consistency; change AsCharge to use a value receiver (func (c CreditPurchaseCharge) AsCharge() Charge) and ensure the Charge returned still stores a pointer by assigning creditPurchase: &c so callers with a value-type CreditPurchaseCharge can call AsCharge and other methods remain unchanged (references: CreditPurchaseCharge.Validate, CreditPurchaseCharge.Type, CreditPurchaseCharge.AsCharge, Charge.creditPurchase).openmeter/billing/charges/stdinvoice.go (1)
57-65: Validate() only checks Status — consider validating other required fields.Fields like
LineIDandServicePeriodaren't validated here. Totally fine if this is intentional placeholder validation that'll be expanded later, just flagging it in case it was an oversight.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/stdinvoice.go` around lines 57 - 65, The Validate method on StandardInvoiceSettlement currently only validates Status; extend it to validate other required fields (e.g., LineID and ServicePeriod) by checking for zero/empty values and appending wrapped errors to the errs slice (similar to the Status check) before returning errors.Join(errs...). Locate StandardInvoiceSettlement.Validate and add checks like "if r.LineID == "" { errs = append(errs, fmt.Errorf("lineID: required")) }" and validate ServicePeriod (nil or empty start/end) with descriptive wrapped errors so all missing/invalid fields are reported.openmeter/billing/charges/chargeflatfee.go (1)
112-118: Nit:FlatFeeState.Validate()is a no-op with unnecessary ceremony.The
var errs []erroranderrors.Join(errs...)dance does nothing here. A simplereturn nilwould be cleaner until there's actual validation to add. Totally fine to leave as-is if you prefer the consistency with otherValidate()methods though!Simpler no-op
func (s FlatFeeState) Validate() error { - var errs []error - - return errors.Join(errs...) + return nil }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargeflatfee.go` around lines 112 - 118, FlatFeeState.Validate() is currently a no-op that creates an empty slice and calls errors.Join unnecessarily; simplify by removing the unused errs slice and replacing the body of FlatFeeState.Validate with a single `return nil` so the method clearly communicates there's no validation for now (update the FlatFeeState.Validate method).openmeter/billing/charges/adapter.go (1)
23-34: Inconsistent naming between type and constant prefix.The type is
ProRatingModeAdapterEnum(Mode before Adapter) but the constants useProRatingAdapterModeEnum...(Adapter before Mode). This is easy to mix up and could lead to typos down the line. Picking one ordering and sticking with it would help readability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter.go` around lines 23 - 34, The constant names are inconsistent with the type name: change the constants from ProRatingAdapterModeEnumProratePrices and ProRatingAdapterModeEnumNoProrate to match the type prefix (e.g., ProRatingModeAdapterEnumProratePrices and ProRatingModeAdapterEnumNoProrate), update the Values() implementation to return the renamed constants, and search/replace any other usages of the old constant names to the new ones (ensure the first constant still wraps productcatalog.ProRatingModeProratePrices and the second remains "no_prorate").openmeter/billing/charges/adapter/create.go (1)
45-47: Use ID-based lookup for parent charges, like you do for sub-entities.Lines 45–47 pair
createdEntities[idx]withinput[idx]using positional indexing. While Ent'sCreateBulk.Save()typically preserves insertion order, the rest of your function already handles this more defensively — you uselo.SliceToMap()to create ID-keyed lookups for flat fees, usage-based, and credit purchase entities (lines 93–95, 142–144, 194–196). For consistency and robustness, apply the same pattern to parent charges instead of relying on positional ordering.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/create.go` around lines 45 - 47, The current pairing uses positional indexing between createdEntities and input to build chargeWithOriginal (variables: createdEntities, input, chargeWithOriginal), which can be brittle; instead build an ID-keyed map from createdEntities (key by entity.ID) and then iterate the input slice to look up each original's matching created entity by ID when constructing the pairs so you mirror the lo.SliceToMap pattern used for flat fees/usage/credits and avoid relying on insertion order.openmeter/billing/charges/adapter/mapper.go (2)
322-355:mapCreditPurchaseSettlementToDBuses a sequential try-cast pattern — a bit fragile.The function tries
AsInvoice...,AsExternal...,AsPromotional...in order, relying on each returning a non-nil error to fall through. This works, but if a new settlement type is added, it's easy to forget to add a branch here, and the error at line 354 is quite generic.Consider adding a brief comment listing the expected variants, or switching on a discriminator field if one exists on
CreditPurchaseSettlement, to make this more maintainable.🤖 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 322 - 355, The try-cast chain in mapCreditPurchaseSettlementToDB (using AsInvoiceCreditPurchaseSettlement, AsExternalAuthorizedCreditPurchaseSettlement, AsPromotionalCreditPurchaseSettlement) is fragile and missing future variants; update this function to either switch on a concrete discriminator field on charges.CreditPurchaseSettlement if one exists (e.g., settlement.Type() or a Kind/Variant method) and handle each known variant explicitly, or if no discriminator exists, keep the casts but add a clear top-of-function comment listing the expected variants and replace the generic error with one that includes the settlement's identifying info and the handled variants (so failures indicate an unrecognized variant), ensuring you reference mapCreditPurchaseSettlementToDB and the three As* methods when making the change.
357-371: Default pro-rating config setsMode: ProRatingModeProratePriceseven when disabled.In
proRatingConfigFromDB, thedefaultbranch returnsEnabled: falsebut still setsMode: ProRatingModeProratePrices. While this likely doesn't affect behavior (sinceEnabledgates the mode), it's a bit misleading for anyone inspecting the config. Consider leavingModeas the zero value or using a dedicated "none" mode, if one exists.🤖 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 357 - 371, The default branch of proRatingConfigFromDB returns Enabled:false but still sets Mode to ProRatingModeProratePrices, which is misleading; update the function (proRatingConfigFromDB) so that when returning Enabled:false it leaves Mode as the zero value (or uses a dedicated "none" enum like productcatalog.ProRatingModeNone if available) instead of ProRatingModeProratePrices so the disabled config doesn't imply an active mode.openmeter/billing/charges/chageusagebased.go (2)
55-65:TaxConfigfield shadows the embeddedIntentMeta.TaxConfig.
UsageBasedIntentembedsIntentMeta, which already has aTaxConfigfield (seeintent.goline 26). Declaring anotherTaxConfighere shadows it. This meansintent.TaxConfigandintent.IntentMeta.TaxConfigare two different fields, which is a maintenance footgun.If this is intentional (e.g., usage-based charges store TaxConfig at the sub-entity level rather than the base charge), consider removing
TaxConfigfromIntentMetaor documenting the distinction. Otherwise, it's a subtle source of bugs in serialization and mapping.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chageusagebased.go` around lines 55 - 65, UsageBasedIntent declares a TaxConfig field that shadows the embedded IntentMeta.TaxConfig; remove the duplicate TaxConfig from UsageBasedIntent so you only use IntentMeta.TaxConfig (and its JSON tag) when serializing/deserializing, updating any references in code that access UsageBasedIntent.TaxConfig to instead use the embedded IntentMeta (e.g., intent.TaxConfig or intent.IntentMeta.TaxConfig); if the duplicate was intentional, instead rename the field (e.g., UsageTaxConfig) and update JSON tags and all usages to make the distinction explicit.
40-45:AsCharge()uses a pointer receiver while all other methods use value receivers.
AsCharge()on line 40 takes*UsageBasedCharge, butValidate(),Type(), and the getters all use value receivers. This inconsistency means you can't callAsCharge()on a non-addressableUsageBasedChargevalue. If the pointer receiver is intentional (to avoid a copy and store the original pointer inCharge), that's fine — but worth noting that theChargestruct then holds a pointer to the original, so mutations to the original will be reflected. If that's not desired, consider making it a value receiver for consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chageusagebased.go` around lines 40 - 45, AsCharge() uses a pointer receiver while Validate(), Type(), and the getters use value receivers, causing inconsistency and preventing calls on non-addressable values; either change AsCharge to a value receiver or make the design intentional. Update the method signature from func (c *UsageBasedCharge) AsCharge() Charge to func (c UsageBasedCharge) AsCharge() Charge and ensure Charge construction stores a copy (e.g., if Charge.usageBased is a pointer, assign usageBased: &c or change Charge.usageBased to a value type), or alternatively document/keep the pointer receiver but accept that Charge will hold the original pointer; adjust the UsageBasedCharge/Charge types accordingly (referencing AsCharge, Validate, Type, and the Charge.usageBased field) for consistency.openmeter/billing/charges/charge.go (3)
82-102: Unreachablereturn Charge{}at line 101.The type constraint on
Tguarantees the switch is exhaustive, so line 101 is dead code. It's harmless, but apanic("unreachable")would make the intent clearer and catch any future mistakes if the constraint is widened without updating the switch.Proposed tweak
case CreditPurchaseCharge: return Charge{ t: ChargeTypeCreditPurchase, creditPurchase: &v, } } - return Charge{} + panic("unreachable: unsupported charge type in NewCharge") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/charge.go` around lines 82 - 102, The final "return Charge{}" in NewCharge[T FlatFeeCharge | UsageBasedCharge | CreditPurchaseCharge] is unreachable due to the exhaustive type constraint; replace it with an explicit panic to signal impossible control flow. Change the unreachable return to panic("unreachable") (or add a default branch in the type switch that panics) so NewCharge clearly fails fast if the constraint is ever changed without updating the switch, referencing the NewCharge function and the ChargeType* cases (FlatFeeCharge, UsageBasedCharge, CreditPurchaseCharge).
178-190:Charges.Validate()stringifies nested errors, losing the error chain.At line 185,
err.Error()is stored as a string attribute, which means callers can't useerrors.Isorerrors.Ason the inner error. If structured error inspection is needed downstream, consider wrapping the original error instead. If this is just for human-readable validation output, it's fine as-is.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/charge.go` around lines 178 - 190, Charges.Validate currently stringifies nested validation errors by calling err.Error() when creating ErrChargeInvalid via ErrChargeInvalid.WithAttr("error", err.Error()); instead preserve the original error chain so callers can use errors.Is/As by either passing the error value (ErrChargeInvalid.WithAttr("error", err)) if WithAttr supports non-string values, or by wrapping the original error into the returned error (e.g., wrap ErrChargeInvalid with fmt.Errorf("%w: %v", ErrChargeInvalid.WithAttr("index", i), err) or errors.Join(ErrChargeInvalid.WithAttr("index", i), err)) so the attribute "error" no longer loses the error type and callers can inspect the underlying error; update the code in Charges.Validate accordingly.
137-147: Naming inconsistency:AsCreditPurchasevsAsFlatFeeCharge/AsUsageBasedCharge.The other extractor methods include "Charge" in their name (
AsGenericCharge,AsFlatFeeCharge,AsUsageBasedCharge), but this one doesn't. Since there's only one call site, renaming toAsCreditPurchaseChargefor consistency is a low-impact change worth doing.Proposed rename
-func (c Charge) AsCreditPurchase() (CreditPurchaseCharge, error) { +func (c Charge) AsCreditPurchaseCharge() (CreditPurchaseCharge, error) {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/charge.go` around lines 137 - 147, The method name AsCreditPurchase is inconsistent with other extractors; rename the method to AsCreditPurchaseCharge and update its declaration and all call sites (e.g., any place calling Charge.AsCreditPurchase) to use AsCreditPurchaseCharge; keep the implementation and signature (returns CreditPurchaseCharge, error) identical aside from the name so behavior doesn't change, and run tests/compile to ensure no remaining references to AsCreditPurchase remain.
🤖 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 297-320: The PromotionalCreditPurchaseSettlement mapping
drops/overwrites the generic fields (SettlementCurrency, CostBasis, TaxConfig)
causing schema constraint violations and silent data loss; update
mapCreditPurchaseSettlementFromDB to populate
PromotionalCreditPurchaseSettlement with GenericCreditPurchaseSettlement (use
the local variable generic) and update mapCreditPurchaseSettlementToDB to write
those fields back for PromotionalCreditPurchaseSettlement, or alternatively add
explicit validation in both map functions to error if any of those generic
fields are non-empty for promotional settlements (choose one approach and apply
consistently in mapCreditPurchaseSettlementFromDB and
mapCreditPurchaseSettlementToDB).
In `@openmeter/billing/charges/chageusagebased.go`:
- Line 1: Rename the source file from "chageusagebased.go" to
"chargeusagebased.go" to fix the typo; update any references to the filename in
the repo (e.g., CI scripts, build lists, or documentation) and run `go test
./...` to ensure no package import or build constraints break—the package
declaration remains "package charges", so no code edits needed inside the file
unless other files referenced the misspelled filename explicitly.
- Around line 28-31: The State.Validate() error is being wrapped with the wrong
label; update the error wrapping in the block that checks c.State.Validate() so
it uses "state: %w" instead of "status: %w" (the corresponding Status.Validate()
block should remain "status: %w"); locate the c.State.Validate() call and change
the fmt.Errorf wrapping string accordingly so errors clearly indicate whether
state or status validation failed.
- Around line 82-84: The code calls i.Discounts.Validate() without checking for
nil, which can panic because Discounts is a *productcatalog.Discounts pointer;
add a nil guard like the one used for TaxConfig: check if i.Discounts != nil
before calling i.Discounts.Validate(), and if it is nil skip validation (or
handle accordingly) so you only append validation errors when Validate() is
invoked on a non-nil Discounts.
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 127-128: The error text for the negative cost check is misleading:
in the block that calls s.CostBasis.IsNegative() (where errs is appended via
append(errs, fmt.Errorf(...))), update the error string to reflect that zero is
allowed—use "must not be negative" or "must be non‑negative" instead of "must be
positive" so the message matches the IsNegative() check.
- Around line 156-174: The constant InitiatedPaymentSettlementStatus is declared
but not included in PaymentSettlementStatus.Values(), causing Validate() to
reject "initiated"; update the Values() method to include
string(InitiatedPaymentSettlementStatus) (or, if exclusion was intentional, add
a clarifying comment above InitiatedPaymentSettlementStatus and adjust usage
accordingly) so PaymentSettlementStatus.Validate() and Values() are consistent;
see the InitiatedPaymentSettlementStatus const and the
PaymentSettlementStatus.Values() and Validate() methods to make the change.
- Around line 236-263: The switch cases for
CreditPurchaseSettlementTypeInvoice/External/Promotional append an error when
the inner pointers (s.invoice, s.external, s.promotional) are nil but then
immediately call .Validate() on them, which can panic; update each case so
Validate() is only invoked when the pointer is non-nil (e.g., use an else or
else-if branch or return/continue after appending the nil error) — specifically
change the logic around s.invoice.Validate(), s.external.Validate(), and
s.promotional.Validate() so you check nil and only call Validate on a non-nil
receiver, leaving the default case that appends the invalid type error (s.t)
unchanged.
In `@openmeter/billing/charges/README.md`:
- Around line 1-32: Fix the README.md in the "Realizations" and "Usage Based
charges" sections: replace the incorrect table separator row ("+----+...+") with
the standard Markdown separator ("|---|---|---|"), change "payed" to "paid" in
the ExternalSettlement example, change "it's status" to "its status", change
"The customer have used" to "The customer has used", hyphenate "Usage-based",
and change "tried to fulfilled" to "tried to be fulfilled" (locate these edits
around the "Realizations" table, the ExternalSettlement line, the example
sentence starting "The customer have used...", the "Usage Based charges"
heading, and the invoice creation bullet that mentions "tried to fulfilled").
In `@openmeter/billing/charges/stdinvoice.go`:
- Line 54: The TODO comment on the Totals field contains a typo; update the
comment on the Totals billing.Totals field (symbol: Totals) from "// TODO: is
this neededed?" to "// TODO: is this needed?" (or remove/clarify the TODO if
more appropriate) so the word "neededed" is corrected to "needed".
---
Nitpick comments:
In `@openmeter/billing/charges/adapter.go`:
- Around line 23-34: The constant names are inconsistent with the type name:
change the constants from ProRatingAdapterModeEnumProratePrices and
ProRatingAdapterModeEnumNoProrate to match the type prefix (e.g.,
ProRatingModeAdapterEnumProratePrices and ProRatingModeAdapterEnumNoProrate),
update the Values() implementation to return the renamed constants, and
search/replace any other usages of the old constant names to the new ones
(ensure the first constant still wraps productcatalog.ProRatingModeProratePrices
and the second remains "no_prorate").
In `@openmeter/billing/charges/adapter/adapter_test.go`:
- Around line 44-177: Tests only cover happy-path CreateCharges ->
GetChargesByIDs round-trips; add focused tests on ChargeService.GetChargeByID,
negative scenarios, and batch creation: add a new test method(s) on
ChargesAdapterTestSuite that calls s.adapter.GetChargeByID (or the ChargeService
implementation) to fetch a single created charge by ID, assert equality with the
created charge, add tests that request a non-existent ID and assert the expected
not-found error/empty result, add tests that call CreateCharges with multiple
valid Charge inputs to verify batch behavior and with invalid inputs/empty
namespace to assert proper validation/error handling; use existing helpers like
newManagedResource, newIntentMeta, CreateTestCustomer and methods
CreateCharges/GetChargesByIDs/GetChargeByID to locate code under test.
- Around line 187-204: Update the test helper newIntentMeta in adapter_test.go
to populate optional fields (at minimum Metadata and Annotations) on the
charges.IntentMeta it returns so the DB round-trip is exercised; set Metadata to
a non-empty map (e.g., string keys/values) and Annotations to a non-empty slice
(and optionally fill TaxConfig, UniqueReferenceID, Subscription if relevant) and
then add/adjust assertions in the test that uses newIntentMeta to verify those
fields survive the mapper/DB round-trip. Ensure you reference the
charges.IntentMeta fields (Metadata, Annotations, and any additional optional
fields you populate) and update the related test expectations accordingly.
In `@openmeter/billing/charges/adapter/create.go`:
- Around line 45-47: The current pairing uses positional indexing between
createdEntities and input to build chargeWithOriginal (variables:
createdEntities, input, chargeWithOriginal), which can be brittle; instead build
an ID-keyed map from createdEntities (key by entity.ID) and then iterate the
input slice to look up each original's matching created entity by ID when
constructing the pairs so you mirror the lo.SliceToMap pattern used for flat
fees/usage/credits and avoid relying on insertion order.
In `@openmeter/billing/charges/adapter/mapper.go`:
- Around line 322-355: The try-cast chain in mapCreditPurchaseSettlementToDB
(using AsInvoiceCreditPurchaseSettlement,
AsExternalAuthorizedCreditPurchaseSettlement,
AsPromotionalCreditPurchaseSettlement) is fragile and missing future variants;
update this function to either switch on a concrete discriminator field on
charges.CreditPurchaseSettlement if one exists (e.g., settlement.Type() or a
Kind/Variant method) and handle each known variant explicitly, or if no
discriminator exists, keep the casts but add a clear top-of-function comment
listing the expected variants and replace the generic error with one that
includes the settlement's identifying info and the handled variants (so failures
indicate an unrecognized variant), ensuring you reference
mapCreditPurchaseSettlementToDB and the three As* methods when making the
change.
- Around line 357-371: The default branch of proRatingConfigFromDB returns
Enabled:false but still sets Mode to ProRatingModeProratePrices, which is
misleading; update the function (proRatingConfigFromDB) so that when returning
Enabled:false it leaves Mode as the zero value (or uses a dedicated "none" enum
like productcatalog.ProRatingModeNone if available) instead of
ProRatingModeProratePrices so the disabled config doesn't imply an active mode.
In `@openmeter/billing/charges/chageusagebased.go`:
- Around line 55-65: UsageBasedIntent declares a TaxConfig field that shadows
the embedded IntentMeta.TaxConfig; remove the duplicate TaxConfig from
UsageBasedIntent so you only use IntentMeta.TaxConfig (and its JSON tag) when
serializing/deserializing, updating any references in code that access
UsageBasedIntent.TaxConfig to instead use the embedded IntentMeta (e.g.,
intent.TaxConfig or intent.IntentMeta.TaxConfig); if the duplicate was
intentional, instead rename the field (e.g., UsageTaxConfig) and update JSON
tags and all usages to make the distinction explicit.
- Around line 40-45: AsCharge() uses a pointer receiver while Validate(),
Type(), and the getters use value receivers, causing inconsistency and
preventing calls on non-addressable values; either change AsCharge to a value
receiver or make the design intentional. Update the method signature from func
(c *UsageBasedCharge) AsCharge() Charge to func (c UsageBasedCharge) AsCharge()
Charge and ensure Charge construction stores a copy (e.g., if Charge.usageBased
is a pointer, assign usageBased: &c or change Charge.usageBased to a value
type), or alternatively document/keep the pointer receiver but accept that
Charge will hold the original pointer; adjust the UsageBasedCharge/Charge types
accordingly (referencing AsCharge, Validate, Type, and the Charge.usageBased
field) for consistency.
In `@openmeter/billing/charges/charge.go`:
- Around line 82-102: The final "return Charge{}" in NewCharge[T FlatFeeCharge |
UsageBasedCharge | CreditPurchaseCharge] is unreachable due to the exhaustive
type constraint; replace it with an explicit panic to signal impossible control
flow. Change the unreachable return to panic("unreachable") (or add a default
branch in the type switch that panics) so NewCharge clearly fails fast if the
constraint is ever changed without updating the switch, referencing the
NewCharge function and the ChargeType* cases (FlatFeeCharge, UsageBasedCharge,
CreditPurchaseCharge).
- Around line 178-190: Charges.Validate currently stringifies nested validation
errors by calling err.Error() when creating ErrChargeInvalid via
ErrChargeInvalid.WithAttr("error", err.Error()); instead preserve the original
error chain so callers can use errors.Is/As by either passing the error value
(ErrChargeInvalid.WithAttr("error", err)) if WithAttr supports non-string
values, or by wrapping the original error into the returned error (e.g., wrap
ErrChargeInvalid with fmt.Errorf("%w: %v", ErrChargeInvalid.WithAttr("index",
i), err) or errors.Join(ErrChargeInvalid.WithAttr("index", i), err)) so the
attribute "error" no longer loses the error type and callers can inspect the
underlying error; update the code in Charges.Validate accordingly.
- Around line 137-147: The method name AsCreditPurchase is inconsistent with
other extractors; rename the method to AsCreditPurchaseCharge and update its
declaration and all call sites (e.g., any place calling Charge.AsCreditPurchase)
to use AsCreditPurchaseCharge; keep the implementation and signature (returns
CreditPurchaseCharge, error) identical aside from the name so behavior doesn't
change, and run tests/compile to ensure no remaining references to
AsCreditPurchase remain.
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 57-65: CreditPurchaseIntent defines a Currency field that shadows
the embedded IntentMeta.Currency causing inconsistent validation between
CreditPurchaseIntent.Validate (which checks i.Currency) and
i.IntentMeta.Validate (which checks the embedded one); fix by either removing
the duplicate Currency from CreditPurchaseIntent and using the embedded
IntentMeta.Currency everywhere (update JSON tags/consumers to use the embedded
field) or, if they represent different currencies, rename the outer field to a
descriptive name like CreditCurrency (and JSON tag "credit_currency"), update
all references and the Validate() on CreditPurchaseIntent to explicitly validate
both fields and assert they match when required; change references to i.Currency
in CreditPurchaseIntent.Validate to the new name or to i.IntentMeta.Currency as
appropriate.
- Around line 15-51: The receiver for AsCharge is a pointer
(*CreditPurchaseCharge) while Validate, Type, and other methods use value
receivers, which breaks method-set consistency; change AsCharge to use a value
receiver (func (c CreditPurchaseCharge) AsCharge() Charge) and ensure the Charge
returned still stores a pointer by assigning creditPurchase: &c so callers with
a value-type CreditPurchaseCharge can call AsCharge and other methods remain
unchanged (references: CreditPurchaseCharge.Validate, CreditPurchaseCharge.Type,
CreditPurchaseCharge.AsCharge, Charge.creditPurchase).
In `@openmeter/billing/charges/chargeflatfee.go`:
- Around line 112-118: FlatFeeState.Validate() is currently a no-op that creates
an empty slice and calls errors.Join unnecessarily; simplify by removing the
unused errs slice and replacing the body of FlatFeeState.Validate with a single
`return nil` so the method clearly communicates there's no validation for now
(update the FlatFeeState.Validate method).
In `@openmeter/billing/charges/stdinvoice.go`:
- Around line 57-65: The Validate method on StandardInvoiceSettlement currently
only validates Status; extend it to validate other required fields (e.g., LineID
and ServicePeriod) by checking for zero/empty values and appending wrapped
errors to the errs slice (similar to the Status check) before returning
errors.Join(errs...). Locate StandardInvoiceSettlement.Validate and add checks
like "if r.LineID == "" { errs = append(errs, fmt.Errorf("lineID: required")) }"
and validate ServicePeriod (nil or empty start/end) with descriptive wrapped
errors so all missing/invalid fields are reported.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (84)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/billinginvoiceline.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline/billinginvoiceline.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline/where.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_create.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_query.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_update.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup/where.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_create.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_query.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_update.gois excluded by!**/ent/db/**openmeter/ent/db/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/where.gois excluded by!**/ent/db/**openmeter/ent/db/charge_create.gois excluded by!**/ent/db/**openmeter/ent/db/charge_delete.gois excluded by!**/ent/db/**openmeter/ent/db/charge_query.gois excluded by!**/ent/db/**openmeter/ent/db/charge_update.gois excluded by!**/ent/db/**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_delete.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/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_delete.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/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_delete.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/customer.gois excluded by!**/ent/db/**openmeter/ent/db/customer/customer.gois excluded by!**/ent/db/**openmeter/ent/db/customer/where.gois excluded by!**/ent/db/**openmeter/ent/db/customer_create.gois excluded by!**/ent/db/**openmeter/ent/db/customer_query.gois excluded by!**/ent/db/**openmeter/ent/db/customer_update.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/standardinvoicesettlement.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement/standardinvoicesettlement.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_delete.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscription.gois excluded by!**/ent/db/**openmeter/ent/db/subscription/subscription.gois excluded by!**/ent/db/**openmeter/ent/db/subscription/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem/subscriptionitem.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase/subscriptionphase.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_update.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 (26)
openmeter/billing/charges/README.mdopenmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/adapter.goopenmeter/billing/charges/adapter/adapter_test.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/get.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/chageusagebased.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeflatfee.goopenmeter/billing/charges/errors.goopenmeter/billing/charges/intent.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/get.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/stdinvoice.goopenmeter/billing/charges/subscription.goopenmeter/ent/schema/billing.goopenmeter/ent/schema/charges.goopenmeter/ent/schema/customer.goopenmeter/ent/schema/subscription.gopkg/framework/entutils/mixins.gotools/migrate/migrations/20260223144814_charges.down.sqltools/migrate/migrations/20260223144814_charges.up.sql
51efaa0 to
8ce07d0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (7)
openmeter/billing/charges/chageusagebased.go (3)
1-1:⚠️ Potential issue | 🟡 MinorTypo in filename:
chageusagebased.go.
Consider renaming tochargeusagebased.gofor consistency and discoverability.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chageusagebased.go` at line 1, The filename has a typo ("chageusagebased.go")—rename the file to "chargeusagebased.go" to match the intended word and improve discoverability; update any imports or references (search the repo for "chageusagebased" and replace with "chargeusagebased"), ensure the package declaration remains "package charges" inside the renamed file, and run go build / go test to catch any leftover references or compile errors.
55-84:⚠️ Potential issue | 🟠 MajorGuard against nil Discounts before Validate().
Line 82 can panic whenDiscountsis nil.🛡️ Suggested fix
- if err := i.Discounts.Validate(); err != nil { - errs = append(errs, fmt.Errorf("discounts: %w", err)) - } + if i.Discounts != nil { + if err := i.Discounts.Validate(); err != nil { + errs = append(errs, fmt.Errorf("discounts: %w", err)) + } + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chageusagebased.go` around lines 55 - 84, The Validate method on UsageBasedIntent can panic when Discounts is nil; update UsageBasedIntent.Validate to guard the nil pointer before calling Discounts.Validate by checking if i.Discounts != nil and only invoking i.Discounts.Validate() when non-nil (and append any returned error with the "discounts: %w" context), otherwise skip validation for discounts or treat nil as no discounts; locate the check inside the UsageBasedIntent.Validate function where Discounts is currently validated and add the nil guard around that call.
12-38:⚠️ Potential issue | 🟡 MinorWrap State.Validate errors with “state”, not “status”.
Line 29 currently labels state validation as status, which makes errors misleading.🔧 Suggested fix
if err := c.State.Validate(); err != nil { - errs = append(errs, fmt.Errorf("status: %w", err)) + errs = append(errs, fmt.Errorf("state: %w", err)) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chageusagebased.go` around lines 12 - 38, In UsageBasedCharge.Validate change the error wrapping for the State validation: currently the call to c.State.Validate() is wrapped with fmt.Errorf("status: %w", err) which is misleading; update that to fmt.Errorf("state: %w", err) so errors from c.State are labeled "state" (leave the Intent and Status validation wraps unchanged).openmeter/billing/charges/README.md (1)
5-31:⚠️ Potential issue | 🟡 MinorPolish the table separator and a few grammar bits.
The current separator row and typos make the table render oddly and read awkwardly.✏️ Suggested doc fixes
| Type | Description | Example | -+----+-----------+-------+ +|------|-------------|---------| | CreditRecognition | Fulfilled by consuming the customer's credit balance, there's no settlement needed, as the system settles the possible credit transfers | | -| InvoiceLaterRecognition | Represents an amount charge that will be eventually paid | The customer have used $10 in the service period of [2026-01-01..2026-01-02] that we are going to invoice the customer for once the billing period happens | -| StandardInvoiceSettlement | Represents a request for the end user that will be eventually payed using a standard invoice | The customer has $20 worth of InvoiceLaterRealization so we send him an invoice with that amount | -| ExternalSettlement | Represents a settlement that is performed on the external system | e.g. the user's own payment gateway handles the settlement and we are just notified of it's status | +| InvoiceLaterRecognition | Represents an amount charge that will be eventually paid | The customer has used $10 in the service period of [2026-01-01..2026-01-02] that we are going to invoice the customer for once the billing period happens | +| StandardInvoiceSettlement | Represents a request for the end user that will be eventually paid using a standard invoice | The customer has $20 worth of InvoiceLaterRealization so we send him an invoice with that amount | +| ExternalSettlement | Represents a settlement that is performed on the external system | e.g. the user's own payment gateway handles the settlement and we are just notified of its status | -# Usage Based charges +# Usage-Based charges @@ -- (optionally): All StandardInvoiceObligationRealizations are tried to fulfilled using credits +- (optionally): All StandardInvoiceObligationRealizations are tried to be fulfilled using credits🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/README.md` around lines 5 - 31, Fix the malformed Markdown table separator and a few grammar issues: replace the current separator row with a proper Markdown separator like "| --- | --- | --- |" so the rows for the types (CreditRecognition, InvoiceLaterRecognition, StandardInvoiceSettlement, ExternalSettlement) render correctly, and correct wording typos in the descriptions and examples (e.g., "have used" → "has used", "payed" → "paid", "it's" → "its", and any awkward phrasing in headings like "Revenue recognition train" / "Creating an invoice" to read clearly).openmeter/billing/charges/chargecreditpurchase.go (3)
170-175:⚠️ Potential issue | 🟠 Major
initiatedis declared but rejected by Validate.
Values()omitsInitiatedPaymentSettlementStatus, so validation fails for a declared constant.✅ Suggested fix (if initiated is intended to be valid)
func (s PaymentSettlementStatus) Values() []string { return []string{ + string(InitiatedPaymentSettlementStatus), string(AuthorizedPaymentSettlementStatus), string(SettledPaymentSettlementStatus), } }🤖 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 170 - 175, PaymentSettlementStatus.Values() currently returns only AuthorizedPaymentSettlementStatus and SettledPaymentSettlementStatus while InitiatedPaymentSettlementStatus is declared and thus rejected by validation; update the Values() method to include string(InitiatedPaymentSettlementStatus) so that PaymentSettlementStatus.Values() lists all declared constants (or if InitiatedPaymentSettlementStatus should be invalid, remove that constant and any references to it) — look for the PaymentSettlementStatus type and the Values() method to make the change.
311-342:⚠️ Potential issue | 🔴 CriticalAvoid nil-pointer Validate calls in settlement validation.
If the inner settlement pointer is nil,Validate()will panic even after appending the error.🛠 Suggested fix
case CreditPurchaseSettlementTypeInvoice: if s.invoice == nil { errs = append(errs, fmt.Errorf("invoice is required")) - } - - if err := s.invoice.Validate(); err != nil { - errs = append(errs, fmt.Errorf("invoice: %w", err)) + } else if err := s.invoice.Validate(); err != nil { + errs = append(errs, fmt.Errorf("invoice: %w", err)) } case CreditPurchaseSettlementTypeExternal: if s.external == nil { errs = append(errs, fmt.Errorf("external is required")) - } - - if err := s.external.Validate(); err != nil { - errs = append(errs, fmt.Errorf("external: %w", err)) + } else if err := s.external.Validate(); err != nil { + errs = append(errs, fmt.Errorf("external: %w", err)) } case CreditPurchaseSettlementTypePromotional: if s.promotional == nil { errs = append(errs, fmt.Errorf("promotional is required")) - } - - if err := s.promotional.Validate(); err != nil { - errs = append(errs, fmt.Errorf("promotional: %w", err)) + } else if err := s.promotional.Validate(); err != nil { + errs = append(errs, fmt.Errorf("promotional: %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 311 - 342, The Validate method on CreditPurchaseSettlement may call Validate() on a nil inner pointer (invoice/external/promotional) after already appending an error; update CreditPurchaseSettlement.Validate to only call s.invoice.Validate(), s.external.Validate(), or s.promotional.Validate() when the corresponding pointer is non-nil — e.g. for each case first check if s.invoice != nil (or s.external != nil, s.promotional != nil), append the "required" error if nil and skip calling Validate; if non-nil then call its Validate() and wrap any returned error (invoice: %w, external: %w, promotional: %w) before appending to errs, preserving the existing switch and final errors.Join(errs...) behavior.
121-130:⚠️ Potential issue | 🟡 MinorError message doesn’t match the validation condition.
This check allows zero (IsNegative()only rejects negatives), but the message says “positive.” Consider “must not be negative” / “must be non‑negative.”✏️ Suggested fix
if s.CostBasis.IsNegative() { - errs = append(errs, fmt.Errorf("cost basis must be positive")) + errs = append(errs, fmt.Errorf("cost basis must not be negative")) }🤖 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 121 - 130, The error message in GenericCreditPurchaseSettlement.Validate is inconsistent: the CostBasis.IsNegative() check allows zero but the message says "must be positive"; update the error text to "cost basis must not be negative" or "cost basis must be non-negative" so it matches the existing IsNegative() condition (or if you actually require strictly positive, change the condition to reject zero as well by checking IsZero() or <= 0); adjust the fmt.Errorf call in Validate accordingly to reference s.CostBasis.IsNegative() / the new condition.
🧹 Nitpick comments (1)
openmeter/billing/charges/adapter/adapter_test.go (1)
44-86: Consider a mixed-type batch CreateCharges test.
You’re already hitting each type individually; a single test that creates multiple charge types in one call would cover the bulk pairing + mapping logic too.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/adapter_test.go` around lines 44 - 86, Add a new test that calls the adapter's CreateCharges with a mixed-type slice (e.g., the existing FlatFeeCharge plus at least one other charge type created via charges.NewCharge like a UsageCharge or TieredCharge) so the batch pairing/mapping logic is exercised; construct each charge with distinct ManagedResource IDs and valid Intent/State data, call s.adapter.CreateCharges(ctx, []charges.Charge{...}), assert no error, assert created length equals input length, convert each created to GenericCharge via AsGenericCharge and verify their ManagedResource IDs, then fetch them back with GetChargesByIDs and assert created[i] equals fetched[i] to ensure mapping and persistence work for mixed-type batches (use the existing TestCreateAndGetFlatFeeCharge structure and helper methods such as CreateTestCustomer, newManagedResource, newIntentMeta, CreateCharges, and GetChargesByIDs).
🤖 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/chargecreditpurchase.go`:
- Around line 68-90: CreditPurchaseIntent.Validate currently skips validating
the settlement details; update the method to call i.Settlement.Validate() and
append any returned error to errs with context (e.g., fmt.Errorf("settlement:
%w", err)); perform this check where other nested validations occur (alongside
IntentMeta, Currency, TaxConfig) and ensure you handle a nil i.Settlement if
that is allowed by its type.
---
Duplicate comments:
In `@openmeter/billing/charges/chageusagebased.go`:
- Line 1: The filename has a typo ("chageusagebased.go")—rename the file to
"chargeusagebased.go" to match the intended word and improve discoverability;
update any imports or references (search the repo for "chageusagebased" and
replace with "chargeusagebased"), ensure the package declaration remains
"package charges" inside the renamed file, and run go build / go test to catch
any leftover references or compile errors.
- Around line 55-84: The Validate method on UsageBasedIntent can panic when
Discounts is nil; update UsageBasedIntent.Validate to guard the nil pointer
before calling Discounts.Validate by checking if i.Discounts != nil and only
invoking i.Discounts.Validate() when non-nil (and append any returned error with
the "discounts: %w" context), otherwise skip validation for discounts or treat
nil as no discounts; locate the check inside the UsageBasedIntent.Validate
function where Discounts is currently validated and add the nil guard around
that call.
- Around line 12-38: In UsageBasedCharge.Validate change the error wrapping for
the State validation: currently the call to c.State.Validate() is wrapped with
fmt.Errorf("status: %w", err) which is misleading; update that to
fmt.Errorf("state: %w", err) so errors from c.State are labeled "state" (leave
the Intent and Status validation wraps unchanged).
In `@openmeter/billing/charges/chargecreditpurchase.go`:
- Around line 170-175: PaymentSettlementStatus.Values() currently returns only
AuthorizedPaymentSettlementStatus and SettledPaymentSettlementStatus while
InitiatedPaymentSettlementStatus is declared and thus rejected by validation;
update the Values() method to include string(InitiatedPaymentSettlementStatus)
so that PaymentSettlementStatus.Values() lists all declared constants (or if
InitiatedPaymentSettlementStatus should be invalid, remove that constant and any
references to it) — look for the PaymentSettlementStatus type and the Values()
method to make the change.
- Around line 311-342: The Validate method on CreditPurchaseSettlement may call
Validate() on a nil inner pointer (invoice/external/promotional) after already
appending an error; update CreditPurchaseSettlement.Validate to only call
s.invoice.Validate(), s.external.Validate(), or s.promotional.Validate() when
the corresponding pointer is non-nil — e.g. for each case first check if
s.invoice != nil (or s.external != nil, s.promotional != nil), append the
"required" error if nil and skip calling Validate; if non-nil then call its
Validate() and wrap any returned error (invoice: %w, external: %w, promotional:
%w) before appending to errs, preserving the existing switch and final
errors.Join(errs...) behavior.
- Around line 121-130: The error message in
GenericCreditPurchaseSettlement.Validate is inconsistent: the
CostBasis.IsNegative() check allows zero but the message says "must be
positive"; update the error text to "cost basis must not be negative" or "cost
basis must be non-negative" so it matches the existing IsNegative() condition
(or if you actually require strictly positive, change the condition to reject
zero as well by checking IsZero() or <= 0); adjust the fmt.Errorf call in
Validate accordingly to reference s.CostBasis.IsNegative() / the new condition.
In `@openmeter/billing/charges/README.md`:
- Around line 5-31: Fix the malformed Markdown table separator and a few grammar
issues: replace the current separator row with a proper Markdown separator like
"| --- | --- | --- |" so the rows for the types (CreditRecognition,
InvoiceLaterRecognition, StandardInvoiceSettlement, ExternalSettlement) render
correctly, and correct wording typos in the descriptions and examples (e.g.,
"have used" → "has used", "payed" → "paid", "it's" → "its", and any awkward
phrasing in headings like "Revenue recognition train" / "Creating an invoice" to
read clearly).
---
Nitpick comments:
In `@openmeter/billing/charges/adapter/adapter_test.go`:
- Around line 44-86: Add a new test that calls the adapter's CreateCharges with
a mixed-type slice (e.g., the existing FlatFeeCharge plus at least one other
charge type created via charges.NewCharge like a UsageCharge or TieredCharge) so
the batch pairing/mapping logic is exercised; construct each charge with
distinct ManagedResource IDs and valid Intent/State data, call
s.adapter.CreateCharges(ctx, []charges.Charge{...}), assert no error, assert
created length equals input length, convert each created to GenericCharge via
AsGenericCharge and verify their ManagedResource IDs, then fetch them back with
GetChargesByIDs and assert created[i] equals fetched[i] to ensure mapping and
persistence work for mixed-type batches (use the existing
TestCreateAndGetFlatFeeCharge structure and helper methods such as
CreateTestCustomer, newManagedResource, newIntentMeta, CreateCharges, and
GetChargesByIDs).
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (84)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/billinginvoiceline.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline/billinginvoiceline.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline/where.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_create.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_query.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoiceline_update.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup/billinginvoicesplitlinegroup.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup/where.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_create.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_query.gois excluded by!**/ent/db/**openmeter/ent/db/billinginvoicesplitlinegroup_update.gois excluded by!**/ent/db/**openmeter/ent/db/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/charge.gois excluded by!**/ent/db/**openmeter/ent/db/charge/where.gois excluded by!**/ent/db/**openmeter/ent/db/charge_create.gois excluded by!**/ent/db/**openmeter/ent/db/charge_delete.gois excluded by!**/ent/db/**openmeter/ent/db/charge_query.gois excluded by!**/ent/db/**openmeter/ent/db/charge_update.gois excluded by!**/ent/db/**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_delete.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/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_delete.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/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_delete.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_query.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.gois excluded by!**/ent/db/**openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/customer.gois excluded by!**/ent/db/**openmeter/ent/db/customer/customer.gois excluded by!**/ent/db/**openmeter/ent/db/customer/where.gois excluded by!**/ent/db/**openmeter/ent/db/customer_create.gois excluded by!**/ent/db/**openmeter/ent/db/customer_query.gois excluded by!**/ent/db/**openmeter/ent/db/customer_update.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/standardinvoicesettlement.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement/standardinvoicesettlement.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement/where.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_create.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_delete.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_query.gois excluded by!**/ent/db/**openmeter/ent/db/standardinvoicesettlement_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscription.gois excluded by!**/ent/db/**openmeter/ent/db/subscription/subscription.gois excluded by!**/ent/db/**openmeter/ent/db/subscription/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscription_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem/subscriptionitem.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionitem_update.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase/subscriptionphase.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase/where.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_create.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_query.gois excluded by!**/ent/db/**openmeter/ent/db/subscriptionphase_update.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 (25)
openmeter/billing/charges/README.mdopenmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/adapter.goopenmeter/billing/charges/adapter/adapter_test.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/get.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/chageusagebased.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeflatfee.goopenmeter/billing/charges/errors.goopenmeter/billing/charges/intent.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/create.goopenmeter/billing/charges/service/get.goopenmeter/billing/charges/service/service.goopenmeter/billing/charges/stdinvoice.goopenmeter/billing/charges/subscription.goopenmeter/ent/schema/billing.goopenmeter/ent/schema/charges.goopenmeter/ent/schema/customer.goopenmeter/ent/schema/subscription.gotools/migrate/migrations/20260224104052_charges.down.sqltools/migrate/migrations/20260224104052_charges.up.sql
🚧 Files skipped from review as they are similar to previous changes (9)
- openmeter/billing/charges/service.go
- openmeter/billing/charges/service/create.go
- openmeter/billing/charges/adapter.go
- openmeter/billing/charges/service/get.go
- openmeter/billing/charges/service/service.go
- openmeter/billing/charges/adapter/adapter.go
- openmeter/billing/charges/errors.go
- openmeter/billing/charges/stdinvoice.go
- openmeter/billing/charges/chargeflatfee.go
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/adapter_test.go`:
- Around line 132-176: The current TestCreateAndGetCreditPurchaseCharge only
covers the invoice settlement happy path; add unit tests that exercise other
settlement variants (e.g. external/promotional settlements created via
charges.NewCreditPurchaseSettlement with the appropriate
InvoiceCreditPurchaseSettlement alternative structs), plus negative tests for
invalid payloads (missing ManagedResource ID, invalid Intent/CreditAmount,
incorrect SettlementCurrency or CostBasis) to assert CreateCharges returns
validation errors and GetChargesByIDs behaves correctly; add new test functions
in the same suite (e.g. TestCreateCreditPurchase_ExternalSettlement,
TestCreateCreditPurchase_PromotionalSettlement,
TestCreateCreditPurchase_InvalidPayload) that construct Charge objects using
charges.CreditPurchaseCharge, call s.adapter.CreateCharges and
s.adapter.GetChargesByIDs, and assert success or expected error cases
accordingly.
In `@openmeter/billing/charges/chargeusagebased.go`:
- Around line 55-98: UsageBasedIntent.Validate() currently omits checking the
SettlementMode field, allowing empty/unknown modes to pass validation; update
the method (UsageBasedIntent.Validate) to validate i.SettlementMode (e.g.,
ensure it is not the zero/empty value or productcatalog.SettlementMode("")
and/or not an Unknown/Invalid sentinel in productcatalog) and append a
descriptive error like "settlement mode is required/invalid" to the errs slice
when it fails so invalid SettlementMode values are rejected.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (14)
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/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/chargeusagebased.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased/where.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_create.gois excluded by!**/ent/db/**openmeter/ent/db/chargeusagebased_update.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 (11)
openmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/adapter_test.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeusagebased.goopenmeter/billing/charges/stdinvoice.goopenmeter/ent/schema/charges.gotools/migrate/migrations/20260224121149_charges.down.sqltools/migrate/migrations/20260224121149_charges.up.sql
🚧 Files skipped from review as they are similar to previous changes (3)
- openmeter/billing/charges/adapter/mapper.go
- openmeter/billing/charges/stdinvoice.go
- openmeter/billing/charges/adapter/create.go
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/chargeusagebased.go`:
- Line 63: The JSON tag for the Discounts field on UsageBasedIntent is
incorrectly set to "rateCardDiscounts"; update the struct tag on the Discounts
field (Discounts *productcatalog.Discounts) to `json:"discounts"` and search for
any serialization/deserialization uses of UsageBasedIntent or the Discounts
field to adjust tests or callers that expect "rateCardDiscounts" to the new
"discounts" key so the API contract remains consistent.
- Around line 73-75: The current validation uses i.InvoiceAt.IsZero() ||
i.InvoiceAt.Before(i.ServicePeriod.From) but the error message says "must be
after", yet Before allows equality; update the check to enforce strict ordering
by replacing the Before test with a non-After check (i.e., treat equal as
invalid) so the condition becomes i.InvoiceAt.IsZero() ||
!i.InvoiceAt.After(i.ServicePeriod.From), keeping the error message as-is and
referencing i.InvoiceAt and i.ServicePeriod.From in chargeusagebased.go.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
openmeter/billing/charges/chargeusagebased.go (2)
54-54: JSON tag likely mismatched (rateCardDiscounts).
This still looks like a copy/paste artifact; intent JSON probably wants"discounts".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargeusagebased.go` at line 54, The struct field Discounts in chargeusagebased.go currently uses the JSON tag `rateCardDiscounts`, which is a copy/paste artifact; update the tag to `"discounts"` so the field serializes/deserializes as intended (modify the Discounts *productcatalog.Discounts `json:"rateCardDiscounts"` declaration to use `json:"discounts"`). Ensure the change is made on the Discounts field to preserve type and behavior.
64-66: Boundary mismatch:Beforeallows equality but message says “after”.
If equality is allowed, the message should say “on or after”; if not, the check should use!After(...).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/chargeusagebased.go` around lines 64 - 66, The boundary check for i.InvoiceAt vs i.ServicePeriod.From is inconsistent: either allow equality and change the error text to "invoice at must be on or after service period from", or enforce strict "after" by replacing the condition with !i.InvoiceAt.After(i.ServicePeriod.From); update the code around the IsZero/Before check (the block using i.InvoiceAt, i.ServicePeriod.From, Before, IsZero) accordingly so the condition and the fmt.Errorf message match.
🧹 Nitpick comments (1)
openmeter/billing/charges/adapter/create.go (1)
26-28: Optional: return an empty slice instead of nil.
This avoids nil checks for callers whenin.Intentsis empty.♻️ Suggested tweak
- if len(in.Intents) == 0 { - return nil, nil - } + if len(in.Intents) == 0 { + return charges.Charges{}, nil + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/adapter/create.go` around lines 26 - 28, The current early-return returns nil for the intents result when in.Intents is empty; change that to return an empty slice instead of nil so callers don't need nil checks. Update the branch that checks if len(in.Intents) == 0 to return an empty slice value for the function's result type (rather than nil) along with the nil error; ensure you construct the empty slice with the correct element type matching the function's return signature so other code consuming the result can iterate safely.
🤖 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/charge.go`:
- Around line 199-205: The type switch in NewChargeIntent is comparing against
FlatFeeCharge but the generic parameter T is constrained to
FlatFeeIntent|UsageBasedIntent|CreditPurchaseIntent, so the FlatFee case never
matches; change the case to use FlatFeeIntent (i.e., case FlatFeeIntent:) and
set ChargeIntent{t: ChargeTypeFlatFee, flatFee: &v.Intent} so the flatFee branch
is populated correctly (verify similar patterns for UsageBasedIntent and
CreditPurchaseIntent match their respective types).
- Around line 147-152: The Values() method for the ChargeStatus enum currently
returns only Active/Settled/Final which causes Validate() to reject newly
created charges because adapter/buildCreateCharge sets status to
ChargeStatusCreated; update ChargeStatus.Values() to include
string(ChargeStatusCreated) so that "created" is an accepted/valid status,
ensuring Validate(), ChargeStatus.Values(), and adapter/buildCreateCharge remain
consistent.
---
Duplicate comments:
In `@openmeter/billing/charges/chargeusagebased.go`:
- Line 54: The struct field Discounts in chargeusagebased.go currently uses the
JSON tag `rateCardDiscounts`, which is a copy/paste artifact; update the tag to
`"discounts"` so the field serializes/deserializes as intended (modify the
Discounts *productcatalog.Discounts `json:"rateCardDiscounts"` declaration to
use `json:"discounts"`). Ensure the change is made on the Discounts field to
preserve type and behavior.
- Around line 64-66: The boundary check for i.InvoiceAt vs i.ServicePeriod.From
is inconsistent: either allow equality and change the error text to "invoice at
must be on or after service period from", or enforce strict "after" by replacing
the condition with !i.InvoiceAt.After(i.ServicePeriod.From); update the code
around the IsZero/Before check (the block using i.InvoiceAt,
i.ServicePeriod.From, Before, IsZero) accordingly so the condition and the
fmt.Errorf message match.
---
Nitpick comments:
In `@openmeter/billing/charges/adapter/create.go`:
- Around line 26-28: The current early-return returns nil for the intents result
when in.Intents is empty; change that to return an empty slice instead of nil so
callers don't need nil checks. Update the branch that checks if len(in.Intents)
== 0 to return an empty slice value for the function's result type (rather than
nil) along with the nil error; ensure you construct the empty slice with the
correct element type matching the function's return signature so other code
consuming the result can iterate safely.
ℹ️ Review info
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
openmeter/billing/charges/adapter.goopenmeter/billing/charges/adapter/adapter_test.goopenmeter/billing/charges/adapter/create.goopenmeter/billing/charges/adapter/mapper.goopenmeter/billing/charges/charge.goopenmeter/billing/charges/chargecreditpurchase.goopenmeter/billing/charges/chargeflatfee.goopenmeter/billing/charges/chargeusagebased.goopenmeter/billing/charges/intent.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/create.go
🚧 Files skipped from review as they are similar to previous changes (3)
- openmeter/billing/charges/adapter/adapter_test.go
- openmeter/billing/charges/adapter.go
- openmeter/billing/charges/adapter/mapper.go
c1081c6 to
e089d85
Compare
Overview
Adds basic types for charges. This code is mostly dead code, the only reason for this pr, so that actual logic changes are made into sizable PRs.
Given this is closely billing related, I am going to add this under billing as a seperate service. Over time billing should follow this structure of having different sub-services.
Summary by CodeRabbit
New Features
Tests