Skip to content

feat(charges): apply namespace default tax codes on charge create - #4396

Merged
borbelyr-kong merged 5 commits into
mainfrom
feat/add-default-tax-code-to-charges
May 21, 2026
Merged

borbelyr-kong merged 5 commits into
mainfrom
feat/add-default-tax-code-to-charges

Conversation

@borbelyr-kong

@borbelyr-kong borbelyr-kong commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Charges now automatically receive default tax codes when none are provided.
    • Distinct defaults apply for credit purchases vs invoicing flows.
    • Defaults are applied at charge creation and carried through invoices and gathering lines.
  • Tests

    • Extensive test updates to provision, validate, and assert default tax-code provisioning and propagation across charge lifecycles and settlements.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR wires taxcode.Service into the charges stack, adds ChargeIntent helpers, applies organization-default TaxCodeIDs to intents missing TaxConfig.TaxCodeID during charge Create, and updates test infra plus many tests to provision and assert these defaults.

Changes

Tax Code Defaulting in Charges Service

Layer / File(s) Summary
All changes: wiring, defaulting, helpers, tests
app/common/*, openmeter/billing/charges/*, test/*
Thread taxcode.Service through app and test constructors; add TaxCodeService to charges Config and service; add applyDefaultTaxCodes invoked by Create to stamp organization-default TaxCodeIDs onto intents missing them; add ChargeIntent.Meta() and WithTaxCodeID() helpers; add BaseSuite.ProvisionDefaultTaxCodes and update many tests to provision and expect defaults.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • turip
  • tothandras
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and concisely summarizes the main change: applying namespace default tax codes during charge creation, which is reflected throughout the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-default-tax-code-to-charges

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

❤️ Share

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

@borbelyr-kong
borbelyr-kong requested a review from turip May 20, 2026 10:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
openmeter/billing/charges/service/create.go (1)

54-62: ⚡ Quick win

Use defensive copies instead of mutating the config in place.

The function stamps a tax code ID onto the config by mutating it directly—which feels a bit risky. If callers are passing around shallow copies of intents that share the same underlying TaxConfig pointer, you could end up accidentally modifying the original intent's tax setup. Not great for predictability.

A safer pattern is to always return a fresh struct with the new values:

♻️ Suggested refactor
 func stampTaxCodeID(cfg *productcatalog.TaxCodeConfig, id string) *productcatalog.TaxCodeConfig {
 	if cfg == nil {
 		return &productcatalog.TaxCodeConfig{TaxCodeID: &id}
 	}

-	cfg.TaxCodeID = &id
-
-	return cfg
+	return &productcatalog.TaxCodeConfig{
+		TaxCodeID: &id,
+		Behavior:  cfg.Behavior,
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/create.go` around lines 54 - 62, The helper
stampTaxCodeID currently mutates the passed productcatalog.TaxCodeConfig
in-place; change it to always return a new productcatalog.TaxCodeConfig copy
with TaxCodeID set to the provided id (and copying any other fields from cfg
when cfg != nil) so callers receive a defensive copy instead of having their
original config mutated; update stampTaxCodeID to construct and return a fresh
struct (not modify cfg) and ensure the returned TaxCodeID uses a newly allocated
string pointer for id.
openmeter/billing/charges/service/taxcode_test.go (1)

33-1410: 💤 Low value

Nice work on the comprehensive test coverage! 🎉

The test suite thoroughly verifies the new default tax code stamping behavior across all charge types, propagation paths, and edge cases. The distinction between invoicing defaults (flat-fee/usage-based) and credit-grant defaults (credit purchase) is correctly tested throughout.

Optional refinement: The most complex multi-step scenarios—like TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine (lines 347-471)—might benefit from brief given/when/then comments at the start to orient readers. But the existing inline comments already make the tests reasonably clear, so this is just a nice-to-have for those really gnarly integration flows. As per coding guidelines, adding concise intent comments when scenarios are non-trivial can help future maintainers quickly grok the test structure.

Overall, the tests are solid, well-structured, and correctly verify the PR objectives! ✨

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/taxcode_test.go` around lines 33 - 1410,
Add a short given/when/then comment header to the complex multi-step test
TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine to improve
readability: locate the test function by name and at its start (before setting
up ctx/ns/defaults/customInvoicing) insert a 2–3 line comment briefly stating
the initial state (given), the action under test (when), and the expected
outcome (then); keep the comments concise and focused so they complement
existing inline comments without duplicating them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 64-72: The code calls GetOrganizationDefaultTaxCodes and then uses
the returned defaults in defaultTaxCodeIDFor without validating them; call
defaults.Validate() (the OrganizationDefaultTaxCodes.Validate method)
immediately after retrieving defaults in the code path that invokes
GetOrganizationDefaultTaxCodes (before passing to defaultTaxCodeIDFor) and
handle the validation error (return or propagate it) so empty
InvoicingTaxCodeID/CreditGrantTaxCodeID are rejected; alternatively, add
.NotEmpty() constraints to the Ent schema for those fields to enforce non-empty
values at the DB level—apply one of these fixes and ensure any error is
logged/returned where GetOrganizationDefaultTaxCodes is called.

---

Nitpick comments:
In `@openmeter/billing/charges/service/create.go`:
- Around line 54-62: The helper stampTaxCodeID currently mutates the passed
productcatalog.TaxCodeConfig in-place; change it to always return a new
productcatalog.TaxCodeConfig copy with TaxCodeID set to the provided id (and
copying any other fields from cfg when cfg != nil) so callers receive a
defensive copy instead of having their original config mutated; update
stampTaxCodeID to construct and return a fresh struct (not modify cfg) and
ensure the returned TaxCodeID uses a newly allocated string pointer for id.

In `@openmeter/billing/charges/service/taxcode_test.go`:
- Around line 33-1410: Add a short given/when/then comment header to the complex
multi-step test
TestCreditPurchaseInvoiceSettlementPropagatesTaxConfigToGatheringLine to improve
readability: locate the test function by name and at its start (before setting
up ctx/ns/defaults/customInvoicing) insert a 2–3 line comment briefly stating
the initial state (given), the action under test (when), and the expected
outcome (then); keep the comments concise and focused so they complement
existing inline comments without duplicating them.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c5503afe-9f66-419e-87c4-c390e5140bb9

📥 Commits

Reviewing files that changed from the base of the PR and between f20774b and 0c4bcca.

📒 Files selected for processing (13)
  • app/common/billing.go
  • app/common/charges.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/featureid_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/service/truncation_test.go
  • openmeter/billing/charges/service/usagebased_test.go

Comment on lines +64 to +72
// defaultTaxCodeIDFor picks which namespace default applies to the given charge type.
// Credit purchases use the credit-grant default; invoicing charges (flat-fee, usage-based) use the invoicing default.
func defaultTaxCodeIDFor(t meta.ChargeType, defaults taxcode.OrganizationDefaultTaxCodes) string {
if t == meta.ChargeTypeCreditPurchase {
return defaults.CreditGrantTaxCodeID
}

return defaults.InvoicingTaxCodeID
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how GetOrganizationDefaultTaxCodes handles missing defaults
rg -nA 20 'func.*GetOrganizationDefaultTaxCodes' --type go

Repository: openmeterio/openmeter

Length of output: 15165


🏁 Script executed:

# Get the full adapter implementation
cat -n openmeter/taxcode/adapter/organizationdefaulttaxcodes.go | head -60

Repository: openmeterio/openmeter

Length of output: 2716


🏁 Script executed:

# Check the OrganizationDefaultTaxCodes type definition
rg -nA 15 'type OrganizationDefaultTaxCodes struct' --type go

Repository: openmeterio/openmeter

Length of output: 5031


🏁 Script executed:

# Look at the create.go file to see how defaultTaxCodeIDFor is used
cat -n openmeter/billing/charges/service/create.go | head -100

Repository: openmeterio/openmeter

Length of output: 3811


🏁 Script executed:

# Get the complete Validate() method for OrganizationDefaultTaxCodes
rg -nA 20 'func \(o OrganizationDefaultTaxCodes\) Validate' --type go

Repository: openmeterio/openmeter

Length of output: 1328


🏁 Script executed:

# Check the Ent schema fields for the tax code IDs
sed -n '26,60p' openmeter/ent/schema/organizationdefaulttaxcodes.go

Repository: openmeterio/openmeter

Length of output: 1165


🏁 Script executed:

# Also check where defaultTaxCodeIDFor is called and how the result is used
rg -nB 5 -A 5 'defaultTaxCodeIDFor' openmeter/billing/charges/service/create.go

Repository: openmeterio/openmeter

Length of output: 848


🏁 Script executed:

# Let's see the context around where GetOrganizationDefaultTaxCodes is called in create.go
rg -nB 10 -A 15 'GetOrganizationDefaultTaxCodes' openmeter/billing/charges/service/create.go

Repository: openmeterio/openmeter

Length of output: 756


🏁 Script executed:

# Check if Validate() is called on the returned defaults anywhere
rg -n 'defaults\.Validate\|GetOrganizationDefaultTaxCodes.*\.Validate' openmeter/billing/charges/service/

Repository: openmeterio/openmeter

Length of output: 47


Add validation of returned defaults before use.

The returned defaults from GetOrganizationDefaultTaxCodes (line 131) is used directly without validation. While OrganizationDefaultTaxCodes.Validate() does check for empty InvoicingTaxCodeID and CreditGrantTaxCodeID, the validation is never called here. The Ent schema also lacks .NotEmpty() constraints on those fields, so the database can return empty strings. This means defaultTaxCodeIDFor could propagate empty IDs onto charge intents.

Either call defaults.Validate() after retrieving them (line 136), or add .NotEmpty() constraints to the Ent schema fields to prevent this at the database level.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/create.go` around lines 64 - 72, The code
calls GetOrganizationDefaultTaxCodes and then uses the returned defaults in
defaultTaxCodeIDFor without validating them; call defaults.Validate() (the
OrganizationDefaultTaxCodes.Validate method) immediately after retrieving
defaults in the code path that invokes GetOrganizationDefaultTaxCodes (before
passing to defaultTaxCodeIDFor) and handle the validation error (return or
propagate it) so empty InvoicingTaxCodeID/CreditGrantTaxCodeID are rejected;
alternatively, add .NotEmpty() constraints to the Ent schema for those fields to
enforce non-empty values at the DB level—apply one of these fixes and ensure any
error is logged/returned where GetOrganizationDefaultTaxCodes is called.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/credits/creditgrant_test.go (1)

90-93: ⚡ Quick win

Use s.T().Context() instead of context.Background() in these tests.

Lines 90, 147, 186, and 244 all create a background context directly, but since you have access to testing.T through the suite (via s.T()), it's better to use s.T().Context() to keep the context lifecycle tied to the test harness.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/credits/creditgrant_test.go` around lines 90 - 93, Replace the use of
context.Background() with the test-scoped context s.T().Context() where the
tests create ctx (e.g., the lines that set ctx := context.Background() before
calling s.GetUniqueNamespace and s.ProvisionDefaultTaxCodes); update all
occurrences in this test (the four places creating ctx) so the context lifecycle
is tied to the testing.T via s.T().Context().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/credits/creditgrant_test.go`:
- Around line 360-362: The test currently compares defaults.CreditGrantTaxCodeID
for equality but doesn't guard against it being empty; add an explicit non-empty
assertion before the equality check to avoid false positives. Locate the call to
s.TaxCodeService.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) and after s.Require().NoError(err)
add s.Require().NotEmpty(defaults.CreditGrantTaxCodeID) (or s.Assert().NotEmpty
if non-fatal preferred), then perform the existing equality assertion against
the expected ID; make the same change at the other occurrence around lines
390-392 to harden both assertions.

---

Nitpick comments:
In `@test/credits/creditgrant_test.go`:
- Around line 90-93: Replace the use of context.Background() with the
test-scoped context s.T().Context() where the tests create ctx (e.g., the lines
that set ctx := context.Background() before calling s.GetUniqueNamespace and
s.ProvisionDefaultTaxCodes); update all occurrences in this test (the four
places creating ctx) so the context lifecycle is tied to the testing.T via
s.T().Context().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a151a8af-d741-443c-afa9-e8e840f5cc7a

📥 Commits

Reviewing files that changed from the base of the PR and between 0c4bcca and bb02df0.

📒 Files selected for processing (15)
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/app/stripe/invoice_credits_test.go
  • test/app/stripe/invoice_test.go
  • test/billing/suite.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/creditgrant_test.go
  • test/credits/rating_test.go
  • test/credits/sanity_lifecycle_test.go
  • test/credits/sanity_test.go

Comment on lines +360 to +362
defaults, err := s.TaxCodeService.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: ns})
s.Require().NoError(err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Harden the default-tax assertion against empty-ID false positives.

Nice coverage update. One small gap: if defaults.CreditGrantTaxCodeID were unexpectedly empty, the equality check could still pass without validating real propagation.

Suggested tweak
 defaults, err := s.TaxCodeService.GetOrganizationDefaultTaxCodes(ctx, taxcode.GetOrganizationDefaultTaxCodesInput{Namespace: ns})
 s.Require().NoError(err)
+s.Require().NotEmpty(defaults.CreditGrantTaxCodeID)

 ...

 s.Require().NotNil(lines[0].TaxConfig.TaxCodeID)
+s.Require().NotEmpty(*lines[0].TaxConfig.TaxCodeID)
 s.Equal(defaults.CreditGrantTaxCodeID, *lines[0].TaxConfig.TaxCodeID, "standard invoice line must reference the namespace default credit-grant tax code")
As per coding guidelines: `**/*_test.go`: Make sure the tests are comprehensive and cover the changes.

Also applies to: 390-392

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/credits/creditgrant_test.go` around lines 360 - 362, The test currently
compares defaults.CreditGrantTaxCodeID for equality but doesn't guard against it
being empty; add an explicit non-empty assertion before the equality check to
avoid false positives. Locate the call to
s.TaxCodeService.GetOrganizationDefaultTaxCodes
(taxcode.GetOrganizationDefaultTaxCodesInput) and after s.Require().NoError(err)
add s.Require().NotEmpty(defaults.CreditGrantTaxCodeID) (or s.Assert().NotEmpty
if non-fatal preferred), then perform the existing equality assertion against
the expected ID; make the same change at the other occurrence around lines
390-392 to harden both assertions.

turip
turip previously approved these changes May 21, 2026

@turip turip left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGFM please rebase

turip
turip previously approved these changes May 21, 2026
@borbelyr-kong
borbelyr-kong force-pushed the feat/add-default-tax-code-to-charges branch from 9e51b15 to 5e607cb Compare May 21, 2026 09:04
@borbelyr-kong
borbelyr-kong enabled auto-merge (squash) May 21, 2026 09:06

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
openmeter/billing/worker/subscriptionsync/service/base_test.go (1)

47-54: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

SuiteBase.Ledger looks unwired in this file’s setup path.

Nice addition overall, but this new field is read by assertLedgerTransactionGroupBookedAt and I can’t see it being initialized in SetupSuite/setupChargesService here. That can make the new ledger assertions fail with ledger service nil checks. Please wire s.Ledger during suite setup (or use the already-wired embedded dependency directly instead of shadowing it).

Also applies to: 60-80, 82-101

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/worker/subscriptionsync/service/base_test.go` around lines
47 - 54, SuiteBase.Ledger is declared but never initialized, causing nil ledger
failures in assertLedgerTransactionGroupBookedAt; initialize or wire it in the
suite setup. In SetupSuite (or setupChargesService) assign s.Ledger to the
already-wired ledger from the embedded billingtest.BaseSuite (or whichever field
holds the initialized ledger) or remove the shadowing field and use the embedded
ledger directly; ensure any uses in assertLedgerTransactionGroupBookedAt
reference the initialized s.Ledger (or the embedded ledger) so ledger service
nil checks pass.
🧹 Nitpick comments (2)
openmeter/billing/charges/service/service.go (1)

57-101: ⚡ Quick win

Wrap joined validation errors with the repository validation error type.

Validate() aggregates errors but returns raw errors.Join(errs...). Please wrap it with models.NewNillableGenericValidationError(...) for consistent validation semantics.

Suggested patch
 import (
 	"errors"
 	"fmt"
 	"log/slog"
 	"slices"
@@
 	"github.com/openmeterio/openmeter/openmeter/productcatalog/feature"
 	"github.com/openmeterio/openmeter/openmeter/taxcode"
+	"github.com/openmeterio/openmeter/pkg/models"
 )
@@
-	return errors.Join(errs...)
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

As per coding guidelines: openmeter/**/*.go: For Validate() error methods, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/service.go` around lines 57 - 101, The
Validate method on Config currently returns raw errors.Join(errs...), so change
the return to wrap the joined errors with
models.NewNillableGenericValidationError(errors.Join(errs...)) to follow repo
validation semantics; keep collecting errs as-is and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) from
Config.Validate so callers receive the standardized validation error type.
test/credits/creditgrant_test.go (1)

95-95: ⚡ Quick win

Prefer s.T().Context() over context.Background() in these tests.

Since testing.T is available, this should use the test-scoped context for lifecycle/cancellation consistency.

As per coding guidelines: **/*_test.go: Use t.Context() in tests when a testing.T or testing.TB is available instead of introducing context.Background() to keep cancellation and lifecycle tied to the test harness.

Also applies to: 152-152, 191-191, 249-249

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/credits/creditgrant_test.go` at line 95, Replace test-local uses of
context.Background() with the test-scoped context from the test harness (e.g.,
s.T().Context() or t.Context()) so cancellation/lifecycle are tied to the test;
search for the assignments to ctx (currently "ctx := context.Background()") in
creditgrant_test.go (occurrences at the shown lines and the other mentioned
instances) and change them to obtain the context from the test runner (use
s.T().Context() if this is a testify suite method or t.Context() if inside a
plain test) ensuring the rest of the test uses the same ctx variable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/service/truncation_test.go`:
- Around line 41-43: Replace the use of context.Background() in
truncation_test.go with the test-scoped context from the test harness: call
s.T().Context() when creating ctx in the test setup (the ctx variable created
near the top of the file where ns is assigned and ProvisionDefaultTaxCodes is
called) and in the later test section around the second occurrence (lines around
the code that provisions tax codes and other test actions, currently using
context.Background()); this ties cancellation and lifecycle to the testing.T
instance instead of using a global background context.

---

Outside diff comments:
In `@openmeter/billing/worker/subscriptionsync/service/base_test.go`:
- Around line 47-54: SuiteBase.Ledger is declared but never initialized, causing
nil ledger failures in assertLedgerTransactionGroupBookedAt; initialize or wire
it in the suite setup. In SetupSuite (or setupChargesService) assign s.Ledger to
the already-wired ledger from the embedded billingtest.BaseSuite (or whichever
field holds the initialized ledger) or remove the shadowing field and use the
embedded ledger directly; ensure any uses in
assertLedgerTransactionGroupBookedAt reference the initialized s.Ledger (or the
embedded ledger) so ledger service nil checks pass.

---

Nitpick comments:
In `@openmeter/billing/charges/service/service.go`:
- Around line 57-101: The Validate method on Config currently returns raw
errors.Join(errs...), so change the return to wrap the joined errors with
models.NewNillableGenericValidationError(errors.Join(errs...)) to follow repo
validation semantics; keep collecting errs as-is and at the end return
models.NewNillableGenericValidationError(errors.Join(errs...)) from
Config.Validate so callers receive the standardized validation error type.

In `@test/credits/creditgrant_test.go`:
- Line 95: Replace test-local uses of context.Background() with the test-scoped
context from the test harness (e.g., s.T().Context() or t.Context()) so
cancellation/lifecycle are tied to the test; search for the assignments to ctx
(currently "ctx := context.Background()") in creditgrant_test.go (occurrences at
the shown lines and the other mentioned instances) and change them to obtain the
context from the test runner (use s.T().Context() if this is a testify suite
method or t.Context() if inside a plain test) ensuring the rest of the test uses
the same ctx variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 17ea07c0-78e2-4652-b6e2-04f9a565a3ad

📥 Commits

Reviewing files that changed from the base of the PR and between 71880f4 and 5e607cb.

📒 Files selected for processing (27)
  • app/common/billing.go
  • app/common/charges.go
  • openmeter/billing/charges/charge.go
  • openmeter/billing/charges/service/advance_test.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/create.go
  • openmeter/billing/charges/service/creditpurchase_test.go
  • openmeter/billing/charges/service/featureid_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/lineage_test.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/service/taxcode_test.go
  • openmeter/billing/charges/service/truncation_test.go
  • openmeter/billing/charges/service/usagebased_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
  • test/app/stripe/invoice_credits_test.go
  • test/app/stripe/invoice_test.go
  • test/billing/suite.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/creditgrant_test.go
  • test/credits/rating_test.go
  • test/credits/sanity_lifecycle_test.go
  • test/credits/sanity_test.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/billing/charges/service/base_test.go

Comment on lines 41 to +43
ctx := context.Background()
ns := s.GetUniqueNamespace("charges-service-truncation-flatfee")
s.ProvisionDefaultTaxCodes(ctx, ns)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use test-scoped context instead of context.Background() in these tests.

Line 41 and Line 99 should use s.T().Context() so cancellation/lifecycle stays tied to the test harness.

Suggested patch
 func (s *ChargeTimestampTruncationTestSuite) TestCreateTruncatesFlatFeeIntentAndProrationInputs() {
-	ctx := context.Background()
+	ctx := s.T().Context()
 	ns := s.GetUniqueNamespace("charges-service-truncation-flatfee")
 	s.ProvisionDefaultTaxCodes(ctx, ns)
@@
 func (s *ChargeTimestampTruncationTestSuite) TestUsageBasedAdvanceTruncatesPersistedCalculationTimestamps() {
-	ctx := context.Background()
+	ctx := s.T().Context()
 	ns := s.GetUniqueNamespace("charges-service-truncation-usagebased")
 	s.ProvisionDefaultTaxCodes(ctx, ns)

As per coding guidelines: **/*_test.go: Use t.Context() in tests when a testing.T or testing.TB is available instead of introducing context.Background() to keep cancellation and lifecycle tied to the test harness.

Also applies to: 99-102

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/service/truncation_test.go` around lines 41 - 43,
Replace the use of context.Background() in truncation_test.go with the
test-scoped context from the test harness: call s.T().Context() when creating
ctx in the test setup (the ctx variable created near the top of the file where
ns is assigned and ProvisionDefaultTaxCodes is called) and in the later test
section around the second occurrence (lines around the code that provisions tax
codes and other test actions, currently using context.Background()); this ties
cancellation and lifecycle to the testing.T instance instead of using a global
background context.

@borbelyr-kong
borbelyr-kong disabled auto-merge May 21, 2026 09:18
@borbelyr-kong
borbelyr-kong requested a review from turip May 21, 2026 09:20
@borbelyr-kong
borbelyr-kong enabled auto-merge (squash) May 21, 2026 09:20
@borbelyr-kong
borbelyr-kong merged commit e6577d5 into main May 21, 2026
28 checks passed
@borbelyr-kong
borbelyr-kong deleted the feat/add-default-tax-code-to-charges branch May 21, 2026 09:35

This branch was previously deployed

1 inactive deployment
dev — 5e607cba Deployed May 21, 2026 by borbelyr-kong via Migration Checks #14558
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants