Skip to content

refactor: split detailed line type - #3514

Merged
turip merged 3 commits into
mainfrom
refactor/split-detailed-line-type
Oct 17, 2025
Merged

turip merged 3 commits into
mainfrom
refactor/split-detailed-line-type

Conversation

@turip

@turip turip commented Oct 15, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch splits the invoice line and the detailed line into seperate types. The change is only affecting the go types, the adapter still uses the old representation.

This approach allows to only include those fields in the detailed lines that are actually required.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Added validation for payment terms and richer, validated detailed invoice lines.
    • Enhanced discount handling with structured amount-discount management and ID reuse.
  • Refactors

    • Reorganized invoice line model to a detailed-line hierarchy and simplified line-type/status semantics.
    • Consolidated discount flows and streamlined invoice line processing to improve consistency.

@coderabbitai

coderabbitai Bot commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors invoice line model to use hierarchical DetailedLine structures, removes union-type line enums, moves discounts to per-detailed-line AmountDiscounts, and updates adapters, services, HTTP mappings, Stripe integration, worker logic, and tests to the new DetailedLine-based model.

Changes

Cohort / File(s) Summary
Core data model
openmeter/billing/invoiceline.go, openmeter/billing/invoicedetailedline.go, openmeter/billing/invoicelinetypes.go
Introduces DetailedLineBase/DetailedLine/DetailedLines; replaces Line.Children with Line.DetailedLines; removes union-type machinery from invoiceline; adds deprecated InvoiceLineType/InvoiceLineStatus in new file.
Adapter layer
openmeter/billing/adapter/invoicelinediff.go, openmeter/billing/adapter/invoicelinediff_test.go, openmeter/billing/adapter/invoicelinemapper.go, openmeter/billing/adapter/invoicelines.go
Converts diffs/mapping/upserts to operate on billing.DetailedLine; switches discounts from Discounts.Amount → AmountDiscounts; adds mapInvoiceDetailedLineFromDB; introduces upsertDetailedLineAmountDiscounts and related diff type changes.
Discount model
openmeter/billing/invoicelinediscount.go
Adds Validate for amount-managed discounts; changes ReuseIDsFrom signatures to return direct slice types (removes error returns) and simplifies generic reuse logic.
Service — invoice & app
openmeter/billing/invoice.go, openmeter/billing/app.go
Replaces FlattenLinesByID; getLeafLines and related functions now return DetailedLines; app.go merges external IDs across DetailedLines and AmountDiscounts and reports unmatched IDs; removes strict Status filters.
Service — detailed-line handling
openmeter/billing/service/lineservice/detailedlines.go, openmeter/billing/service/invoicecalc/*, openmeter/billing/service/invoice.go
newDetailedLines/merge/calculate totals updated to build and return billing.DetailedLines; totals calculations adapted to AmountDiscounts and DetailedLineBase fields (ServicePeriod, Quantity, PerUnitAmount).
Service — line types & base
openmeter/billing/service/lineservice/service.go, openmeter/billing/service/lineservice/linebase.go, openmeter/billing/service/lineservice/discountpercentage.go
Removes flat-fee feeline implementation; eliminates PreventChildChanges and Status() from LineBase API; simplifies FromEntity branching and appends discounts to AmountDiscounts.
HTTP / API layer
openmeter/billing/httpdriver/invoiceline.go
Maps DetailedLines via mapDetailedLineToAPI(..., invoiceAt); splits discount mapping into amount/usage mappers; removes flat-fee creation prohibition and adapts field mappings to DetailedLine schema.
Stripe integration
openmeter/app/stripe/entity/app/invoice.go
Migrates functions and params to accept billing.DetailedLine; uses line.ServicePeriod, line.Quantity, line.PerUnitAmount and line.AmountDiscounts for building Stripe invoice item params.
Worker / subscription
openmeter/billing/worker/subscription/*.go
Removes type/status initializations and guards (lineFromSubscritionRateCard, feehelper, invoiceupdate, handlers); selection filters drop Status==Valid requirement; quantity recalcs and updates no longer restricted to usage-based type.
Tests — adapter / billing / invoice
test/billing/*, openmeter/billing/*_test.go, test/app/stripe/invoice_test.go
Update test fixtures and assertions: replace Children → DetailedLines; Discounts → AmountDiscounts; remove Type assignments; adjust helper functions and expectations to new DetailedLine model across many test files.
Utility & misc
pkg/slicesx/slice.go, openmeter/productcatalog/price.go, openmeter/app/stripe/...
Adds SliceToPtrSlice helper; adds PaymentTermType.Validate(); multiple Stripe and other callsites updated to DetailedLine-based parameters.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Rationale: Large, cross-cutting refactor touching data model, adapters, services, HTTP layer, worker logic, Stripe integration, and extensive tests. Changes are heterogeneous (new types, signature changes, mapping logic, validation) and require coordinated review across domains.

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "refactor: split detailed line type" accurately describes the primary structural change throughout the changeset. The PR's core objective is to refactor the Go type system by creating a new DetailedLine type separate from the Line type, which is evident from the introduction of DetailedLineBase and DetailedLine types in the new invoicedetailedline.go file and the systematic replacement of LineChildren with DetailedLines across dozens of files. The title is concise, uses clear language ("split"), and is specific enough that a teammate scanning the history would understand this is a type hierarchy refactoring for invoice lines. While the changeset touches many files and involves related changes like removing union types and consolidating fields, the title effectively captures the main architectural intent.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/split-detailed-line-type

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 refactor/split-detailed-line-type branch from ab447c2 to 67d7a47 Compare October 15, 2025 12:52
Base automatically changed from refactory/entitydiff to main October 15, 2025 13:27
@turip
turip force-pushed the refactor/split-detailed-line-type branch 2 times, most recently from 1c3d751 to d6a595d Compare October 15, 2025 14:45
@turip
turip force-pushed the refactor/split-detailed-line-type branch from d6a595d to bf9585e Compare October 16, 2025 12:46
@turip
turip changed the base branch from main to cleanup/remove-recursive-line-lookups October 16, 2025 12:47
Base automatically changed from cleanup/remove-recursive-line-lookups to main October 16, 2025 13:08
@turip
turip force-pushed the refactor/split-detailed-line-type branch from bf9585e to 1f8d86f Compare October 16, 2025 15:16
@turip
turip force-pushed the refactor/split-detailed-line-type branch 3 times, most recently from cc775f8 to 38edc57 Compare October 17, 2025 07:47
@turip
turip force-pushed the refactor/split-detailed-line-type branch from 38edc57 to dfcf3f6 Compare October 17, 2025 10:03
@turip turip added release-note/misc Miscellaneous changes kind/refactor Code refactor, cleanup or minor improvement area/billing labels Oct 17, 2025
@turip
turip marked this pull request as ready for review October 17, 2025 11:12
@turip
turip requested a review from a team as a code owner October 17, 2025 11:12
@turip
turip requested a review from chrisgacsal October 17, 2025 11:12

@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: 12

Caution

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

⚠️ Outside diff range comments (10)
openmeter/billing/service/lineservice/usagebasedline_test.go (1)

163-185: Duplicate subtest names (“no overage”).

Two subtests use the same name; rename for clarity (e.g., “no overage” and “no overage (currency rounding)”) to ease failure triage.

openmeter/billing/worker/subscription/invoiceupdate.go (1)

195-208: Recalculate quantity only for usage‑based lines.
Calling SnapshotLineQuantity for non‑UBP lines can fail unnecessarily.

Apply:

-				if invoice.Status != billing.InvoiceStatusGathering {
+				if invoice.Status != billing.InvoiceStatusGathering && targetState.UsageBased != nil {
 					// We need to update the quantities of the usage based lines, to compensate for any changes in the period
 					// of the line
test/app/stripe/invoice_test.go (2)

523-536: Fix pointer-to-range-var gotcha in getLine (return pointer to slice elem).

Returning &line from a range variable yields a pointer to the loop var, not the backing slice element. Return &lines[i] instead.

-        getLine := func(description string) *billing.DetailedLine {
-            for _, line := range invoice.GetLeafLinesWithConsolidatedTaxBehavior() {
-                name := line.Name
-                if line.Description != nil {
-                    name = fmt.Sprintf("%s (%s)", name, *line.Description)
-                }
-                if name == description {
-                    return &line
-                }
-            }
-            return nil
-        }
+        getLine := func(description string) *billing.DetailedLine {
+            lines := invoice.GetLeafLinesWithConsolidatedTaxBehavior()
+            for i := range lines {
+                name := lines[i].Name
+                if lines[i].Description != nil {
+                    name = fmt.Sprintf("%s (%s)", name, *lines[i].Description)
+                }
+                if name == description {
+                    return &lines[i]
+                }
+            }
+            return nil
+        }

543-563: Harden getDiscountID against non-matching input.

Guard regex match before indexing groups to avoid panics on unexpected descriptions.

-        getDiscountID := func(description string) string {
+        getDiscountID := func(description string) string {
             r, err := regexp.Compile(`^(.+) \((.+)\)$`)
             s.NoError(err)
-            group := r.FindAllStringSubmatch(description, -1)
-            id := ""
-            line := getLine(group[0][1])
+            group := r.FindAllStringSubmatch(description, -1)
+            id := ""
+            if len(group) == 0 || len(group[0]) < 3 {
+                return id
+            }
+            line := getLine(group[0][1])
             if line == nil {
                 return id
             }
             for _, discount := range line.AmountDiscounts {
                 if lo.FromPtr(discount.Description) != "" && group[0][2] == lo.FromPtr(discount.Description) {
                     return discount.GetID()
                 }
             }
             return id
         }
test/billing/adapter_test.go (1)

351-356: Comment contradicts behavior; adjust to 3 lines (deleted children are not returned).

Query intentionally excludes deleted detailed lines. Fix the comment to avoid confusion.

-  // Then we get the 4 lines
+  // Then we get the 3 lines (deleted detailed lines are intentionally excluded)
openmeter/app/stripe/entity/app/invoice.go (2)

353-356: Wrong external ID recorded for discount lines during update.

You’re associating the discount’s ID with the parent line’s external ID. Use the discount Stripe line’s ID.

-        result.AddLineDiscountExternalID(discount.ID, line.ExternalIDs.Invoicing)
+        result.AddLineDiscountExternalID(discount.ID, stripeLine.ID)

438-463: Generic sorter never matches types; descriptions are never compared.

The type switch checks []*stripe.InvoiceAddLinesLineParams / []*stripe.InvoiceUpdateLinesLineParams, but callers pass []*stripe.InvoiceItemParams and []*stripeclient.StripeInvoiceItemWithID. Descriptions remain nil; sort becomes effectively no-op.

-// sortInvoiceLines sorts the lines by description
-func sortInvoiceLines[K StripeInvoiceLineOperationParams](stripeLineAdd []*K) {
-  sort.Slice(stripeLineAdd, func(i, j int) bool {
-    var (
-      descA *string
-      descB *string
-    )
-    // Go generics can't handle two structs with common fields
-    // We need to switch on the type
-    switch params := any(stripeLineAdd).(type) {
-    case []*stripe.InvoiceAddLinesLineParams:
-      descA = params[i].Description
-      descB = params[j].Description
-    case []*stripe.InvoiceUpdateLinesLineParams:
-      descA = params[i].Description
-      descB = params[j].Description
-    }
-    a := lo.FromPtr(descA)
-    b := lo.FromPtr(descB)
-    return a < b
-  })
-}
+// Deterministic ordering by description (adds)
+func sortInvoiceItemParams(items []*stripe.InvoiceItemParams) {
+  sort.Slice(items, func(i, j int) bool {
+    return lo.FromPtr(items[i].Description) < lo.FromPtr(items[j].Description)
+  })
+}
+
+// Deterministic ordering by description (updates)
+func sortInvoiceItemsWithID(items []*stripeclient.StripeInvoiceItemWithID) {
+  sort.Slice(items, func(i, j int) bool {
+    // The description lives on the embedded InvoiceItemParams
+    var ai, aj *string
+    if items[i] != nil && items[i].InvoiceItemParams != nil {
+      ai = items[i].InvoiceItemParams.Description
+    }
+    if items[j] != nil && items[j].InvoiceItemParams != nil {
+      aj = items[j].InvoiceItemParams.Description
+    }
+    return lo.FromPtr(ai) < lo.FromPtr(aj)
+  })
+}

And update call sites:

-  sortInvoiceLines(stripeLineAdd)
+  sortInvoiceItemParams(stripeLineAdd)
-  sortInvoiceLines(stripeLineAdd)
+  sortInvoiceItemParams(stripeLineAdd)
-  sortInvoiceLines(stripeLinesUpdate)
+  sortInvoiceItemsWithID(stripeLinesUpdate)

Also applies to: 236-236, 387-389, 407-407

openmeter/billing/adapter/invoicelines.go (1)

257-266: Detailed lines’ UpdatedAt not bumped when only discounts change.

You track DetailedLineAffectedLineIDs in diffs but don’t update them here, so discount-only edits won’t reflect on the child line’s UpdatedAt.

   if !lineDiffs.AffectedLineIDs.IsEmpty() {
     err := tx.db.BillingInvoiceLine.Update().
       SetUpdatedAt(clock.Now().In(time.UTC)).
       Where(billinginvoiceline.IDIn(lineDiffs.AffectedLineIDs.AsSlice()...)).
       Exec(ctx)
     if err != nil {
       return nil, fmt.Errorf("updating updated_at for lines: %w", err)
     }
   }
+  if !lineDiffs.DetailedLineAffectedLineIDs.IsEmpty() {
+    err := tx.db.BillingInvoiceLine.Update().
+      SetUpdatedAt(clock.Now().In(time.UTC)).
+      Where(billinginvoiceline.IDIn(lineDiffs.DetailedLineAffectedLineIDs.AsSlice()...)).
+      Exec(ctx)
+    if err != nil {
+      return nil, fmt.Errorf("updating updated_at for detailed lines: %w", err)
+    }
+  }
openmeter/billing/adapter/invoicelinemapper.go (1)

100-104: Return nil line on error to avoid accidental use of partial state.

On non-usage-based top-level line, return nil for the line pointer.

- if dbLine.Type != billing.InvoiceLineTypeUsageBased {
-   return invoiceLine, fmt.Errorf("only usage based lines can be top level lines [line_id=%s]", dbLine.ID)
- }
+ if dbLine.Type != billing.InvoiceLineTypeUsageBased {
+   return nil, fmt.Errorf("only usage based lines can be top level lines [line_id=%s]", dbLine.ID)
+ }
openmeter/billing/invoice.go (1)

421-431: Ensure return value is DetailedLines after Map.

lo.Map returns []DetailedLine; cast to DetailedLines to preserve type.

-func (i *Invoice) GetLeafLinesWithConsolidatedTaxBehavior() DetailedLines {
+func (i *Invoice) GetLeafLinesWithConsolidatedTaxBehavior() DetailedLines {
   leafLines := i.getLeafLines()
   if i.Workflow.Config.Invoicing.DefaultTaxConfig == nil {
     return leafLines
   }
-  return lo.Map(leafLines, func(line DetailedLine, _ int) DetailedLine {
+  return DetailedLines(lo.Map(leafLines, func(line DetailedLine, _ int) DetailedLine {
     line.TaxConfig = productcatalog.MergeTaxConfigs(i.Workflow.Config.Invoicing.DefaultTaxConfig, line.TaxConfig)
     return line
-  })
+  }))
 }
🧹 Nitpick comments (24)
pkg/slicesx/slice.go (1)

5-9: Consider a simpler implementation without external dependencies.

The current implementation uses lo.Map for a straightforward transformation. A plain loop would be more idiomatic, easier to understand, and eliminate the dependency on the lo library for this simple operation.

Apply this diff to use a plain loop:

-func SliceToPtrSlice[T any](s []T) []*T {
-	return lo.Map(s, func(_ T, i int) *T {
-		return &s[i]
-	})
+func SliceToPtrSlice[T any](s []T) []*T {
+	result := make([]*T, len(s))
+	for i := range s {
+		result[i] = &s[i]
+	}
+	return result
 }

If keeping lo.Map, you can remove the import:

-import "github.com/samber/lo"
openmeter/billing/invoicelinediscount.go (2)

209-219: Collection-level validation added.

Good aggregation with contextual IDs. Consider using models.NewNillableGenericValidationError for consistency with other validators, but current errors.Join(nil) → nil is fine.


431-473: Add uniqueness validation in adapter layer for ChildUniqueReferenceID per parent item.

The ReuseIDsFrom function groups items by ChildUniqueReferenceID and selects the first match without checking for duplicates. While the current design assumes one item per reference (as evidenced by the map-based matching pattern in invoiceline.go lines 520–541), if duplicates can arise from adapter or DB layer bugs, the selection becomes nondeterministic. Consider adding an assertion or validation in the adapter/DB layer to enforce this uniqueness constraint earlier, making the assumption explicit rather than implicit.

openmeter/billing/invoicelinetypes.go (1)

3-11: Apply Go's standard deprecation format to enable staticcheck SA1019 tooling.

Replace "TODO: Deprecated" with proper doc comments on both InvoiceLineType and InvoiceLineStatus:

-// TODO: Deprecated: remove in the next PR
+// Deprecated: kept for backward compatibility. Will be removed in the next PR.
 type InvoiceLineType string
-// TODO: Deprecated: remove in the next PR
+// Deprecated: kept for backward compatibility. Will be removed in the next PR.
 type InvoiceLineStatus string

Both types are actively used throughout the codebase (in generated Ent code, adapter logic, and API schemas), so this comment-only change is safe. Once applied, staticcheck SA1019 will flag any new uses of these types, helping enforce the deprecation period.

openmeter/billing/worker/subscription/feehelper.go (1)

17-21: Rename isFlatFee to isUBPFlatFee to clarify intent and prevent future confusion.

All 5 call sites confirm the predicate is used exclusively within UBP contexts:

  • sync.go:787, 911: Guard !isFlatFee to skip empty UBP lines for deletion
  • sync.go:802–803: Handle flat fee prorating and validate fee-type consistency
  • invoiceupdate.go:273: Validate immutable flat fee line constraints

The implementation exclusively checks line.UsageBased field, confirming the guard applies only to flat fees within the usage-based pricing model, not flat fees in general. Renaming improves clarity and safeguards against accidental misuse as the codebase evolves.

openmeter/billing/app.go (1)

234-269: Typo in variable name; minor cleanup.
Rename dicountIDToExternalID → discountIDToExternalID for clarity; no behavior change.

-	dicountIDToExternalID := r.GetLineDiscountExternalIDs()
+	discountIDToExternalID := r.GetLineDiscountExternalIDs()
 ...
-	foundIDs := line.SetDiscountExternalIDs(dicountIDToExternalID)
+	foundIDs := line.SetDiscountExternalIDs(discountIDToExternalID)
 ...
-	for idx, detailedLine := range line.DetailedLines {
+	for idx, detailedLine := range line.DetailedLines {
 		if externalID, ok := lineIDToExternalID[detailedLine.ID]; ok {
 			line.DetailedLines[idx].ExternalIDs.Invoicing = externalID
 			delete(lineIDToExternalID, detailedLine.ID)
 		}
 
-		foundIDs := line.DetailedLines[idx].SetDiscountExternalIDs(dicountIDToExternalID)
+		foundIDs := line.DetailedLines[idx].SetDiscountExternalIDs(discountIDToExternalID)
 		for _, id := range foundIDs {
-			delete(dicountIDToExternalID, id)
+			delete(discountIDToExternalID, id)
 		}
 	}
 ...
-	if len(dicountIDToExternalID) > 0 {
-		outErr = errors.Join(outErr, fmt.Errorf("some line discounts were not found in the invoice: ids=[%s]", strings.Join(lo.Keys(dicountIDToExternalID), ", ")))
+	if len(discountIDToExternalID) > 0 {
+		outErr = errors.Join(outErr, fmt.Errorf("some line discounts were not found in the invoice: ids=[%s]", strings.Join(lo.Keys(discountIDToExternalID), ", ")))
 	}
openmeter/billing/service/lineservice/pricedynamic_test.go (1)

188-199: Prefer exact integers and make rounding explicit in discount stub.

Use NewFromInt for whole-number amounts and set RoundingAmount to 0 to avoid float-init drift and make expectations explicit.

-                    AmountDiscounts: []billing.AmountLineDiscountManaged{
+                    AmountDiscounts: []billing.AmountLineDiscountManaged{
                         {
                             AmountLineDiscount: billing.AmountLineDiscount{
-                                Amount: alpacadecimal.NewFromFloat(60),
+                                Amount:         alpacadecimal.NewFromInt(60),
+                                RoundingAmount: alpacadecimal.NewFromInt(0),
                                 LineDiscountBase: billing.LineDiscountBase{
                                     Description:            lo.ToPtr("Maximum spend discount for charges over 100"),
                                     ChildUniqueReferenceID: lo.ToPtr(billing.LineMaximumSpendReferenceID),
                                     Reason:                 billing.NewDiscountReasonFrom(billing.MaximumSpendDiscount{}),
                                 },
                             },
                         },
                     },
                 },
openmeter/billing/adapter/invoicelinediff_test.go (2)

376-387: Use NewFromInt for constant discount amounts.

Discount amounts are integers in tests; initialize them exactly to avoid float parsing noise.

-            AmountLineDiscount: billing.AmountLineDiscount{
-                Amount: alpacadecimal.NewFromFloat(10),
-            },
+            AmountLineDiscount: billing.AmountLineDiscount{
+                Amount: alpacadecimal.NewFromInt(10),
+            },

389-396: Avoid returning pointer to slice element; return index or copy.

Returning &slice[i] is easy to misuse if the slice is later reallocated. Safer: return index and use it immediately, or return a copy.

Option A (index-based, minimal churn):

-func getDetailedLineByID(l *billing.Line, id string) *billing.DetailedLine {
-    for idx := range l.DetailedLines {
-        if l.DetailedLines[idx].ID == id {
-            return &l.DetailedLines[idx]
-        }
-    }
-    return nil
-}
+func getDetailedLineIndexByID(l *billing.Line, id string) int {
+    for i := range l.DetailedLines {
+        if l.DetailedLines[i].ID == id {
+            return i
+        }
+    }
+    return -1
+}

And adapt remover:

-func removeDetailedLineByID(l *billing.Line, id string) bool {
-    toBeRemoved := getDetailedLineByID(l, id)
-    if toBeRemoved == nil {
-        return false
-    }
-    l.DetailedLines = lo.Filter(l.DetailedLines, func(dl billing.DetailedLine, _ int) bool {
-        return dl.ID != id
-    })
-    return true
-}
+func removeDetailedLineByID(l *billing.Line, id string) bool {
+    idx := getDetailedLineIndexByID(l, id)
+    if idx < 0 {
+        return false
+    }
+    l.DetailedLines = append(l.DetailedLines[:idx], l.DetailedLines[idx+1:]...)
+    return true
+}

Also applies to: 398-408

test/billing/ubpflatfee_test.go (1)

113-120: LGTM on DetailedLines migration; consider strengthening assertions.

Current checks validate quantity/amount/payment term and discount totals. Add a brief assert on discount Reason and Description to cover mapping end-to-end.

Example:

s.Equal(billing.MaximumSpendDiscountReason, detailedLine.AmountDiscounts[0].Reason.GetType())
s.NotEmpty(lo.FromPtr(detailedLine.AmountDiscounts[0].Description))

Also applies to: 193-195, 198-201

test/app/stripe/invoice_test.go (1)

509-521: Optional: cache detailedLine→parent to speed up parent lookups.

getParentOfDetailedLine scans all parents each time. Build a map[id]parent once if used repeatedly.

test/billing/tax_test.go (1)

268-305: Avoid package name shadowing in helper param.

Parameter name customer shadows the imported package customer, reducing clarity. Rename param to cust.

-func (s *InvoicingTaxTestSuite) generateDraftInvoice(ctx context.Context, customer *customer.Customer) billing.Invoice {
+func (s *InvoicingTaxTestSuite) generateDraftInvoice(ctx context.Context, cust *customer.Customer) billing.Invoice {
-    res, err := s.BillingService.CreatePendingInvoiceLines(ctx,
+    res, err := s.BillingService.CreatePendingInvoiceLines(ctx,
         billing.CreatePendingInvoiceLinesInput{
-            Customer: customer.GetID(),
+            Customer: cust.GetID(),
...
-    invoices, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{
-        Customer: customer.GetID(),
+    invoices, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{
+        Customer: cust.GetID(),
openmeter/billing/worker/subscription/sync_test.go (1)

3492-3496: DRY up FeeLineConfigID normalization in comparisons.

The same lo.Map normalization is duplicated for expected and actual. Extract a small helper to reduce repetition and future drift.

-expectedInvoice := draftInvoice.Clone()
-expectedInvoice.Lines = expectedInvoice.Lines.Map(func(line *billing.Line) *billing.Line {
-    if line.ChildUniqueReferenceID != nil && *line.ChildUniqueReferenceID == draftLineReferenceID {
-        line.Annotations = models.Annotations{
-            billing.AnnotationSubscriptionSyncIgnore:               true,
-            billing.AnnotationSubscriptionSyncForceContinuousLines: true,
-        }
-    }
-    line.DetailedLines = lo.Map(line.DetailedLines, func(child billing.DetailedLine, _ int) billing.DetailedLine {
-        child.FeeLineConfigID = ""
-        return child
-    })
-    return line
-})
+expectedInvoice := draftInvoice.Clone()
+normalize := func(l *billing.Line) *billing.Line {
+    if l.ChildUniqueReferenceID != nil && *l.ChildUniqueReferenceID == draftLineReferenceID {
+        l.Annotations = models.Annotations{
+            billing.AnnotationSubscriptionSyncIgnore:               true,
+            billing.AnnotationSubscriptionSyncForceContinuousLines: true,
+        }
+    }
+    l.DetailedLines = lo.Map(l.DetailedLines, func(child billing.DetailedLine, _ int) billing.DetailedLine {
+        child.FeeLineConfigID = ""
+        return child
+    })
+    return l
+}
+expectedInvoice.Lines = expectedInvoice.Lines.Map(normalize)
 
-draftInvoiceAfterSync.Lines = draftInvoiceAfterSync.Lines.Map(func(line *billing.Line) *billing.Line {
-    line.DetailedLines = lo.Map(line.DetailedLines, func(child billing.DetailedLine, _ int) billing.DetailedLine {
-        child.FeeLineConfigID = ""
-        return child
-    })
-    return line
-})
+draftInvoiceAfterSync.Lines = draftInvoiceAfterSync.Lines.Map(normalize)

If preferred, place normalize as a file-level helper to reuse in other tests.

Also applies to: 3501-3506

test/billing/adapter_test.go (1)

359-363: Guard against nil ChildUniqueReferenceID in helper.

If this helper leaks into broader reuse, a nil ChildUniqueReferenceID will panic. Safe guard is trivial.

-func getUniqReferenceNames(lines []billing.DetailedLine) []string {
-  return lo.Map(lines, func(l billing.DetailedLine, _ int) string {
-    return *l.ChildUniqueReferenceID
-  })
-}
+func getUniqReferenceNames(lines []billing.DetailedLine) []string {
+  return lo.Map(lines, func(l billing.DetailedLine, _ int) string {
+    return lo.FromPtr(l.ChildUniqueReferenceID)
+  })
+}
openmeter/billing/service/lineservice/priceunit_test.go (1)

188-200: Minor: use the managed slice alias for consistency.

Prefer billing.AmountLineDiscountsManaged to mirror production type names and other tests.

- AmountDiscounts: []billing.AmountLineDiscountManaged{
+ AmountDiscounts: billing.AmountLineDiscountsManaged{

Also applies to: 247-268

openmeter/billing/adapter/invoicelinediff.go (1)

105-111: Error message refers to obsolete 'flat fee'.

Clarify message to match DetailedLine context.

- if detailedLine.ExpectedState == nil {
-   return fmt.Errorf("detailed line expected state is nil or flat fee is nil")
- }
+ if detailedLine.ExpectedState == nil {
+   return fmt.Errorf("detailed line expected state is nil")
+ }
- if detailedLine.PersistedState == nil {
-   return fmt.Errorf("detailed line db state is nil or flat fee is nil")
- }
+ if detailedLine.PersistedState == nil {
+   return fmt.Errorf("detailed line db state is nil")
+ }
openmeter/billing/invoice_test.go (1)

13-66: Stabilize time usage in sort test to avoid flakiness.

Use a fixed base time (or the project clock helper) instead of time.Now() to ensure deterministic ordering across TZ/slow test runners.

- Start: time.Now().Add(time.Hour * 24),
+ Start: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC).Add(24 * time.Hour),
...
- Start: time.Now(),
+ Start: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC),
openmeter/billing/adapter/invoicelinemapper.go (1)

27-31: Improve error context when mapping detailed lines.

ParentLineID on the parent is nil; message shows empty parentID. Log the parent line ID instead.

- return nil, fmt.Errorf("mapping detailed lines [parentID=%s,id=%s]: %w", lo.FromPtr(dbLine.ParentLineID), dbLine.ID, err)
+ return nil, fmt.Errorf("mapping detailed lines for line [line_id=%s]: %w", dbLine.ID, err)
test/billing/invoice_test.go (1)

2375-2413: Avoid potential nil deref in GroupBy on ChildUniqueReferenceID.

If any detailed line lacks ChildUniqueReferenceID, deref will panic. Use a safe fallback key.

- detailsById := lo.GroupBy(detailedLines, func(l billing.DetailedLine) string {
-   return *l.ChildUniqueReferenceID
- })
+ detailsById := lo.GroupBy(detailedLines, func(l billing.DetailedLine) string {
+   return lo.FromPtrOr(l.ChildUniqueReferenceID, "")
+ })
openmeter/billing/invoice.go (1)

535-540: Doc/code mismatch in NonDeletedLineCount.

Comment says “not deleted and have a valid status,” but code only checks DeletedAt. Either restore the status filter or update the comment.

-// NonDeletedLineCount returns the number of lines that are not deleted and have a valid status (e.g. we are ignoring split lines)
+// NonDeletedLineCount returns the number of lines that are not deleted.
openmeter/billing/invoicedetailedline.go (2)

107-116: Clone should deep‑copy pointer fields (Index, ChildUniqueReferenceID).

Current Clone only copies TaxConfig; pointer fields may alias and be mutated elsewhere.

 func (l DetailedLineBase) Clone() DetailedLineBase {
-	if l.TaxConfig != nil {
-		taxConfig := *l.TaxConfig
-		l.TaxConfig = &taxConfig
-	}
+	if l.TaxConfig != nil {
+		tc := *l.TaxConfig
+		l.TaxConfig = &tc
+	}
+	if l.ChildUniqueReferenceID != nil {
+		id := *l.ChildUniqueReferenceID
+		l.ChildUniqueReferenceID = &id
+	}
+	if l.Index != nil {
+		idx := *l.Index
+		l.Index = &idx
+	}
 
 	return l
 }

117-119: Equality via reflect.DeepEqual on decimals/time may be brittle.

Consider field-wise equality using Decimal.Equal and Period.Equal to avoid representation quirks.

openmeter/billing/service/lineservice/detailedlines.go (2)

108-118: Round discountAmount to currency precision.

discountAmount should be normalized to the currency calculator to avoid precision drift.

-	discountAmount := totalBillableAmount.Sub(normalizedMaxSpend)
-	i.AmountDiscounts = append(i.AmountDiscounts, billing.AmountLineDiscountManaged{
+	discountAmount := totalBillableAmount.Sub(normalizedMaxSpend)
+	discountAmount = in.Currency.RoundToPrecision(discountAmount)
+	i.AmountDiscounts = append(i.AmountDiscounts, billing.AmountLineDiscountManaged{
 		AmountLineDiscount: billing.AmountLineDiscount{
 			Amount: discountAmount,

138-157: Avoid shadowing parameter ‘line’; prefer dl and avoid interior pointer to input field.

  • Shadowing line := … obscures the function arg line and hurts readability.
  • Use lo.ToPtr(in.ChildUniqueReferenceID) for consistency and to avoid interior-pointer style.
-		line := billing.DetailedLine{
+		dl := billing.DetailedLine{
 			DetailedLineBase: billing.DetailedLineBase{
 				ManagedResource: models.NewManagedResource(models.ManagedResourceInput{
 					Namespace: line.Namespace,
 					Name:      in.Name,
 				}),
 
 				ServicePeriod:          period,
 				InvoiceID:              line.InvoiceID,
 				Currency:               line.Currency,
-				ChildUniqueReferenceID: &in.ChildUniqueReferenceID,
+				ChildUniqueReferenceID: lo.ToPtr(in.ChildUniqueReferenceID),
 				TaxConfig:              line.TaxConfig,
 
 				PaymentTerm:   lo.CoalesceOrEmpty(in.PaymentTerm, productcatalog.InArrearsPaymentTerm),
 				PerUnitAmount: in.PerUnitAmount,
 				Quantity:      in.Quantity,
 				Category:      in.Category,
 			},
-			AmountDiscounts: in.AmountDiscounts,
+			AmountDiscounts: in.AmountDiscounts,
 		}
 
-		if err := line.Validate(); err != nil {
-			return billing.DetailedLine{}, err
-		}
-
-		return line, nil
+		if err := dl.Validate(); err != nil {
+			return billing.DetailedLine{}, err
+		}
+		return dl, nil

Also applies to: 159-164, 148-149

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8b1dee and dfcf3f6.

📒 Files selected for processing (46)
  • openmeter/app/stripe/entity/app/invoice.go (10 hunks)
  • openmeter/billing/adapter/invoicelinediff.go (8 hunks)
  • openmeter/billing/adapter/invoicelinediff_test.go (9 hunks)
  • openmeter/billing/adapter/invoicelinemapper.go (2 hunks)
  • openmeter/billing/adapter/invoicelines.go (7 hunks)
  • openmeter/billing/app.go (2 hunks)
  • openmeter/billing/httpdriver/invoiceline.go (7 hunks)
  • openmeter/billing/invoice.go (5 hunks)
  • openmeter/billing/invoice_test.go (1 hunks)
  • openmeter/billing/invoicedetailedline.go (1 hunks)
  • openmeter/billing/invoiceline.go (12 hunks)
  • openmeter/billing/invoicelinediscount.go (5 hunks)
  • openmeter/billing/invoicelinetypes.go (1 hunks)
  • openmeter/billing/service/invoice.go (2 hunks)
  • openmeter/billing/service/invoicecalc/gatheringrealtime.go (1 hunks)
  • openmeter/billing/service/invoicecalc/period.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (0 hunks)
  • openmeter/billing/service/lineservice/detailedlines.go (7 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (1 hunks)
  • openmeter/billing/service/lineservice/feeline.go (0 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (0 hunks)
  • openmeter/billing/service/lineservice/linebase.go (0 hunks)
  • openmeter/billing/service/lineservice/pricedynamic_test.go (1 hunks)
  • openmeter/billing/service/lineservice/pricegraduatedtiered_test.go (2 hunks)
  • openmeter/billing/service/lineservice/pricepackage_test.go (1 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (2 hunks)
  • openmeter/billing/service/lineservice/pricevolumetiered_test.go (1 hunks)
  • openmeter/billing/service/lineservice/service.go (3 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (4 hunks)
  • openmeter/billing/worker/subscription/feehelper.go (1 hunks)
  • openmeter/billing/worker/subscription/handlers.go (1 hunks)
  • openmeter/billing/worker/subscription/invoiceupdate.go (1 hunks)
  • openmeter/billing/worker/subscription/suitebase_test.go (0 hunks)
  • openmeter/billing/worker/subscription/sync.go (0 hunks)
  • openmeter/billing/worker/subscription/sync_test.go (2 hunks)
  • openmeter/productcatalog/price.go (1 hunks)
  • pkg/slicesx/slice.go (1 hunks)
  • test/app/custominvoicing/invocing_test.go (0 hunks)
  • test/app/stripe/invoice_test.go (3 hunks)
  • test/billing/adapter_test.go (17 hunks)
  • test/billing/collection_test.go (0 hunks)
  • test/billing/discount_test.go (4 hunks)
  • test/billing/invoice_test.go (14 hunks)
  • test/billing/suite.go (1 hunks)
  • test/billing/tax_test.go (4 hunks)
  • test/billing/ubpflatfee_test.go (2 hunks)
💤 Files with no reviewable changes (8)
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/worker/subscription/suitebase_test.go
  • test/app/custominvoicing/invocing_test.go
  • openmeter/billing/worker/subscription/sync.go
  • test/billing/collection_test.go
  • openmeter/billing/service/lineservice/feeline_test.go
  • openmeter/billing/service/lineservice/linebase.go
  • openmeter/billing/service/lineservice/feeline.go
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-21T08:32:31.689Z
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).

Applied to files:

  • openmeter/billing/worker/subscription/feehelper.go
  • test/billing/invoice_test.go
🧬 Code graph analysis (32)
test/billing/suite.go (3)
openmeter/productcatalog/price.go (1)
  • Price (94-101)
openmeter/billing/invoiceline.go (1)
  • Period (53-56)
openmeter/billing/totals.go (1)
  • Totals (9-26)
test/billing/tax_test.go (3)
openmeter/billing/invoicedetailedline.go (1)
  • DetailedLines (166-166)
openmeter/customer/customer.go (1)
  • Customer (18-30)
openmeter/billing/invoice.go (1)
  • Invoice (330-341)
openmeter/billing/service/lineservice/usagebasedline_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
openmeter/billing/adapter/invoicelinediff_test.go (6)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLines (166-166)
  • DetailedLineBase (43-69)
  • DetailedLine (121-126)
pkg/models/model.go (2)
  • ManagedResource (23-31)
  • ManagedModelWithID (179-182)
pkg/clock/clock.go (1)
  • Now (14-21)
pkg/entitydiff/diff.go (1)
  • Entity (11-14)
openmeter/billing/invoiceline.go (1)
  • Line (233-244)
openmeter/billing/invoicelinediscount.go (3)
  • AmountLineDiscountsManaged (157-157)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
test/app/stripe/invoice_test.go (2)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLine (121-126)
  • DetailedLines (166-166)
openmeter/billing/invoiceline.go (2)
  • Line (233-244)
  • Lines (559-559)
openmeter/app/stripe/entity/app/invoice.go (2)
openmeter/billing/invoicedetailedline.go (1)
  • DetailedLine (121-126)
openmeter/billing/invoicelinediscount.go (1)
  • AmountLineDiscountManaged (108-111)
openmeter/billing/worker/subscription/invoiceupdate.go (1)
openmeter/billing/invoice.go (1)
  • InvoiceStatusGathering (74-74)
openmeter/billing/service/lineservice/pricevolumetiered_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
test/billing/adapter_test.go (4)
openmeter/billing/invoiceline.go (2)
  • Period (53-56)
  • Line (233-244)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
  • DetailedLineBase (43-69)
pkg/models/model.go (4)
  • ManagedResource (23-31)
  • NewManagedResource (75-97)
  • ManagedResourceInput (45-53)
  • ManagedModelWithID (179-182)
openmeter/billing/invoicelinediscount.go (5)
  • AmountLineDiscountsManaged (157-157)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
  • AmountLineDiscountManaged (108-111)
openmeter/billing/app.go (3)
openmeter/billing/invoiceline.go (1)
  • Lines (559-559)
openmeter/billing/service/lineservice/service.go (1)
  • Lines (211-211)
openmeter/billing/invoicedetailedline.go (1)
  • DetailedLines (166-166)
test/billing/ubpflatfee_test.go (1)
openmeter/billing/invoicedetailedline.go (1)
  • DetailedLines (166-166)
openmeter/billing/service/lineservice/service.go (4)
openmeter/productcatalog/price.go (2)
  • Price (94-101)
  • FlatPriceType (49-49)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/totals.go (1)
  • Totals (9-26)
pkg/slicesx/map.go (1)
  • Map (8-21)
openmeter/billing/invoicelinediscount.go (2)
pkg/models/validator.go (1)
  • Validate (16-26)
pkg/slicesx/empty.go (1)
  • EmptyAsNil (6-11)
openmeter/productcatalog/price.go (2)
api/api.gen.go (1)
  • PaymentTermType (5800-5800)
pkg/models/validator.go (1)
  • Validate (16-26)
openmeter/billing/adapter/invoicelinediff.go (5)
pkg/entitydiff/parent.go (3)
  • EqualerNestedEntity (18-21)
  • NestedEntity (5-8)
  • NewEqualersWithParent (35-42)
openmeter/billing/invoiceline.go (1)
  • Line (233-244)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLine (121-126)
  • DetailedLines (166-166)
  • DetailedLineBase (43-69)
pkg/entitydiff/diff.go (5)
  • Diff (29-33)
  • DiffByID (184-213)
  • DiffByIDInput (169-176)
  • DiffUpdate (16-21)
  • Entity (11-14)
pkg/slicesx/slice.go (1)
  • SliceToPtrSlice (5-9)
openmeter/billing/service/invoicecalc/gatheringrealtime.go (1)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/invoice_test.go (3)
openmeter/billing/invoiceline.go (3)
  • Lines (559-559)
  • LineBase (98-125)
  • Period (53-56)
pkg/models/model.go (3)
  • ManagedResource (23-31)
  • NewManagedResource (75-97)
  • ManagedResourceInput (45-53)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLineBase (43-69)
test/billing/discount_test.go (1)
openmeter/billing/invoicedetailedline.go (1)
  • DetailedLines (166-166)
openmeter/billing/service/lineservice/pricepackage_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
openmeter/billing/service/lineservice/pricegraduatedtiered_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
openmeter/billing/service/invoice.go (1)
openmeter/ent/db/billinginvoiceline/where.go (1)
  • DeletedAt (87-89)
openmeter/billing/adapter/invoicelinemapper.go (5)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
  • DetailedLineBase (43-69)
pkg/slicesx/map.go (1)
  • MapWithErr (25-49)
openmeter/ent/schema/billing.go (5)
  • BillingInvoiceLine (317-319)
  • BillingInvoiceLine (321-328)
  • BillingInvoiceLine (330-428)
  • BillingInvoiceLine (430-440)
  • BillingInvoiceLine (442-483)
pkg/models/model.go (3)
  • ManagedResource (23-31)
  • NewManagedResource (75-97)
  • ManagedResourceInput (45-53)
pkg/convert/time.go (1)
  • TimePtrIn (5-10)
openmeter/billing/httpdriver/invoiceline.go (5)
pkg/slicesx/map.go (1)
  • MapWithErr (25-49)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
api/api.gen.go (16)
  • InvoiceDetailedLine (3982-4071)
  • InvoiceLineDiscounts (4373-4383)
  • InvoiceLineStatusDetailed (430-430)
  • InvoiceLineManagedBySystem (425-425)
  • Invoice (3815-3929)
  • Period (5813-5819)
  • TaxConfig (7360-7372)
  • PricePaymentTerm (6186-6186)
  • RateCard (6233-6235)
  • InvoiceDetailedLineRateCard (4081-4097)
  • Price (6180-6182)
  • FlatPriceWithPaymentTerm (3671-3681)
  • Discounts (2462-2468)
  • InvoiceLineStatusValid (432-432)
  • InvoiceLineAmountDiscount (4260-4284)
  • InvoiceLineUsageDiscount (4485-4514)
openmeter/billing/invoice.go (2)
  • Invoice (330-341)
  • InvoiceID (214-214)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountsManaged (157-157)
  • AmountLineDiscountManaged (108-111)
  • UsageLineDiscountsManaged (325-325)
  • UsageLineDiscountManaged (274-277)
openmeter/billing/invoice.go (2)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/invoiceline.go (2)
  • Lines (559-559)
  • Line (233-244)
openmeter/billing/worker/subscription/sync_test.go (2)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/invoiceline.go (2)
  • Lines (559-559)
  • Line (233-244)
openmeter/billing/service/lineservice/priceunit_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
openmeter/billing/adapter/invoicelines.go (6)
openmeter/billing/invoicelinetypes.go (4)
  • InvoiceLineStatusValid (25-25)
  • InvoiceLineTypeUsageBased (10-10)
  • InvoiceLineStatusDetailed (27-27)
  • InvoiceLineTypeFee (8-8)
openmeter/ent/schema/billing.go (8)
  • BillingInvoiceFlatFeeLineConfig (485-487)
  • BillingInvoiceFlatFeeLineConfig (489-494)
  • BillingInvoiceFlatFeeLineConfig (496-513)
  • BillingInvoiceLineDiscount (689-691)
  • BillingInvoiceLineDiscount (693-700)
  • BillingInvoiceLineDiscount (702-749)
  • BillingInvoiceLineDiscount (751-760)
  • BillingInvoiceLineDiscount (762-770)
openmeter/billing/invoiceline.go (1)
  • SystemManagedLine (37-37)
pkg/entitydiff/diff.go (1)
  • Entity (11-14)
openmeter/ent/db/billinginvoicelinediscount.go (2)
  • BillingInvoiceLineDiscount (19-63)
  • BillingInvoiceLineDiscount (86-105)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/billing/invoicedetailedline.go (6)
pkg/models/validator.go (1)
  • Validate (16-26)
pkg/models/model.go (1)
  • ManagedResource (23-31)
openmeter/productcatalog/price.go (1)
  • PaymentTermType (24-24)
openmeter/billing/invoiceline.go (2)
  • Period (53-56)
  • LineExternalIDs (225-227)
openmeter/billing/totals.go (1)
  • Totals (9-26)
openmeter/billing/invoicelinediscount.go (1)
  • AmountLineDiscountsManaged (157-157)
openmeter/billing/invoiceline.go (4)
openmeter/ent/db/billinginvoiceline/where.go (5)
  • ChildUniqueReferenceID (178-180)
  • ID (17-19)
  • CreatedAt (77-79)
  • UpdatedAt (82-84)
  • Amount (108-110)
openmeter/ent/db/billinginvoicelinediscount/where.go (5)
  • ChildUniqueReferenceID (96-98)
  • ID (16-18)
  • CreatedAt (76-78)
  • UpdatedAt (81-83)
  • Amount (111-113)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/invoicelinediscount.go (1)
  • ReuseIDsFrom (431-473)
openmeter/billing/service/lineservice/pricedynamic_test.go (2)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountManaged (108-111)
  • AmountLineDiscount (60-68)
  • LineDiscountBase (22-27)
  • LineMaximumSpendReferenceID (19-19)
openmeter/billing/discount.go (2)
  • NewDiscountReasonFrom (154-191)
  • MaximumSpendDiscount (145-145)
test/billing/invoice_test.go (6)
openmeter/productcatalog/price.go (2)
  • Price (94-101)
  • FlatPriceType (49-49)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
  • FlatFeeCategoryCommitment (24-24)
openmeter/billing/totals.go (1)
  • Totals (9-26)
openmeter/billing/invoiceline.go (1)
  • Lines (559-559)
openmeter/billing/invoice.go (1)
  • Invoice (330-341)
openmeter/billing/invoicelinediscount.go (1)
  • AmountLineDiscountManaged (108-111)
openmeter/billing/service/lineservice/detailedlines.go (5)
openmeter/billing/invoicelinediscount.go (2)
  • AmountLineDiscountsManaged (157-157)
  • AmountLineDiscountManaged (108-111)
openmeter/billing/invoiceline.go (1)
  • Line (233-244)
openmeter/billing/invoicedetailedline.go (3)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
  • DetailedLineBase (43-69)
pkg/slicesx/map.go (1)
  • MapWithErr (25-49)
openmeter/billing/totals.go (1)
  • Totals (9-26)
🔇 Additional comments (37)
openmeter/billing/service/lineservice/usagebasedline_test.go (1)

197-209: LGTM: tests updated to AmountDiscounts with correct Reason and child reference.

The expected structures match the new discount model and keep rounding-centered invariants intact.

Also applies to: 223-235, 249-261, 275-287

openmeter/billing/invoicelinetypes.go (1)

13-18: Minor: Values helpers are fine as-is.

No issues; keep until the deprecation removal.

Also applies to: 30-35

openmeter/billing/invoicelinediscount.go (2)

221-223: ID reuse convenience on AmountLineDiscountsManaged.

Nice wrapper over generic ReuseIDsFrom; keeps callers clean.


413-417: Signature change verified and complete.

All ReuseIDsFrom variants now return only the data type without error:

  • Line 221 (AmountLineDiscountsManaged method)
  • Line 413 (LineDiscounts method—under review)
  • Line 431 (generic function)

The sole external call site at openmeter/billing/invoiceline.go:551 is correctly updated without error handling. No leftover error-handling patterns detected.

openmeter/billing/service/invoice.go (2)

1001-1005: Verify whether filtering by line status is intentional or if it should be re-introduced at the service layer.

The concern about widening the validation scope appears valid, but verification reveals a structural constraint: the Line struct in Go doesn't expose a Status field at the service layer (only the database adapter uses StatusEQ/StatusIn filters). The current checkIfLinesAreInvoicable filters only by DeletedAt == nil.

No test files were found that validate this filtering behavior, making it impossible to confirm whether this change is intentional or represents a regression. You should verify:

  • Did this PR intentionally remove status-based filtering from the validation scope?
  • Should status filtering be re-introduced (and if so, the Status field would need to be exposed in the Line struct)?

If status filtering should be retained, consider centralizing this logic (e.g., via LineService.IsBillableCandidate() as suggested in the original comment) rather than duplicating filter logic across call sites.


156-160: Verify all code paths maintain the Valid+!Deleted invariant after status filter removal.

The original concern has partial validity. While the database query at line 132 still enforces Statuses: [InvoiceLineStatusValid] before the in-memory DeletedAt filter is applied at lines 156–160, the removal of the in-memory status check creates fragility during the stated deprecation of InvoiceLineStatus.

Key findings:

  • The type is marked deprecated (invoicelinetypes.go:20) with removal planned
  • Database-level status filters persist at lines 132 and 597, but in-memory checks no longer validate status
  • The code comment at linebase.go:48 documents expectation of "lines with status Valid"
  • FromEntities is called in multiple contexts (lines 156, 557, 605)—line 557's inScopeLines source is unverified

Action items:

  1. Verify that ResolveInScopeLines (adapter call at line 551) maintains the Valid+!Deleted invariant for line 557's FromEntities call
  2. Confirm no other code paths bypass status filtering before invoking FromEntities
  3. If status deprecation is intentional, add explicit defensive checks or update code comments to clarify the expected invariant
openmeter/billing/service/lineservice/discountpercentage.go (1)

39-39: LGTM! Clean refactor to AmountDiscounts.

The change from nested Discounts.Amount to direct AmountDiscounts aligns with the new DetailedLine-based data model while preserving the discount application logic.

openmeter/productcatalog/price.go (1)

40-46: LGTM! Good defensive validation.

The new Validate() method ensures PaymentTermType values are constrained to the allowed set. This is consistent with validation patterns used elsewhere (e.g., TieredPriceMode validation at line 641) and helps catch invalid payment terms early in the DetailedLine data flow.

openmeter/billing/service/lineservice/pricegraduatedtiered_test.go (1)

283-294: LGTM! Test data correctly updated to AmountDiscounts.

The test expectations now use AmountDiscounts []billing.AmountLineDiscountManaged instead of the nested Discounts wrapper, correctly aligning with the new DetailedLine-based data model while preserving the same discount amounts and metadata.

Also applies to: 302-313

openmeter/billing/service/lineservice/pricepackage_test.go (1)

243-254: LGTM! Consistent with other test updates.

The test data structure update matches the pattern used in pricegraduatedtiered_test.go and correctly represents the maximum spend discount using the new AmountDiscounts field.

openmeter/billing/service/invoicecalc/gatheringrealtime.go (1)

17-31: LGTM! Straightforward refactor to DetailedLines.

The change from line.Children to line.DetailedLines with type billing.DetailedLine preserves the same initialization logic (ID, CreatedAt, UpdatedAt) while aligning with the new hierarchical data model.

openmeter/billing/worker/subscription/handlers.go (1)

50-58: No issues found. The status check removal is intentional and properly handled.

The change is part of commit dfcf3f6 ("refactor: split detailed line type") where the Status field was removed from the Line type entirely. Tests confirm that deleted lines are intentionally preserved through the sync process with period updates. Lines with DeletedAt are properly managed in the subscription sync flow.

openmeter/billing/service/invoicecalc/period.go (1)

10-12: ** - No Status.Valid check exists for lines**

The review comment's premise is incorrect. There is no evidence of a Status.Valid check being replaced by DeletedAt filtering in period.go.

Verification findings:

  • No Status field exists on Line, DetailedLine, or LineBase structs
  • ManagedResource (the base model) has no Status field
  • Status.Valid references in the codebase are only for Invoice/CreditNote status, not lines
  • InvoiceLineStatus type exists but is marked deprecated for removal
  • The current period.go code (lines 10-12) only filters by DeletedAt—this is the only filtering logic present
  • Git history shows period.go has consistently used DeletedAt filtering

The code change shown is not replacing a Status.Valid check; it's the actual implementation of period calculation filtering. All lines without a Status field, and the filtering mechanism has always been based on DeletedAt, not a line's status.

Likely an incorrect or invalid review comment.

test/billing/discount_test.go (4)

160-166: DetailedLines and AmountDiscounts migration looks correct.
Indexes guarded by Len checks; aligns with new model.


363-363: Assertion matches intent.
No detailed lines expected when no usage; good.


405-409: Quantity assertion on DetailedLine is consistent.
Single detailed line with quantity 15; OK.


437-439: Final invoice detailed line check LGTM.
Single detailed line with quantity 30; OK.

openmeter/billing/service/lineservice/pricevolumetiered_test.go (1)

397-409: Correct refactor to AmountDiscounts.
Structure and reason wiring for maximum spend are accurate.

openmeter/billing/app.go (1)

227-230: Hard requirement on expanded lines — confirm all callers comply.
Returning an error when Lines are not expanded changes behavior. Ensure all Upsert/Sync paths fetch with ExpandAll before merge, or degrade to no‑op merge.

test/billing/tax_test.go (1)

261-266: LGTM on DetailedLines tax propagation.

Switch to DetailedLines and asserting TaxConfig on the child is correct and matches the parent line.

openmeter/billing/worker/subscription/sync_test.go (1)

4134-4138: LGTM on discount check migration.

Validating child.AmountDiscounts on DetailedLine after refactor is correct and improves specificity.

openmeter/billing/adapter/invoicelines.go (1)

83-86: Hard-coding Status and Type for parent lines.

You unconditionally set Status=valid and Type=usage_based. Verify this matches the intended contract; otherwise you may overwrite legitimate states from callers.

Do we want to preserve incoming Status/Type if provided and valid?

test/billing/invoice_test.go (4)

1857-1868: LGTM: external ID propagation for detailed lines and discounts is verified.

Good coverage of child IDs and discount external IDs through upsert/finalize flows.

Also applies to: 1985-2031, 2047-2149, 2142-2151


1650-1650: LGTM: totals assertion on first detailed line.

Validates DetailedLines totals independently from line totals.


3450-3454: LGTM: zero-price path asserts a single detailed line with zero total and non-zero quantity.


3844-3875: LGTM: sort stability for DetailedLines by Index.

Shuffling + SortLines validates deterministic ordering and commitment last invariant.

openmeter/billing/httpdriver/invoiceline.go (2)

266-271: LGTM: children now map from DetailedLines with invoiceAt propagated from parent.


181-241: No issues found — hardcoding FlatFee type is correct.

Verification confirms the API enum InvoiceDetailedLineType supports only InvoiceDetailedLineTypeFlatFee. Since this is the sole available type, hardcoding it in the mapping function is the correct approach and requires no changes.

openmeter/billing/invoice.go (2)

453-459: LGTM: delegate sorting to Lines.Sort().

Cleaner and consistent with new Lines type.


461-473: LGTM: InvoiceLines wraps Lines with Option and adds Sort().

API surface matches the refactor; NewInvoiceLines correctly wraps children.

Also applies to: 525-533

openmeter/billing/service/lineservice/detailedlines.go (2)

179-193: LGTM: index assignment and ID reuse.

Index is persisted deterministically and ID reuse is delegated; looks correct.


195-224: LGTM: totals computation per-detailed-line.

Totals use rounded amount, per-category routing, and discount sum; placeholder taxes acknowledged.

openmeter/billing/invoiceline.go (4)

404-431: LGTM: stable sort for DetailedLines.

Deterministic by Index, then Name, then ServicePeriod, then ID; matches expectations.


513-557: LGTM: DetailedLinesWithIDReuse keeps IDs and timestamps; discounts reuse IDs too.

Solid approach to avoid churn and preserve history.


590-609: LGTM: Lines.Sort with secondary sort on period and ID; also sorts DetailedLines.

Looks deterministic and clear.


611-632: LGTM: external discount IDs propagation (line‑level).

Straightforward and side‑effect minimal.

openmeter/billing/invoicedetailedline.go (1)

92-94: PaymentTermType implements Validate() — code is correct as-is.

PaymentTermType has a Validate() error method defined at openmeter/productcatalog/price.go:40. The call at lines 92-94 is valid; no changes needed.

Likely an incorrect or invalid review comment.

Comment thread openmeter/billing/invoice.go Resolved
Comment thread openmeter/billing/invoiceline.go Resolved
Comment thread openmeter/billing/invoiceline.go Resolved
Comment thread pkg/slicesx/slice.go Resolved
Comment thread test/billing/suite.go Resolved
@turip
turip merged commit ee91abb into main Oct 17, 2025
@turip
turip deleted the refactor/split-detailed-line-type branch October 17, 2025 12:24

@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: 0

♻️ Duplicate comments (2)
openmeter/billing/service/lineservice/service.go (2)

76-85: Nil-deref risk: guard UsageBased and Price before calling Type().

The existing critical issue flagged in previous reviews is still present. Calling line.UsageBased.Price.Type() without checking if line.UsageBased or line.UsageBased.Price is nil will cause a panic. Please apply the suggested fix from the previous review or add appropriate nil guards before accessing these fields.


148-159: Hoist parent DeletedAt check before processing detailed lines.

The existing major issue flagged in previous reviews is still present. The function should check if line.DeletedAt is non-nil and return early before iterating over detailed lines. Please apply the suggested fix from the previous review.

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

153-156: Consider including the detailed line index in the error message.

For easier debugging, include the idx in the error message to identify which detailed line failed the totals calculation.

Apply this diff to improve the error message:

 		totals, err := calculateDetailedLineTotals(detailedLine)
 		if err != nil {
-			return fmt.Errorf("updating totals for line[%s]: %w", line.ID, err)
+			return fmt.Errorf("updating totals for line[%s] detailedLine[%d]: %w", line.ID, idx, err)
 		}
openmeter/billing/httpdriver/invoiceline.go (1)

266-268: Update error message for consistency.

The field was renamed from Children to DetailedLines, but the error message still references "children."

Apply this diff:

-	children, err := mapDetailedLinesToAPI(line.DetailedLines, line.InvoiceAt)
 	if err != nil {
-		return api.InvoiceLine{}, fmt.Errorf("failed to map children: %w", err)
+		return api.InvoiceLine{}, fmt.Errorf("failed to map detailed lines: %w", err)
 	}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dfcf3f6 and e5e7160.

📒 Files selected for processing (2)
  • openmeter/billing/httpdriver/invoiceline.go (7 hunks)
  • openmeter/billing/service/lineservice/service.go (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-04-21T08:32:31.689Z
Learnt from: chrisgacsal
PR: openmeterio/openmeter#2699
File: openmeter/productcatalog/planaddon/service/service_test.go:210-211
Timestamp: 2025-04-21T08:32:31.689Z
Learning: In `productcatalog.UsageBasedRateCard`, the `BillingCadence` field is a non-pointer `isodate.Period`, while in `productcatalog.FlatFeeRateCard`, `BillingCadence` is a pointer type (`*isodate.Period`). This means `MonthPeriod` should be used directly for `UsageBasedRateCard` (not `&MonthPeriod`).

Applied to files:

  • openmeter/billing/service/lineservice/service.go
🧬 Code graph analysis (2)
openmeter/billing/service/lineservice/service.go (3)
openmeter/productcatalog/price.go (2)
  • Price (94-101)
  • FlatPriceType (49-49)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
openmeter/billing/totals.go (1)
  • Totals (9-26)
openmeter/billing/httpdriver/invoiceline.go (7)
openmeter/billing/invoiceline.go (2)
  • Lines (559-559)
  • Period (53-56)
pkg/slicesx/map.go (1)
  • MapWithErr (25-49)
openmeter/billing/invoicedetailedline.go (2)
  • DetailedLines (166-166)
  • DetailedLine (121-126)
api/api.gen.go (14)
  • InvoiceDetailedLine (3982-4071)
  • InvoiceLineDiscounts (4373-4383)
  • InvoiceLineStatusDetailed (430-430)
  • InvoiceLineManagedBySystem (425-425)
  • Invoice (3815-3929)
  • Period (5813-5819)
  • PricePaymentTerm (6186-6186)
  • RateCard (6233-6235)
  • InvoiceDetailedLineRateCard (4081-4097)
  • Price (6180-6182)
  • Discounts (2462-2468)
  • InvoiceLineStatusValid (432-432)
  • InvoiceLineAmountDiscount (4260-4284)
  • InvoiceLineUsageDiscount (4485-4514)
openmeter/billing/invoicelinetypes.go (2)
  • InvoiceLineStatusDetailed (27-27)
  • InvoiceLineStatusValid (25-25)
openmeter/billing/invoice.go (1)
  • Invoice (330-341)
openmeter/billing/invoicelinediscount.go (4)
  • AmountLineDiscountsManaged (157-157)
  • AmountLineDiscountManaged (108-111)
  • UsageLineDiscountsManaged (325-325)
  • UsageLineDiscountManaged (274-277)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Code Generators
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
openmeter/billing/service/lineservice/service.go (1)

170-177: LGTM: Proper handling of deleted detailed lines in aggregation.

The totals aggregation correctly excludes deleted detailed lines by checking DeletedAt and returning an empty Totals{} struct for those entries.

openmeter/billing/httpdriver/invoiceline.go (4)

7-7: LGTM: Import and mapping simplification.

The time import supports the new signature requiring explicit invoiceAt timestamps, and reusing mapInvoiceLineToAPI at line 100 removes duplication.

Also applies to: 100-100


170-179: LGTM: Clean detailed lines mapper.

The function correctly threads the invoiceAt timestamp to each detailed line mapping and handles errors appropriately.


181-240: LGTM: Detailed line mapping correctly reflects new type structure.

The function appropriately:

  • Takes invoiceAt as an explicit parameter since DetailedLine no longer carries it
  • Maps only AmountDiscounts (consistent with DetailedLine having only that field)
  • Uses ServicePeriod instead of Period
  • Sets system-managed fields (Status, ManagedBy) correctly

356-434: LGTM: Clean discount mapping separation.

The refactor into separate mapInvoiceLineAmountDiscountsToAPI and mapInvoiceLineUsageDiscountsToAPI functions improves maintainability. Error messages are now accurate for each discount type, and the past review comment about the misleading error message has been addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing kind/refactor Code refactor, cleanup or minor improvement release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants