Skip to content

fix: invoice edit tax code diff - #4621

Merged
turip merged 3 commits into
mainfrom
feat/repro-invoice-edit-taxcode
Jul 1, 2026
Merged

turip merged 3 commits into
mainfrom
feat/repro-invoice-edit-taxcode

Conversation

@turip

@turip turip commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Overview

Fix invoice editing for charge-backed lines whose tax config is represented by provider-default omission in API edit payloads.

For API-originated invoice edits, billing now normalizes both the persisted invoice and the edited invoice before line diffing. Nil or identity-less tax configs are resolved to the namespace provider-default tax code, explicit provider codes are resolved to TaxCodeID, and API diff equality compares only tax behavior and resolved TaxCodeID. This prevents unrelated invoice edits from being interpreted as tax-code edits while keeping charge-managed tax config immutable.

System-originated edits continue to use full TaxConfig.Equal, so resolved tax-code snapshots are not ignored outside the API edit path.

Changes

  • Normalize invoice-line tax configs before API edit diffing, including provider-default lookup by taxcode.ProviderDefaultTaxCodeKey.
  • Keep the diff-specific tax config equality scoped to ChangeSourceAPIRequest; system edits use full tax config equality.
  • Add tax-code service lookup support by key and seed the provider-default tax code where e2e/local fixtures exercise API invoice edits with omitted tax config.
  • Add unit coverage for provider-default resolution, explicit provider-code resolution, API-vs-system diff behavior, and unresolved tax-code validation.
  • Extend the invoice edit e2e scenario to reproduce the staging shape: the line has a defaulted tax code, the edit payload omits it, and the edit applies a discount.

Validation

  • env POSTGRES_HOST=127.0.0.1 make test-nocache
  • make etoe
  • direnv exec . make lint-go-fast
  • Focused billing/Stripe/notification tests while iterating:
    • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 ./test/billing
    • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 -run TestStripeInvoicing/TestEmptyInvoiceGenerationZeroUsage ./test/app/stripe
    • env POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 ./test/notification

Summary by CodeRabbit

  • New Features

    • Added support for resolving tax codes by key, including the provider default tax code.
    • Default tax code handling is now consistent across billing flows and test setups.
  • Bug Fixes

    • Invoice line edits now handle defaulted tax codes more reliably.
    • Tax configuration comparisons during invoice updates now better preserve expected editable values while avoiding unnecessary changes.

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

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces a ProviderDefaultTaxCodeKey constant and a new GetTaxCodeByKey lookup capability across the taxcode repository/service/adapter stack, replacing hard-coded "default" strings. Billing invoice update logic now threads billing.ChangeSource through line diffing, sanitizing and comparing tax configs differently for API vs system sources. Invoice line merge logic now unconditionally overwrites TaxConfig. Tests and e2e suites are updated to provision and assert the provider default tax code.

Changes

Provider default tax code key + diffing

Layer / File(s) Summary
ProviderDefaultTaxCodeKey constant and GetTaxCodeByKey lookup path
openmeter/taxcode/taxcode.go, openmeter/taxcode/service.go, openmeter/taxcode/repository.go, openmeter/taxcode/errors.go, openmeter/taxcode/adapter/taxcode.go, openmeter/taxcode/service/taxcode.go, openmeter/taxcode/service/taxcode_test.go, openmeter/productcatalog/tax_test.go, openmeter/server/server_test.go
Adds the ProviderDefaultTaxCodeKey constant, GetTaxCodeByKeyInput with validation, new GetTaxCodeByKey methods across Repository/Service/adapter, a not-found error constructor, and matching test stub/noop implementations.
Using the new key constant in config and test seeding
app/config/taxcode.go, openmeter/taxcode/namespacehandler_test.go, openmeter/taxcode/testutils/env.go
Replaces hard-coded "default" key literals with taxcode.ProviderDefaultTaxCodeKey in config seed and test setup.
Invoice line merge overwrites TaxConfig
openmeter/billing/httpdriver/invoiceline.go, openmeter/billing/httpdriver/invoiceline_test.go
Merge logic now unconditionally overwrites existing.TaxConfig from incoming rate card data instead of preserving an equal existing instance; tests updated to expect cleared TaxCode/TaxCodeID in relevant scenarios.
Source-aware tax config sanitization and diffing
openmeter/billing/service/invoiceupdate.go, openmeter/billing/service/invoiceupdate_test.go, openmeter/billing/service/gatheringinvoice.go, openmeter/billing/service/stdinvoice.go, openmeter/billing/worker/subscriptionsync/service/sync_test.go
Threads ctx and billing.ChangeSource through diffMutableInvoiceLines/diffInvoiceLine, adds tax config sanitization/resolution helpers, and compares only Behavior/TaxCodeID for API-sourced diffs vs full equality otherwise; extensive new tests cover these paths.
Test/e2e provisioning of provider default tax code
test/billing/suite.go, test/billing/invoice_test.go, test/billing/collection_test.go, test/billing/discount_test.go, test/billing/tax_test.go, test/app/stripe/invoice_test.go, e2e/billinginvoice_discount_edit_test.go
Adds ProvisionProviderDefaultTaxCode/getOrCreateTaxCodeByKey helpers and calls them across multiple test setups; e2e test renamed and extended to assert/clear defaulted TaxCodeId.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4224: Both PRs change how TaxConfig represents tax code identity (TaxCodeID vs resolved) during billing/invoice merge flows.
  • openmeterio/openmeter#4588: Both PRs modify diffInvoiceLine's tax-config override computation in openmeter/billing/service/invoiceupdate.go.
  • openmeterio/openmeter#4591: Both PRs make the invoice-line diffing path billing.ChangeSource-aware, touching the same diffMutableInvoiceLines implementation.

Suggested labels: area/billing

Suggested reviewers: tothandras, borbelyr-kong

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.26% 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 title matches the main change: fixing invoice edit tax code diff behavior.
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.
✨ 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/repro-invoice-edit-taxcode

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.

@greptile-apps

greptile-apps Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes invoice edit diffs for tax configs that use provider-default omission. The main changes are:

  • Normalize persisted and edited invoice-line tax configs before API diffing.
  • Resolve omitted tax-code identity to the namespace provider-default tax code.
  • Compare API tax diffs by tax behavior and resolved tax-code ID.
  • Keep system-originated invoice diffs on full tax-config equality.
  • Add key-based tax-code lookup and update billing test coverage.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
openmeter/billing/httpdriver/invoiceline.go The replace merge path now lets omitted tax-code identity flow into billing diff normalization.
openmeter/billing/service/invoiceupdate.go API invoice edits now normalize tax configs before diffing, while system edits keep full tax-config comparison.
openmeter/taxcode/adapter/taxcode.go Tax codes can now be resolved by namespace and key for provider-default lookup.
app/config/taxcode.go The seeded provider-default tax code now uses the shared tax-code key constant.

Reviews (3): Last reviewed commit: "fix(billing): restore invoice diff compa..." | Re-trigger Greptile

@turip turip changed the title Fix invoice edit tax code diff fix: invoice edit tax code diff Jul 1, 2026
@turip
turip marked this pull request as ready for review July 1, 2026 10:39
@turip
turip requested a review from a team as a code owner July 1, 2026 10:39

@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 (3)
openmeter/taxcode/taxcode.go (1)

15-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider a short doc comment on this constant.

ProviderDefaultTaxCodeKey is now referenced across config seeding, billing invoice diff resolution, and several test suites — a one-liner explaining its role (the stable key used to resolve a tax config to the provider/invoicing app's own default tax code) would help future readers who only see the usage sites.

As per coding guidelines, "When adding comments or docstrings, explain intent and domain constraints that are not obvious from the code itself."

📝 Suggested doc comment
+// ProviderDefaultTaxCodeKey is the stable key used to identify the tax code that
+// represents "let the invoicing provider apply its own default tax treatment".
 const ProviderDefaultTaxCodeKey = "default"
🤖 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/taxcode/taxcode.go` around lines 15 - 16, Add a short doc comment
for ProviderDefaultTaxCodeKey in taxcode.go that explains it is the stable key
used to resolve the provider/invoicing app’s own default tax code in config
seeding and billing invoice diff resolution. Keep it a one-liner placed directly
above the constant so readers understand its intent from the symbol name alone.
openmeter/taxcode/namespacehandler_test.go (1)

20-25: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Nice constant swap, but a couple lookups still use the raw string.

Seed/creation calls now use taxcode.ProviderDefaultTaxCodeKey, but keyToTC["default"] on Line 71 and Line 117 still hardcode the literal. Works fine today since the constant's value is "default", but it'd be more consistent (and safer if the value ever changes) to use the constant everywhere in this file.

♻️ Suggested tweak
-		defaultTC, ok := keyToTC["default"]
+		defaultTC, ok := keyToTC[taxcode.ProviderDefaultTaxCodeKey]

and similarly for Line 117:

-		gotDefault, ok := keyToTC["default"]
+		gotDefault, ok := keyToTC[taxcode.ProviderDefaultTaxCodeKey]

Also applies to: 71-71, 92-96, 117-117, 141-146

🤖 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/taxcode/namespacehandler_test.go` around lines 20 - 25, The
namespace handler tests still hardcode the default tax code lookup string in a
few places instead of using the shared constant. Update the lookup/assertion
code in namespacehandler_test.go to use taxcode.ProviderDefaultTaxCodeKey
everywhere keyToTC["default"] is referenced, including the checks around the
existing test cases that exercise default tax code behavior, so the tests stay
consistent with the seed/creation calls and remain safe if the constant value
changes.
openmeter/billing/service/invoiceupdate.go (1)

293-340: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider a short docstring here.

sanitizeTaxConfigForDiff packs in a fair bit of business logic (empty-string normalization, provider-default resolution vs. explicit-provider resolution) that isn't obvious from a glance. A short comment on the observable contract (e.g., "returns a tax config guaranteed to have a resolved, non-empty TaxCodeID for diff comparison purposes") would help future readers.

🤖 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/service/invoiceupdate.go` around lines 293 - 340, Add a
short docstring to sanitizeTaxConfigForDiff explaining its contract: it
normalizes empty TaxCodeID values and returns a tax config guaranteed to have a
resolved non-empty TaxCodeID for diff comparison. Keep it near the
sanitizeTaxConfigForDiff signature so readers can understand the
provider-default vs. explicit Stripe resolution paths without tracing the
internal logic.

Source: Coding guidelines

🤖 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/service/invoiceupdate.go`:
- Around line 212-340: The invoice edit diff sanitization path is doing repeated
namespace-scoped tax-code lookups per line, which can create N+1 database calls
in invoice updates. Memoize the provider-default tax code once in
invoiceWithSanitizedTaxConfigForDiff (similar to the syncx.OnceValues pattern
used in defaultTaxCodeResolversForInvoiceUpdate) and thread a cached getter
through sanitizeInvoiceLineTaxConfigForDiff and sanitizeTaxConfigForDiff instead
of calling s.taxCodeService.GetTaxCodeByKey directly for each line; keep
productcatalog.ResolveTaxConfig on the same memoized path where it resolves the
same default/provider tax code.

---

Nitpick comments:
In `@openmeter/billing/service/invoiceupdate.go`:
- Around line 293-340: Add a short docstring to sanitizeTaxConfigForDiff
explaining its contract: it normalizes empty TaxCodeID values and returns a tax
config guaranteed to have a resolved non-empty TaxCodeID for diff comparison.
Keep it near the sanitizeTaxConfigForDiff signature so readers can understand
the provider-default vs. explicit Stripe resolution paths without tracing the
internal logic.

In `@openmeter/taxcode/namespacehandler_test.go`:
- Around line 20-25: The namespace handler tests still hardcode the default tax
code lookup string in a few places instead of using the shared constant. Update
the lookup/assertion code in namespacehandler_test.go to use
taxcode.ProviderDefaultTaxCodeKey everywhere keyToTC["default"] is referenced,
including the checks around the existing test cases that exercise default tax
code behavior, so the tests stay consistent with the seed/creation calls and
remain safe if the constant value changes.

In `@openmeter/taxcode/taxcode.go`:
- Around line 15-16: Add a short doc comment for ProviderDefaultTaxCodeKey in
taxcode.go that explains it is the stable key used to resolve the
provider/invoicing app’s own default tax code in config seeding and billing
invoice diff resolution. Keep it a one-liner placed directly above the constant
so readers understand its intent from the symbol name alone.
🪄 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: b08bc315-772d-47a3-8434-1ea8634250fb

📥 Commits

Reviewing files that changed from the base of the PR and between 7899b41 and 30dd176.

📒 Files selected for processing (26)
  • app/config/taxcode.go
  • e2e/billinginvoice_discount_edit_test.go
  • openmeter/billing/httpdriver/invoiceline.go
  • openmeter/billing/httpdriver/invoiceline_test.go
  • openmeter/billing/service/gatheringinvoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/invoiceupdate_test.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/productcatalog/tax_test.go
  • openmeter/server/server_test.go
  • openmeter/taxcode/adapter/taxcode.go
  • openmeter/taxcode/errors.go
  • openmeter/taxcode/namespacehandler_test.go
  • openmeter/taxcode/repository.go
  • openmeter/taxcode/service.go
  • openmeter/taxcode/service/taxcode.go
  • openmeter/taxcode/service/taxcode_test.go
  • openmeter/taxcode/taxcode.go
  • openmeter/taxcode/testutils/env.go
  • test/app/stripe/invoice_test.go
  • test/billing/collection_test.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
  • test/billing/suite.go
  • test/billing/tax_test.go

@turip
turip enabled auto-merge (squash) July 1, 2026 10:55
@turip
turip merged commit 9cea4ab into main Jul 1, 2026
27 checks passed
@turip
turip deleted the feat/repro-invoice-edit-taxcode branch July 1, 2026 10:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants