Repository navigation
fix(billing-sync): fix aligned line generation - #2982
Conversation
📝 WalkthroughWalkthroughThis change refines invoice timestamp validation, simplifies invoice date calculation for flat-fee items, and adjusts logic for aligned subscription billing and iteration. Test coverage is expanded to include both in-advance and in-arrears billing scenarios, and a test file for aligned billing period calculation is removed. Internal logic for determining billing periods is also updated. Changes
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 ✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (8)
openmeter/billing/worker/subscription/phaseiterator.go (2)
76-85: Comment typo & clarification inGetInvoiceAtMinor, but worth fixing to avoid leaking into generated docs:
- // For in advance invoicing we attempt to incoice at the start of the billing period + // For in-advance invoicing we attempt to invoice at the start of the billing period
283-289:invoiceAtboundary condition & loop structureThe “stop-when-past-iterationEnd” check uses
After, meaning a line whoseinvoiceAt == iterationEndwill still be emitted.
If the caller expects generation up-to and includingiterationEndthat’s fine; if the intention was strictly before the limit, change to!invAt.Before(iterationEnd)for clarity.Also, you calculate
newItem.GetInvoiceAt()twice – capture once to avoid extra work and keep logs consistent.- // Check if we have reached the iteration end based on invoiceAt - if newItem.GetInvoiceAt().After(iterationEnd) { + invAt := newItem.GetInvoiceAt() + // Stop once invoiceAt exceeds the iteration end + if invAt.After(iterationEnd) { logger.DebugContext(ctx, "exiting loop due to iteration end", slog.Time("at", at), slog.Time("iterationEnd", iterationEnd), slog.Time("invoiceAt", invAt)) break } - - *items = append(*items, newItem) + *items = append(*items, newItem)openmeter/subscription/subscriptionspec.go (1)
219-233: Error messages & early-period handling polish
- Two error strings have trailing commas – looks accidental and will read oddly in logs / client responses.
- return def, fmt.Errorf("phase %s is not active at %s, ", phaseKey, at) + return def, fmt.Errorf("phase %s is not active at %s", phaseKey, at)
at.Before(subCad.ActiveFrom)path returns an error, but a timestamp slightly beforeActiveFrom(e.g. customer tries to preview the first invoice) may be legitimate. Consider allowing a configurable “look-back” grace or documenting that consumers must always pass ≥ActiveFrom.(Not blocking but worth noting.)
openmeter/billing/worker/subscription/phaseiterator_test.go (2)
677-698: Table-row is becoming unwieldy – factor out a helper for mixed cadence scenariosThis block adds a third “mega” test case that mixes in-advance and in-arrears items.
The raw literal construction of the items slice already spans ~20 lines and the
correspondingexpectedslice further below is >100 lines long. Updating or
debugging this by hand will be painful and very error-prone.Consider introducing a small builder/helper that can produce:
func mkItem(key string, t productcatalog.PriceType, cad string, startAfter, endAfter *isodate.Period) subscriptionItemViewMockand another helper that builds an
expectedIterationsslice from start/end
timestamps plus a template format for theKey. That keeps each test row
focused on intent rather than on copy-pasted boilerplate and will localise any
future cadence logic changes to one place.
748-764: Expectation comment is code – assert itThe inline comment
// As we want to generate all in advance items invoicable by end time, we get an extra in advance itemis useful, but the assertion does not make that guarantee explicit.
A quick win is to add:s.Equal(4, lo.CountBy(outAsExpect, func(it expectedIterations) bool { return strings.Contains(it.Key, "item-key") }), "expected 4 in-advance periods")(or via a helper). That turns the rationale into a checked invariant and
guards against future regressions where the extra period accidentally
disappears.openmeter/billing/worker/subscription/sync_test.go (3)
1632-1683: Leverage the newgenerateSameNTimeshelper to reduce duplicationEight identical
InvoiceAttimestamps are manually listed here.
Now thatgenerateSameNTimesexists (see ~4105-4114), these four-line blocks can be collapsed into a single helper call, e.g.- InvoiceAt: []time.Time{ - s.mustParseTime("2024-01-01T00:00:00Z"), - s.mustParseTime("2024-01-01T00:00:00Z"), - s.mustParseTime("2024-01-01T00:00:00Z"), - s.mustParseTime("2024-01-01T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - }, + InvoiceAt: append( + s.generateSameNTimes("2024-01-01T00:00:00Z", 4), + s.generateSameNTimes("2024-01-29T00:00:00Z", 4)..., + ),This removes boilerplate, keeps the test intent clear, and avoids the risk of mismatching counts when periods change.
1710-1738: Same duplication pattern for in-arrears line – apply helper
InvoiceAtis repeated four times with the same value. Consider the same refactor as above:- InvoiceAt: []time.Time{ - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - s.mustParseTime("2024-01-29T00:00:00Z"), - }, + InvoiceAt: s.generateSameNTimes("2024-01-29T00:00:00Z", 4),This keeps the expectations DRY and consistent with the new helper.
4105-4114: Minor micro-optimisations ingenerateSameNTimesThe helper is neat, but we can eliminate unnecessary work inside tight loops:
- Parse the timestamp only once.
- Pre-allocate the slice capacity.
-func (s *SubscriptionHandlerTestSuite) generateSameNTimes(ts string, n int) []time.Time { - out := []time.Time{} - for n != 0 { - out = append(out, s.mustParseTime(ts)) - n-- - } - return out +func (s *SubscriptionHandlerTestSuite) generateSameNTimes(ts string, n int) []time.Time { + t := s.mustParseTime(ts) + out := make([]time.Time, n) + for i := 0; i < n; i++ { + out[i] = t + } + return out }Not critical for tests, but it’s a one-liner change that makes the helper both clearer and cheaper.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
openmeter/billing/invoiceline.go(0 hunks)openmeter/billing/worker/subscription/phaseiterator.go(2 hunks)openmeter/billing/worker/subscription/phaseiterator_test.go(6 hunks)openmeter/billing/worker/subscription/sync.go(1 hunks)openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/subscription/aligment_test.go(0 hunks)openmeter/subscription/subscriptionspec.go(1 hunks)
💤 Files with no reviewable changes (2)
- openmeter/billing/invoiceline.go
- openmeter/subscription/aligment_test.go
🧰 Additional context used
🧠 Learnings (1)
openmeter/billing/worker/subscription/sync_test.go (1)
undefined
<retrieved_learning>
Learnt from: chrisgacsal
PR: #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).
</retrieved_learning>
🧬 Code Graph Analysis (2)
openmeter/subscription/subscriptionspec.go (1)
pkg/models/cadence.go (1)
CadencedModel(21-25)
openmeter/billing/worker/subscription/sync.go (4)
api/api.gen.go (2)
Alignment(999-1003)SubscriptionPhase(6604-6637)openmeter/productcatalog/alignment.go (1)
Alignment(7-10)openmeter/ent/db/subscription/where.go (1)
BillablesMustAlign(101-103)openmeter/ent/schema/subscription.go (5)
SubscriptionPhase(82-84)SubscriptionPhase(86-93)SubscriptionPhase(95-104)SubscriptionPhase(106-112)SubscriptionPhase(114-123)
⏰ Context from checks skipped due to timeout of 90000ms (10)
- GitHub Check: Developer environment
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Lint
- GitHub Check: Migration Checks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
Overview
InvoiceAtforin-advanceitems so they get billed together at billing period start (potentially outside service period)Notes for reviewer
Summary by CodeRabbit
Bug Fixes
Tests
Refactor