Skip to content

refactor(billing): remove detailed line tax config domain - #4460

Merged
turip merged 4 commits into
mainfrom
chore/drop-tax-fields-from-detailed-lines
Jun 2, 2026
Merged

turip merged 4 commits into
mainfrom
chore/drop-tax-fields-from-detailed-lines

Conversation

@turip

@turip turip commented May 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Remove tax configuration from detailed-line domain objects and stop writing/reading detailed-line tax fields in billing and charge adapters.
  • Resolve effective detailed-line tax config from the parent standard line where app/API boundaries still need it.
  • Mark the remaining detailed-line Ent tax fields as deprecated so the DB shape stays non-breaking until a later cleanup.

Validation

  • go generate ./openmeter/billing/models/stddetailedline
  • make generate
  • go test ./openmeter/billing/models/stddetailedline ./openmeter/ent/db/...
  • go test ./openmeter/app/stripe/...
  • go vet -tags=dynamic ./openmeter/app/stripe/...
  • go test -tags=dynamic ./openmeter/billing/charges/flatfee/adapter
  • go vet -tags=dynamic ./openmeter/billing/charges/flatfee/adapter
  • make lint-go-fast running
  • make test-nocache pending

Summary by CodeRabbit

  • Refactor

    • Tax resolution moved to the invoice/workflow level; detailed invoice rows no longer carry per-line tax config and legacy tax fields were deprecated/removed.
    • Leaf invoice lines now include an explicit resolved tax config and external billing integrations use that resolved config.
  • New Features

    • Invoices now compute and attach an inherited/resolved tax configuration to leaf lines for downstream billing and tax calculations.
  • Tests

    • Tests updated to validate tax settings at the invoice/DB level and reflect the new resolved-tax behavior.

@turip
turip requested a review from a team as a code owner May 29, 2026 14:39
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 86549cf8-969b-47b5-9358-19959d474ec0

📥 Commits

Reviewing files that changed from the base of the PR and between c0deb12 and 399c6f1.

⛔ Files ignored due to path filters (6)
  • openmeter/ent/db/billingstandardinvoicedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billingstandardinvoicedetailedline/billingstandardinvoicedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
📒 Files selected for processing (17)
  • openmeter/app/stripe/appinvoice.go
  • openmeter/billing/adapter/stdinvoicelinemapper.go
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/billing/models/stddetailedline/mapping.go
  • openmeter/billing/models/stddetailedline/mixin.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/stdinvoice.go
  • test/app/stripe/invoice_test.go
  • test/billing/tax_test.go
💤 Files with no reviewable changes (8)
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • test/billing/tax_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/models/stddetailedline/model.go
✅ Files skipped from review due to trivial changes (1)
  • openmeter/billing/models/stddetailedline/mixin.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/models/stddetailedline/mapping.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • test/app/stripe/invoice_test.go
  • openmeter/billing/stdinvoice.go
  • openmeter/app/stripe/appinvoice.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/adapter/stdinvoicelinemapper.go

📝 Walkthrough

Walkthrough

Removes detailed-line TaxConfig from models and persistence, adds per-leaf resolved TaxConfig on invoices, and threads that resolved config through API mapping, Stripe invoice builders, adapters, and tests.

Changes

Tax Config Resolution and Model Refactoring

Layer / File(s) Summary
Core model refactoring and deprecated schema markers
openmeter/billing/models/stddetailedline/model.go, openmeter/billing/models/stddetailedline/mapping.go, openmeter/billing/models/stddetailedline/derived.gen.go, openmeter/billing/models/stddetailedline/mixin.go
Base removes TaxConfig; BackfillTaxConfig and TaxConfig equality checks removed; FromDB signature simplified; legacy tax DB fields annotated Deprecated.
Invoice-level tax resolution API
openmeter/billing/stdinvoice.go
Adds DetailedLineWithResolvedTaxConfig and GetLeafLinesWithResolvedTaxConfig() that merge invoice default and parent-line tax configs and return leaf lines paired with the resolved config.
Invoice line adapter persistence cleanup
openmeter/billing/adapter/stdinvoicelinemapper.go, openmeter/billing/adapter/stdinvoicelines.go
Detailed-line create/upsert/mapping paths stop writing/backfilling TaxConfig/TaxCodeID/TaxBehavior; stddetailedline.FromDB used directly.
Charge-specific adapter cleanup
openmeter/billing/charges/flatfee/adapter/detailedline.go, openmeter/billing/charges/flatfee/adapter/mapper.go, openmeter/billing/charges/usagebased/adapter/detailedline.go
Removes eager-loading of tax code, removes tax updates in upserts, deletes small mapping helpers, and directly maps DB rows to in-memory detailed lines.
Service-layer tax config removal
openmeter/billing/service/invoicecalc/details.go, openmeter/billing/charges/usagebased/detailedline.go, openmeter/billing/charges/usagebased/service/rating/service_test.go
Stops assigning TaxConfig when generating billing DetailedLine instances; usage-based rating tests updated.
Stripe invoice line generation with resolved tax config
openmeter/app/stripe/appinvoice.go
createInvoice/updateInvoice use GetLeafLinesWithResolvedTaxConfig(); discount/credit/line builders accept DetailedLineWithResolvedTaxConfig; applyTaxSettingsToInvoiceItem now takes explicit resolved taxConfig to set Stripe TaxBehavior/TaxCode.
HTTP API response mapping with resolved tax config
openmeter/billing/httpdriver/invoiceline.go
mapDetailedLinesToAPI/mapDetailedLineToAPI accept explicit taxConfig and populate detailed-line and nested rate-card tax fields from it.
Test updates for resolved tax behaviour
test/app/stripe/invoice_test.go, test/billing/tax_test.go
Tests create/assign Stripe tax codes, attach TaxConfig to pending parent lines, switch resolved-leaf iteration, and assert normalized tax fields on persisted invoice-line rows and Stripe params.

Sequence Diagram(s)

sequenceDiagram
  participant StandardInvoice
  participant LeafResolver
  participant StripeBuilder
  participant APIMapper

  StandardInvoice->>LeafResolver: GetLeafLinesWithResolvedTaxConfig()
  LeafResolver-->>StandardInvoice: []DetailedLineWithResolvedTaxConfig
  StandardInvoice->>StripeBuilder: build invoice items (line, discount, credit) with resolved taxConfig
  StripeBuilder->>StripeBuilder: applyTaxSettingsToInvoiceItem(taxConfig)
  StandardInvoice->>APIMapper: mapDetailedLinesToAPI(taxConfig)
  APIMapper-->>StandardInvoice: API invoice lines with tax fields
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • openmeterio/openmeter#4049: Modifies invoice/detailed-line tax propagation at adapter/database layer; related to changes that remove detailed-line tax updates here.
  • openmeterio/openmeter#4308: Adds organization-default tax-code handling used by updated Stripe invoice tests in this PR.
  • openmeterio/openmeter#4254: Also touches detailed-line TaxConfig propagation during rating—relevant to usage-based detailed-line changes.

Suggested labels

kind/refactor

Suggested reviewers

  • borbelyr-kong
  • tothandras
  • mark-vass-konghq
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.84% 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 directly reflects the main objective: removing tax configuration from the detailed-line domain, which is the primary change across all modified files.
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 chore/drop-tax-fields-from-detailed-lines

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.

@turip
turip force-pushed the chore/drop-tax-fields-from-detailed-lines branch from 554f3aa to c3e2794 Compare May 29, 2026 14:42
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels May 29, 2026
@turip

turip commented May 29, 2026

Copy link
Copy Markdown
Member Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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/charges/flatfee/adapter/detailedline.go (1)

40-48: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Drop the now-unused WithTaxCode() eager-load in FetchCurrentRunDetailedLines.

openmeter/billing/charges/flatfee/adapter/detailedline.go has no other TaxCode usage besides the .WithTaxCode() call on the query, so this edge is only being loaded unnecessarily (extra eager-load query on the read path).

♻️ Proposed cleanup
 		dbLines, err := tx.db.ChargeFlatFeeRunDetailedLine.Query().
 			Where(
 				dbchargeflatfeerundetailedline.NamespaceEQ(charge.Namespace),
 				dbchargeflatfeerundetailedline.RunIDEQ(currentRunID.ID),
 				dbchargeflatfeerundetailedline.DeletedAtIsNil(),
 			).
-			WithTaxCode().
 			All(ctx)
🤖 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/flatfee/adapter/detailedline.go` around lines 40 -
48, The query in FetchCurrentRunDetailedLines is performing an unnecessary
eager-load by calling WithTaxCode(); remove the WithTaxCode() invocation from
the DB query that produces dbLines so the TaxCode edge is not fetched, then
ensure the loop that converts dbLines to flatfee.DetailedLines via
stddetailedline.FromDB remains unchanged (no other TaxCode usages exist).
🧹 Nitpick comments (2)
test/app/stripe/invoice_test.go (1)

565-566: ⚡ Quick win

Add one assertion for resolved tax config in this flow.

This helper now walks GetLeafLinesWithResolvedTaxConfig(), but the test still never checks that inherited/default tax config actually shows up in the Stripe params. A small case with invoice default tax config plus a parent-line override would lock down the core behavior of this refactor.

As per coding guidelines, "**/*_test.go: Make sure the tests are comprehensive and cover the changes."

openmeter/billing/charges/usagebased/adapter/detailedline.go (1)

40-40: ⚡ Quick win

Drop the dead .WithTaxCode() eager load in FetchDetailedLines

mapDetailedLineFromDB + usagebased.DetailedLine.Validate() don’t use any tax-code/tax-config data (they only consume stddetailedline.FromDB(dbLine) plus PricerReferenceID/CorrectsRunID), so this WithTaxCode() join/load is orphaned on this path.

♻️ Proposed cleanup
 		dbLines, err := tx.db.ChargeUsageBasedRunDetailedLine.Query().
 			Where(
 				dbchargeusagebasedrundetailedline.NamespaceEQ(charge.Namespace),
 				dbchargeusagebasedrundetailedline.ChargeIDEQ(charge.ID),
 				dbchargeusagebasedrundetailedline.RunIDIn(runIDs...),
 				dbchargeusagebasedrundetailedline.DeletedAtIsNil(),
 			).
-			WithTaxCode().
 			All(ctx)
🤖 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/usagebased/adapter/detailedline.go` at line 40, The
eager-load call WithTaxCode() in FetchDetailedLines is dead —
mapDetailedLineFromDB and usagebased.DetailedLine.Validate() do not use
tax-code/tax-config data — so remove the WithTaxCode() invocation from the query
construction in FetchDetailedLines; ensure FetchDetailedLines still returns the
expected fields (stddetailedline.FromDB(dbLine), PricerReferenceID,
CorrectsRunID) and run/update any tests that assumed the tax join was present.
🤖 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/httpdriver/invoiceline.go`:
- Line 327: The call to mapDetailedLinesToAPI currently passes the raw
line.TaxConfig which ignores inherited defaults; compute the effective/merged
tax config (e.g., merge line.TaxConfig with
invoice.Workflow.Config.Invoicing.DefaultTaxConfig or use the already-resolved
tax config used for the parent line) and pass that merged config into
mapDetailedLinesToAPI in place of line.TaxConfig so child detailed-line mapping
uses the resolved tax settings consistent with the invoice.

---

Outside diff comments:
In `@openmeter/billing/charges/flatfee/adapter/detailedline.go`:
- Around line 40-48: The query in FetchCurrentRunDetailedLines is performing an
unnecessary eager-load by calling WithTaxCode(); remove the WithTaxCode()
invocation from the DB query that produces dbLines so the TaxCode edge is not
fetched, then ensure the loop that converts dbLines to flatfee.DetailedLines via
stddetailedline.FromDB remains unchanged (no other TaxCode usages exist).

---

Nitpick comments:
In `@openmeter/billing/charges/usagebased/adapter/detailedline.go`:
- Line 40: The eager-load call WithTaxCode() in FetchDetailedLines is dead —
mapDetailedLineFromDB and usagebased.DetailedLine.Validate() do not use
tax-code/tax-config data — so remove the WithTaxCode() invocation from the query
construction in FetchDetailedLines; ensure FetchDetailedLines still returns the
expected fields (stddetailedline.FromDB(dbLine), PricerReferenceID,
CorrectsRunID) and run/update any tests that assumed the tax join was present.
🪄 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: bc521a00-1f3b-40ac-a4e9-a448cffd675a

📥 Commits

Reviewing files that changed from the base of the PR and between 819c22b and c3e2794.

⛔ Files ignored due to path filters (6)
  • openmeter/ent/db/billingstandardinvoicedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billingstandardinvoicedetailedline/billingstandardinvoicedetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline/chargeflatfeerundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeusagebasedrundetailedline/chargeusagebasedrundetailedline.go is excluded by !**/ent/db/**
📒 Files selected for processing (17)
  • openmeter/app/stripe/appinvoice.go
  • openmeter/billing/adapter/stdinvoicelinemapper.go
  • openmeter/billing/adapter/stdinvoicelines.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/billing/models/stddetailedline/mapping.go
  • openmeter/billing/models/stddetailedline/mixin.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/service/invoicecalc/details.go
  • openmeter/billing/stdinvoice.go
  • test/app/stripe/invoice_test.go
  • test/billing/tax_test.go
💤 Files with no reviewable changes (8)
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/models/stddetailedline/derived.gen.go
  • openmeter/billing/models/stddetailedline/model.go
  • openmeter/billing/charges/usagebased/detailedline.go
  • openmeter/billing/service/invoicecalc/details.go
  • test/billing/tax_test.go
  • openmeter/billing/adapter/stdinvoicelines.go

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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/app/stripe/invoice_test.go (1)

179-207: ⚡ Quick win

Use test-scoped context for these new TaxCodeService calls.

These new calls should use s.T().Context() (or a ctx derived from it) instead of a background context so cancellation/lifecycle is tied to the test harness.

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".

🤖 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/app/stripe/invoice_test.go` around lines 179 - 207, The new
TaxCodeService calls use a background ctx; change them to use the test-scoped
context from the test harness by replacing ctx with s.T().Context() (or create a
local ctx := s.T().Context() and pass that) for the calls to
s.TaxCodeService.CreateTaxCode (both defaultInvoicingTaxCode and
defaultCreditGrantTaxCode) and
s.TaxCodeService.UpsertOrganizationDefaultTaxCodes so the operations’ lifecycle
is tied to the test; ensure any subsequent uses of the variable
defaultInvoicingTaxCode/defaultCreditGrantTaxCode still reference the same
test-scoped ctx where needed.
🤖 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/app/stripe/invoice_test.go`:
- Around line 778-783: The test dereferences lineWithDefaultTax after a
non-fatal s.True(found); change the assertions that check lookup success to
fatal assertions (e.g., use s.Require().True(found) or
s.Require().NoError-style) before accessing lo.FromPtr(lineWithDefaultTax...) so
the test stops immediately if lo.Find on expectedInvoiceAddLines fails; apply
the same change to the other similar block around lines 785-790 where a found
boolean is checked before dereferencing the result.

---

Nitpick comments:
In `@test/app/stripe/invoice_test.go`:
- Around line 179-207: The new TaxCodeService calls use a background ctx; change
them to use the test-scoped context from the test harness by replacing ctx with
s.T().Context() (or create a local ctx := s.T().Context() and pass that) for the
calls to s.TaxCodeService.CreateTaxCode (both defaultInvoicingTaxCode and
defaultCreditGrantTaxCode) and
s.TaxCodeService.UpsertOrganizationDefaultTaxCodes so the operations’ lifecycle
is tied to the test; ensure any subsequent uses of the variable
defaultInvoicingTaxCode/defaultCreditGrantTaxCode still reference the same
test-scoped ctx where needed.
🪄 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: f035f0f7-af0c-4d86-99ba-4a829418e43b

📥 Commits

Reviewing files that changed from the base of the PR and between c3e2794 and d6cf558.

📒 Files selected for processing (3)
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • test/app/stripe/invoice_test.go
💤 Files with no reviewable changes (2)
  • openmeter/billing/charges/usagebased/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go

Comment thread test/app/stripe/invoice_test.go Resolved
@turip
turip force-pushed the chore/drop-tax-fields-from-detailed-lines branch from c0deb12 to 399c6f1 Compare June 1, 2026 15:56
@turip
turip merged commit d839096 into main Jun 2, 2026
27 checks passed
@turip
turip deleted the chore/drop-tax-fields-from-detailed-lines branch June 2, 2026 10:42

This branch was previously deployed

1 inactive deployment
dev — 399c6f16 Deployed Jun 1, 2026 by turip via Migration Checks #14755
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants