Skip to content

chore: add flat fee run db tables - #4349

Merged
turip merged 2 commits into
mainfrom
chore/add-flat-fee-run-db-tables
May 12, 2026
Merged

turip merged 2 commits into
mainfrom
chore/add-flat-fee-run-db-tables

Conversation

@turip

@turip turip commented May 12, 2026 •

Copy link
Copy Markdown
Member

Overview

This patch introduces flat-fee runs. This is needed due to credit notes/pro-rating support, which requires to store different versions of the flat fee (one current, and all the old pending pro-rating/creditnote ones).

This patch only migrates credit_only data, as credit_then_invoice is not yet operational for flat fee.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Introduced realization runs for flat‑fee charges to scope billing records, payments, invoiced usage, credits, and detailed lines per run.
    • Added RealizationRunType enumeration for run state classification.
    • Mapped charge realizations to the current run so UI and exports reflect run-scoped payments, credits, usage, and detailed lines.
  • Bug Fixes / Data Integrity

    • Ensured allocations, payments, usage, and detailed lines are persisted and queried against the active run to prevent cross-run mixing.

Review Change Stack

@turip
turip requested a review from a team as a code owner May 12, 2026 04:56
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

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: cade9d1d-0e3b-4dff-abb4-b362fb3eff37

📥 Commits

Reviewing files that changed from the base of the PR and between 4b63e01 and ad47bbb.

⛔ Files ignored due to path filters (33)
  • openmeter/ent/db/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations/chargeflatfeeruncreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_query.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/chargeflatfeerundetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage/chargeflatfeeruninvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (6)
  • openmeter/billing/charges/flatfee/adapter/credits.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/ent/schema/chargesflatfee.go
  • tools/migrate/flatfee_runs_test.go
  • tools/migrate/migrations/20260511201803_flatfee_runs.down.sql
  • tools/migrate/migrations/20260511201803_flatfee_runs.up.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/flatfee/adapter/credits.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go

📝 Walkthrough

Walkthrough

This PR moves flat-fee realization persistence from charge-scoped tables to run-scoped tables, adds RealizationRunType and adapter methods for creating/fetching/updating a charge's current realization run, updates all adapters (credits, payments, invoiced usage, detailed lines) to persist to run-scoped entities, and maps realizations from the current run.

Changes

Flat-Fee Run-Scoped Realization Refactor

Layer / File(s) Summary
RealizationRunType: Type definition and validation
openmeter/billing/charges/flatfee/realizationrun.go
Adds RealizationRunType, two constants, and Values(), Validate(), IsVoidedBillingHistory() methods.
Run lifecycle adapter methods
openmeter/billing/charges/flatfee/adapter/realizationrun.go
Implements creating the current run for a charge, fetching the current run by charge ID, updating run totals, and queryCurrentRunByChargeID helper.
Charge creation and realization eager-loading
openmeter/billing/charges/flatfee/adapter/charge.go
CreateCharges now creates a current run per new charge (empty totals) and expands realizations under WithCurrentRun.
Run-scoped detailed lines (fetch/upsert) and tests
openmeter/billing/charges/flatfee/adapter/detailedline.go, .../detailedline_test.go
Fetch/Upsert operate on ChargeFlatFeeRunDetailedLine (filtering by Namespace+RunID), buildDetailedLineCreate accepts runID, upsert uses conflict key (Namespace, RunID, ChildUniqueReferenceID), and tests updated to assert run-scoped rows.
Run-scoped payments persistence
openmeter/billing/charges/flatfee/adapter/payment.go
CreatePayment/UpdatePayment now persist/update ChargeFlatFeeRunPayment records tied to the current run.
Run-scoped invoiced usage persistence
openmeter/billing/charges/flatfee/adapter/usage.go
CreateInvoicedUsage fetches current run, updates run totals, and creates ChargeFlatFeeRunInvoicedUsage with RunID.
Run-scoped credit allocations and totals update
openmeter/billing/charges/flatfee/adapter/credits.go
CreateCreditAllocations creates ChargeFlatFeeRunCreditAllocations, calls updateCreditOnlyRunTotals to adjust run totals for credit-only settlements, and maps from run-scoped entities.
Realization mapping from current run
openmeter/billing/charges/flatfee/adapter/mapper.go
MapChargeFlatFeeFromDB loads CurrentRun and delegates population of realizations to mapRealizationsFromCurrentRun, which maps credits, invoiced usage, payment, and optionally detailed lines into the model.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

release-note/feature, area/billing

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 'chore: add flat fee run db tables' directly aligns with the core change of introducing flat-fee run database entities and related adapter logic to support credit notes and pro-rating workflows.
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/add-flat-fee-run-db-tables

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.

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

🧹 Nitpick comments (2)
openmeter/billing/charges/flatfee/adapter/charge.go (1)

140-144: 🏗️ Heavy lift

Batch current-run initialization to reduce bulk-create DB overhead.

Nice migration step overall. The new loop does per-charge run insert + charge update, which adds a lot of round-trips for larger batches. Consider a set-based/bulk approach for run creation + current-run linkage so this path stays fast under load.

As per coding guidelines, "Performance should be a priority... database operations... should be vetted for potential performance bottlenecks."

🤖 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/charge.go` around lines 140 - 144,
The loop doing per-entity inserts via tx.createCurrentRun(ctx, entity,
totals.Totals{}) causes many DB round-trips; instead build all run records
in-memory for the incoming entities, perform a single bulk insert (e.g.
implement tx.createCurrentRunsBulk(ctx, runs) or use the DB driver's bulk insert
mechanism) to get back all created run IDs, then perform a single bulk update to
set each charge's current_run_id (e.g. one UPDATE with WHERE id IN (...) or a
CASE mapping) within the same transaction; replace the per-entity calls in the
current function with the bulk insert + bulk update sequence and ensure
transactional integrity and returned errors are handled the same way.
openmeter/billing/charges/flatfee/adapter/detailedline.go (1)

145-169: 💤 Low value

Tiny cleanup opportunity: chargeID is only used for its Namespace.

Now that RunID carries the run linkage, buildDetailedLineCreate only pulls Namespace out of chargeID. Passing the full meta.ChargeID is a bit misleading — a namespace string, runID string signature would more accurately reflect what the helper actually needs. Totally optional, just a readability nudge.

♻️ Suggested signature tweak
-func buildDetailedLineCreate(db *entdb.Client, chargeID meta.ChargeID, runID string, line flatfee.DetailedLine) (*entdb.ChargeFlatFeeRunDetailedLineCreate, error) {
+func buildDetailedLineCreate(db *entdb.Client, namespace string, runID string, line flatfee.DetailedLine) (*entdb.ChargeFlatFeeRunDetailedLineCreate, error) {
 	if line.ID == "" {
 		line.ID = ulid.Make().String()
 	}
 
 	create := db.ChargeFlatFeeRunDetailedLine.Create().
 		SetID(line.ID).
-		SetNamespace(chargeID.Namespace).
+		SetNamespace(namespace).
 		SetRunID(runID).
 		SetPricerReferenceID(line.ChildUniqueReferenceID)
🤖 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 145 -
169, buildDetailedLineCreate currently accepts a meta.ChargeID but only uses its
Namespace; change the signature of buildDetailedLineCreate to accept namespace
string (and runID string) instead of chargeID to make intent clearer, update all
call sites that invoke buildDetailedLineCreate to pass charge.Namespace where
they previously passed a meta.ChargeID, and ensure the body replaces uses of
chargeID.Namespace with the new namespace parameter (preserving behavior for
SetNamespace). Keep the function name, internals like stddetailedline.Create and
the handling of CreditsApplied and TaxConfig unchanged.
🤖 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.

Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 140-144: The loop doing per-entity inserts via
tx.createCurrentRun(ctx, entity, totals.Totals{}) causes many DB round-trips;
instead build all run records in-memory for the incoming entities, perform a
single bulk insert (e.g. implement tx.createCurrentRunsBulk(ctx, runs) or use
the DB driver's bulk insert mechanism) to get back all created run IDs, then
perform a single bulk update to set each charge's current_run_id (e.g. one
UPDATE with WHERE id IN (...) or a CASE mapping) within the same transaction;
replace the per-entity calls in the current function with the bulk insert + bulk
update sequence and ensure transactional integrity and returned errors are
handled the same way.

In `@openmeter/billing/charges/flatfee/adapter/detailedline.go`:
- Around line 145-169: buildDetailedLineCreate currently accepts a meta.ChargeID
but only uses its Namespace; change the signature of buildDetailedLineCreate to
accept namespace string (and runID string) instead of chargeID to make intent
clearer, update all call sites that invoke buildDetailedLineCreate to pass
charge.Namespace where they previously passed a meta.ChargeID, and ensure the
body replaces uses of chargeID.Namespace with the new namespace parameter
(preserving behavior for SetNamespace). Keep the function name, internals like
stddetailedline.Create and the handling of CreditsApplied and TaxConfig
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f5ba59fc-e76a-4b05-819c-c3dad8b635c4

📥 Commits

Reviewing files that changed from the base of the PR and between de21763 and 4b63e01.

⛔ Files ignored due to path filters (80)
  • openmeter/ent/db/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoiceline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/chargeflatfee.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfee_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeecreditallocations_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeedetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeinvoicedusage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeepayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun/chargeflatfeerun.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerun_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations/chargeflatfeeruncreditallocations.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruncreditallocations_update.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/chargeflatfeerundetailedline/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerundetailedline_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage/chargeflatfeeruninvoicedusage.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeeruninvoicedusage_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/chargeflatfeerunpayment.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/chargeflatfeerunpayment_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/cursor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/entmixinaccessor.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode/taxcode.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/taxcode_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
📒 Files selected for processing (12)
  • openmeter/billing/charges/flatfee/adapter/charge.go
  • openmeter/billing/charges/flatfee/adapter/credits.go
  • openmeter/billing/charges/flatfee/adapter/detailedline.go
  • openmeter/billing/charges/flatfee/adapter/detailedline_test.go
  • openmeter/billing/charges/flatfee/adapter/mapper.go
  • openmeter/billing/charges/flatfee/adapter/payment.go
  • openmeter/billing/charges/flatfee/adapter/realizationrun.go
  • openmeter/billing/charges/flatfee/adapter/usage.go
  • openmeter/billing/charges/flatfee/realizationrun.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/schema/chargesflatfee.go
  • openmeter/ent/schema/taxcode.go

@turip turip added the kind/refactor Code refactor, cleanup or minor improvement label May 12, 2026
@turip
turip merged commit 5e858a7 into main May 12, 2026
27 checks passed
@turip
turip deleted the chore/add-flat-fee-run-db-tables branch May 12, 2026 11:34

This branch was previously deployed

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

Labels

kind/refactor Code refactor, cleanup or minor improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants