Repository navigation
feat: capture invoice snapshot date - #2829
Conversation
📝 WalkthroughWalkthroughA new optional timestamp field, Changes
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 Note ⚡️ AI Code Reviews for VS Code, Cursor, WindsurfCodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback. Note ⚡️ Faster reviews with cachingCodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure ✨ 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 (4)
openmeter/billing/service/invoiceline.go (1)
356-356: Good use of UTC for timestamp consistency in billing data.Setting
QuantitySnapshotedAtto UTC time after snapshotting all line quantities ensures consistent timestamp storage, which is important for billing data that may be used across different time zones.Consider standardizing UTC usage across all timestamp assignments. In
invoice.go, there's a similar assignment that usesclock.Now()without explicit UTC conversion:-invoice.QuantitySnapshotedAt = lo.ToPtr(now) +invoice.QuantitySnapshotedAt = lo.ToPtr(now.UTC())api/spec/src/billing/invoices/invoice.tsp (1)
141-146: Add read-only snapshot timestamp: The newquantitySnapshotedAtfield is correctly introduced with@visibility(Lifecycle.Read)and a clear description. Please verify that the corresponding OpenAPI specs (api/openapi.yaml,api/openapi.cloud.yaml) and the JavaScript client schema have been updated to include this property.
Minor nit: consider whether “quantitySnapshotedAt” is the most intuitive name (e.g.,quantitySnapshotAtorquantitySnapshotTakenAt) for consistency and readability.api/openapi.cloud.yaml (1)
15318-15323: Consider nullability for invoices without snapshots.
If invoices in the gathering state should explicitly returnnullinstead of omitting the field, consider marking the property as nullable. For example:quantitySnapshotedAt: + nullable: true type: string format: date-time description: The time when the quantity snapshots on the invoice lines were taken. example: '2023-01-01T01:01:01.001Z' readOnly: trueapi/openapi.yaml (1)
15428-15433: Explicitly allow null forquantitySnapshotedAtand sync cloud spec
The new read-onlyquantitySnapshotedAtfield is correctly defined, but since it won’t be set for gathering-state invoices, consider marking it asnullable: trueto explicitly allow null values. Also verify that this property has been added toapi/openapi.cloud.yamlto keep both API specs in sync.Proposed diff:
quantitySnapshotedAt: type: string format: date-time + nullable: true description: The time when the quantity snapshots on the invoice lines were taken. example: '2023-01-01T01:01:01.001Z' readOnly: true
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (21)
api/client/javascript/src/client/schemas.ts(1 hunks)api/openapi.cloud.yaml(1 hunks)api/openapi.yaml(1 hunks)api/spec/src/billing/invoices/invoice.tsp(1 hunks)openmeter/billing/adapter/invoice.go(2 hunks)openmeter/billing/httpdriver/invoice.go(1 hunks)openmeter/billing/invoice.go(1 hunks)openmeter/billing/service/invoice.go(1 hunks)openmeter/billing/service/invoiceline.go(2 hunks)openmeter/ent/db/billinginvoice.go(4 hunks)openmeter/ent/db/billinginvoice/billinginvoice.go(3 hunks)openmeter/ent/db/billinginvoice/where.go(2 hunks)openmeter/ent/db/billinginvoice_create.go(5 hunks)openmeter/ent/db/billinginvoice_update.go(4 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(10 hunks)openmeter/ent/db/runtime.go(1 hunks)openmeter/ent/db/setorclear.go(1 hunks)openmeter/ent/schema/billing.go(2 hunks)tools/migrate/migrations/20250516090128_billing-invoice-snapshotted-at.down.sql(1 hunks)tools/migrate/migrations/20250516090128_billing-invoice-snapshotted-at.up.sql(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (10)
openmeter/billing/service/invoice.go (1)
openmeter/ent/db/billinginvoice/where.go (1)
QuantitySnapshotedAt(255-257)
openmeter/billing/service/invoiceline.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
QuantitySnapshotedAt(255-257)pkg/clock/clock.go (1)
Now(14-21)
openmeter/billing/httpdriver/invoice.go (3)
openmeter/ent/db/billinginvoice/where.go (9)
CreatedAt(78-80)UpdatedAt(83-85)DeletedAt(88-90)IssuedAt(240-242)VoidedAt(235-237)DueAt(266-268)DraftUntil(250-252)SentToCustomerAt(245-247)QuantitySnapshotedAt(255-257)openmeter/billing/invoiceline.go (1)
Period(83-86)api/api.gen.go (1)
Period(5433-5439)
openmeter/billing/invoice.go (1)
openmeter/ent/db/billinginvoice/where.go (8)
CreatedAt(78-80)UpdatedAt(83-85)VoidedAt(235-237)DraftUntil(250-252)IssuedAt(240-242)DeletedAt(88-90)SentToCustomerAt(245-247)QuantitySnapshotedAt(255-257)
openmeter/ent/db/migrate/schema.go (1)
openmeter/ent/db/billinginvoice/billinginvoice.go (1)
Columns(204-260)
openmeter/billing/adapter/invoice.go (3)
pkg/convert/ptr.go (1)
SafeToUTC(36-40)openmeter/ent/db/billinginvoice/where.go (9)
QuantitySnapshotedAt(255-257)ID(18-20)Namespace(73-75)Currency(260-263)Number(215-217)Description(220-222)DueAt(266-268)DraftUntil(250-252)SentToCustomerAt(245-247)pkg/convert/time.go (1)
TimePtrIn(5-10)
openmeter/ent/db/setorclear.go (1)
openmeter/ent/db/billinginvoice_update.go (2)
BillingInvoiceUpdate(25-29)BillingInvoiceUpdateOne(1398-1403)
openmeter/ent/db/billinginvoice/where.go (3)
openmeter/ent/schema/billing.go (5)
BillingInvoice(699-701)BillingInvoice(703-718)BillingInvoice(720-853)BillingInvoice(855-867)BillingInvoice(869-911)openmeter/ent/db/predicate/predicate.go (1)
BillingInvoice(65-65)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldQuantitySnapshotedAt(98-98)
openmeter/ent/db/billinginvoice_update.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
QuantitySnapshotedAt(255-257)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldQuantitySnapshotedAt(98-98)
openmeter/ent/db/billinginvoice_create.go (2)
openmeter/ent/db/billinginvoice/where.go (1)
QuantitySnapshotedAt(255-257)openmeter/ent/db/billinginvoice/billinginvoice.go (1)
FieldQuantitySnapshotedAt(98-98)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Analyze (go)
🔇 Additional comments (43)
tools/migrate/migrations/20250516090128_billing-invoice-snapshotted-at.down.sql (1)
1-2: The down migration is correctly implemented.The SQL statement properly drops the
quantity_snapshoted_atcolumn from thebilling_invoicestable, providing a clean rollback path for the feature.openmeter/billing/service/invoice.go (1)
160-161: Recording snapshot timestamp before calculation is a good approach.Setting
QuantitySnapshotedAtat this point ensures the timestamp accurately reflects when invoice quantities were captured, just before the invoice calculations are performed.openmeter/billing/invoice.go (1)
282-282: New timestamp field properly follows established conventions.The
QuantitySnapshotedAtfield is correctly defined as a pointer type consistent with other optional timestamp fields, includes appropriate JSON tags withomitempty, and is well-placed among related timestamp fields.api/openapi.cloud.yaml (1)
15318-15323: Schema addition looks correct.
The newquantitySnapshotedAtproperty is well-defined as a read-only date-time field with a clear description and example, accurately capturing when invoice line quantities were snapshotted.api/client/javascript/src/client/schemas.ts (1)
5193-5198:Details
❓ Verification inconclusive
Confirm
quantitySnapshotedAtconsistency and mapping
The new optionalquantitySnapshotedAt?: Dateproperty is correctly defined with matching JSDoc. Please ensure that:
- The spelling and casing of this field exactly match the OpenAPI specs (
api/openapi.yaml&api/openapi.cloud.yaml) and the backend model.- The client-side JSON→TS transformer (mapper) handles this new
date-timefield and converts the incoming ISO string into aDateobject.
🏁 Script executed:
#!/usr/bin/env bash # Verify consistency of 'quantitySnapshotedAt' across specs and client code rg -n "quantitySnapshotedAt" api/openapi.yaml api/openapi.cloud.yaml api/client/javascript/src/clientLength of output: 305
🏁 Script executed:
#!/usr/bin/env bash # Show the surrounding interface and mapper for `quantitySnapshotedAt` sed -n '5170,5230p' api/client/javascript/src/client/schemas.tsLength of output: 2831
Confirm JSON→TS mapping for
quantitySnapshotedAt
We’ve verified thatquantitySnapshotedAtis defined in bothapi/openapi.yamlandapi/openapi.cloud.yaml(lines 15428/15318) and inapi/client/javascript/src/client/schemas.ts. Please double-check that your JSON→TS transformer (mapper) includes this field and converts the incoming ISO string into aDate, for example:// in your Invoice mapper quantitySnapshotedAt: raw.quantitySnapshotedAt ? new Date(raw.quantitySnapshotedAt) : undefined,
- If you use a generic date mapping utility, ensure it’s applied to this new property.
- If you hand-roll mappers for each schema, add the above line to the Invoice mapper.
openmeter/billing/httpdriver/invoice.go (1)
491-499: LGTM: The new timestamp field is correctly added to the API response.The addition of
QuantitySnapshotedAtfield to the invoice API response is correctly implemented, maintaining consistency with other timestamp fields in the struct. This change properly exposes the new field that tracks when quantity snapshots on invoice lines were taken.openmeter/ent/schema/billing.go (1)
775-778: LGTM: New field properly defined in the database schema.The addition of the
quantity_snapshoted_atfield to theBillingInvoiceschema is correctly implemented. The field is appropriately defined as optional and nullable, which is suitable for a timestamp that might not be set for all invoices. This aligns with the PR objective of capturing invoice quantity snapshot dates.openmeter/ent/db/runtime.go (1)
483-488: Index updates correctly reflect the new field addition.The modified indices for
billinginvoiceDescCurrencyandbillinginvoiceDescCollectionAtare necessary accommodations for the insertion of the newquantity_snapshoted_atfield in the schema. These adjustments ensure proper field descriptor mappings are maintained after the schema change.openmeter/billing/adapter/invoice.go (2)
455-455: Added proper handling for the new quantitySnapshotedAt field.The implementation correctly uses the
SetOrClearQuantitySnapshotedAtmethod withconvert.SafeToUTCto handle nullable timestamps. This ensures proper timezone handling when updating invoice data.
647-647: Added mapping for the new field in the response structure.The implementation correctly maps the database field to the domain model using
convert.TimePtrInwith UTC timezone, maintaining consistency with how other datetime fields are handled.tools/migrate/migrations/20250516090128_billing-invoice-snapshotted-at.up.sql (3)
1-3: Added nullable timestamp column for quantity snapshot tracking.The migration correctly adds
quantity_snapshoted_atas a nullable timestamp column, which is appropriate for an optional field.
4-9: Sensible backfill strategy for existing invoices.The migration includes a well-commented backfill strategy that sets
quantity_snapshoted_attocreated_atonly for non-gathering invoices. The comment clearly explains why gathering invoices are excluded from the backfill.
1-9:Details
✅ Verification successful
Verify consistent naming convention across the codebase.
I notice the field name uses "snapshoted" rather than "snapshotted" (with two 'p's). While either could be valid, ensure this spelling is used consistently throughout the codebase, documentation, and API.
🏁 Script executed:
#!/bin/bash # Check for consistency in spelling of "snapshoted" vs "snapshotted" across the codebase echo "Checking for 'snapshoted' usage:" rg -i "snapshoted" --type=go --type=sql --type=typescript --type=yaml echo -e "\nChecking for 'snapshotted' usage:" rg -i "snapshotted" --type=go --type=sql --type=typescript --type=yamlLength of output: 380
🏁 Script executed:
#!/bin/bash # Re-run spelling check without file-type filters to capture all occurrences echo "Searching for 'snapshoted' across all files..." rg -i "snapshoted" || echo "No matches for 'snapshoted'" echo -e "\nSearching for 'snapshotted' across all files..." rg -i "snapshotted" || echo "No matches for 'snapshotted'"Length of output: 24081
No inconsistencies found for the invoice field spelling
The column/field
quantity_snapshoted_atis spelled “snapshoted” everywhere in the invoice code paths (migrations, Ent schema, DB models, service, HTTP driver, OpenAPI spec and generated clients).
Occurrences of “snapshotted” appear only in the balance‐snapshot domain (e.g.SnapshottedUsage), which is a separate concept and not related to the invoice field. No changes required here.openmeter/ent/db/setorclear.go (1)
842-855: LGTM! Well-implemented field operations for the new quantity snapshot timestamp.The new
SetOrClearQuantitySnapshotedAtmethods for bothBillingInvoiceUpdateandBillingInvoiceUpdateOnefollow the established pattern in this file, properly handling nil values and maintaining the fluent interface pattern with appropriate return types. This implementation aligns well with the PR objective of capturing invoice snapshot dates.openmeter/ent/db/migrate/schema.go (3)
600-600: Well-integrated field addition to invoice schemaThe new nullable timestamp column
quantity_snapshoted_athas been properly added to theBillingInvoicesColumns. This field correctly aligns with the PR objective to capture the snapshot date of invoice quantities.
625-656: Foreign key indices correctly updatedThe foreign key references have been properly incremented to accommodate the new column position in the table. This ensures that all relationships are maintained correctly after adding the new field.
680-691: Index references correctly updatedThe index references have been appropriately adjusted to account for the insertion of the new field, ensuring that all indexes point to the correct columns after the schema change.
openmeter/ent/db/billinginvoice.go (4)
107-108: Field properly added to BillingInvoice structThe new
QuantitySnapshotedAtfield has been correctly added to the struct with proper documentation and JSON tags. This implementation matches the database schema change.
261-261: Field correctly added to scanValues handlerThe
QuantitySnapshotedAtfield has been appropriately added to the list of time fields in thescanValuesmethod, ensuring that it will be properly scanned from database results as asql.NullTime.
543-549: Assignment logic correctly implementedThe assignment logic for the new field has been properly implemented in the
assignValuesmethod, including type checking and validity checks. This ensures proper conversion from the database value to the struct field.
877-881: String representation appropriately updatedThe
String()method has been updated to include the string representation of the new field when it's non-nil, ensuring that the field is properly represented in string output.openmeter/ent/db/billinginvoice/billinginvoice.go (3)
97-98: Addition of new QuantitySnapshotedAt field constant.The new field constant is properly documented and follows the naming convention used throughout the codebase.
245-245: Adding QuantitySnapshotedAt to Columns array.Correctly adds the new field to the Columns slice to ensure it's recognized as a valid column for the entity.
514-517: Implementation of ByQuantitySnapshotedAt ordering function.The ordering function follows the same pattern as other field ordering functions, making the field available for sorting in queries.
openmeter/ent/db/billinginvoice_update.go (4)
635-653: Added setter and clearer methods for QuantitySnapshotedAt in BillingInvoiceUpdate.These methods provide the standard interface for setting, conditionally setting, and clearing the new timestamp field, following the same pattern as other fields.
1209-1214: Updated sqlSave to handle QuantitySnapshotedAt field changes.The implementation correctly handles both setting and clearing the field in SQL update operations.
2003-2021: Added setter and clearer methods for QuantitySnapshotedAt in BillingInvoiceUpdateOne.These methods follow the same pattern as in BillingInvoiceUpdate, maintaining consistency throughout the codebase.
2607-2612: Updated BillingInvoiceUpdateOne.sqlSave to handle QuantitySnapshotedAt field.The implementation properly handles both setting and clearing the field in SQL update operations for single entity updates.
openmeter/ent/db/mutation.go (10)
11431-11431: Field addition looks good.The new nullable timestamp field
quantity_snapshoted_atfollows the same pattern as other timestamp fields in the struct and is properly positioned within the field list.
13260-13307: Accessor methods are complete and follow established patterns.All necessary mutation methods for the new field have been implemented, following the same pattern as other timestamp fields:
- Setter and getter methods
- Old value retrieval with proper error handling
- Clear and reset functionality
- Status checking methods
These implementations maintain consistency with the codebase patterns.
14247-14247: Capacity adjustment is appropriate.The fields slice capacity was increased to accommodate the additional field.
14365-14367: Field collection logic looks good.The field is properly included in the Fields() method when it has been set.
14496-14497: Field accessor case added correctly.The new field case was added to the Field() method's switch statement.
14613-14614: Old field accessor case added correctly.The new field case was added to the OldField() method's switch statement.
14925-14931: Field setter case added with proper type checking.The SetField() method includes the new field with appropriate type checking to ensure the value is a time.Time.
15126-15128: Cleared field tracking is properly implemented.The field is correctly included in the list of cleared fields when appropriate.
15233-15235: Field clearing case added correctly.The new field case was added to the ClearField() method's switch statement.
15385-15387: Field reset case added correctly.The new field case was added to the ResetField() method's switch statement.
openmeter/ent/db/billinginvoice_create.go (4)
454-466: Properly implementedquantitySnapshotedAtfield setters for creation operations.The implementation correctly adds setter methods for the new
quantity_snapshoted_attimestamp field, following the established pattern in the codebase - one method for direct setting and another for conditionally setting non-nil values.
1078-1081: Correctly integrated field into SQL specification.The field is properly added to the SQL insert specification, which ensures it's correctly persisted to the database during entity creation.
1860-1876: Properly implemented upsert operations for the new field.The implementation follows the same pattern as other fields, adding the necessary methods for setting, updating, and clearing the
quantity_snapshoted_atfield during upsert operations.
3862-3881: Properly implemented bulk upsert operations for the new field.The implementation correctly adds support for the new field in bulk upsert operations, maintaining consistency with the existing pattern for other fields.
openmeter/ent/db/billinginvoice/where.go (1)
254-647: Implementation for new quantitySnapshotedAt field looks correct and follows established patterns.The added predicate functions for the
quantity_snapshoted_atfield follow the same pattern as other timestamp fields, providing a complete set of equality, comparison, inclusion, and null-checking operations that will enable flexible querying based on this new timestamp.
| quantitySnapshotedAt: | ||
| type: string | ||
| format: date-time | ||
| description: The time when the quantity snapshots on the invoice lines were taken. | ||
| example: '2023-01-01T01:01:01.001Z' | ||
| readOnly: true |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Ensure consistent inclusion across API specs.
Please verify that quantitySnapshotedAt is also present in the core api/openapi.yaml, client schemas, and any generated SDKs to maintain full parity.
Run this script from the repo root to confirm:
🏁 Script executed:
#!/bin/bash
# Verify that the field exists in all OpenAPI specs
rg -n "quantitySnapshotedAt" -C2 api/openapi*Length of output: 733
quantitySnapshotedAt present in core and cloud specs; update client SDKs
We’ve confirmed that quantitySnapshotedAt exists in both API specs:
api/openapi.yaml(line 15428)api/openapi.cloud.yaml(line 15318)
Next steps to maintain parity:
- Regenerate all client schemas and SDKs (e.g., via your standard codegen command).
- Inspect the generated models (e.g., the
InvoiceLinetype/interface) to ensurequantitySnapshotedAtis included.
No further spec changes are needed.
🤖 Prompt for AI Agents
In api/openapi.cloud.yaml around lines 15318 to 15323, the field
quantitySnapshotedAt is correctly defined and also present in the core
api/openapi.yaml at line 15428. To maintain parity, regenerate all client
schemas and SDKs using the standard code generation commands. After
regeneration, verify that the quantitySnapshotedAt field is included in the
generated models such as the InvoiceLine type or interface. No changes to the
spec files are needed.
| issued_at *time.Time | ||
| sent_to_customer_at *time.Time | ||
| draft_until *time.Time | ||
| quantity_snapshoted_at *time.Time |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify consistent spelling across the codebase.
The field name uses "snapshoted" (with one 't') rather than the more common spelling "snapshotted" (with two 't's). This appears to be a consistent choice across the codebase based on the PR summary, but it's worth confirming that this spelling is used consistently throughout all related changes.
Also applies to: 13260-13307
🏁 Script executed:
#!/bin/bash
# Check for consistent spelling of "snapshoted" vs "snapshotted" in the codebase
echo "Checking for spelling consistency across codebase..."
echo "Occurrences of 'snapshoted':"
rg -i "snapshoted" --type go --type sql
echo -e "\nOccurrences of 'snapshotted':"
rg -i "snapshotted" --type go --type sqlLength of output: 22990
Unify “snapshoted” vs. “snapshotted” spelling across the codebase
Your search shows two distinct spellings in use:
- “snapshoted” (one ‘t’) in billing-invoice code and DB migrations (
quantity_snapshoted_at,QuantitySnapshotedAt, etc.) - “snapshotted” (two ‘t’s) in balance-snapshot code and tests (
SnapshottedUsage,balance_snapshot, etc.)
This inconsistency can lead to confusion and bugs. Please pick one spelling (we recommend the correct “snapshotted”) and update all occurrences:
• Migration files under tools/migrate/migrations/*
• Go structs, JSON tags, and service code in openmeter/billing/...
• Ent schema and generated code under openmeter/ent/schema/… and openmeter/ent/db/... (column names, methods, predicates, mutations, etc.)
• API definitions in api/api.gen.go and api/client/go/client.gen.go
Renaming the DB column will require a new migration and adjustment of all references.
🤖 Prompt for AI Agents
In openmeter/ent/db/mutation.go at line 11431 and also in the range 13260-13307,
there is inconsistent spelling of the term "snapshoted" versus "snapshotted"
across the codebase. To fix this, choose the correct spelling "snapshotted" and
update all occurrences accordingly, including migration files under
tools/migrate/migrations, Go structs, JSON tags, service code in
openmeter/billing, ent schema and generated code under openmeter/ent/schema and
openmeter/ent/db, and API definitions in api/api.gen.go and
api/client/go/client.gen.go. This will require creating a new migration to
rename the database column and updating all references to maintain consistency
and avoid confusion.
Overview
Draft invoices have their quantities snapshotted during creation. This patch captures it into the invoice header for non-gathering invoices.
This will enable us to move the collection to the draft state.
Summary by CodeRabbit
New Features
Database
Bug Fixes
Chores